From 38b53e5d07dea3210daad6ebf7c7f76998b5b6c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 13:33:38 +0300 Subject: [PATCH] U7: drop unlisted ec-h265 integration test modules and ec-h265-syntax sei_sweep (test bloat, no output change) --- crates/ec-h265-syntax/tests/sei_sweep.rs | 83 -- crates/ec-h265/tests/it/conformance.rs | 964 ------------------ crates/ec-h265/tests/it/conformance_intra.rs | 276 ----- crates/ec-h265/tests/it/conformance_rext.rs | 325 ------ .../ec-h265/tests/it/conformance_rext422.rs | 128 --- crates/ec-h265/tests/it/cu_syntax.rs | 130 --- crates/ec-h265/tests/it/dec_meta.rs | 244 ----- crates/ec-h265/tests/it/dec_shell.rs | 454 --------- crates/ec-h265/tests/it/dolby_vision_p8.rs | 197 ---- crates/ec-h265/tests/it/encode.rs | 922 ----------------- crates/ec-h265/tests/it/main.rs | 13 - crates/ec-h265/tests/it/rate_control.rs | 207 ---- crates/ec-h265/tests/it/rdoq_cache_hash.rs | 70 -- crates/ec-h265/tests/it/real_library.rs | 367 ------- crates/ec-h265/tests/it/scaling_lists.rs | 111 -- 15 files changed, 4491 deletions(-) delete mode 100644 crates/ec-h265-syntax/tests/sei_sweep.rs delete mode 100644 crates/ec-h265/tests/it/conformance.rs delete mode 100644 crates/ec-h265/tests/it/conformance_intra.rs delete mode 100644 crates/ec-h265/tests/it/conformance_rext.rs delete mode 100644 crates/ec-h265/tests/it/conformance_rext422.rs delete mode 100644 crates/ec-h265/tests/it/cu_syntax.rs delete mode 100644 crates/ec-h265/tests/it/dec_meta.rs delete mode 100644 crates/ec-h265/tests/it/dec_shell.rs delete mode 100644 crates/ec-h265/tests/it/dolby_vision_p8.rs delete mode 100644 crates/ec-h265/tests/it/encode.rs delete mode 100644 crates/ec-h265/tests/it/rate_control.rs delete mode 100644 crates/ec-h265/tests/it/rdoq_cache_hash.rs delete mode 100644 crates/ec-h265/tests/it/real_library.rs delete mode 100644 crates/ec-h265/tests/it/scaling_lists.rs diff --git a/crates/ec-h265-syntax/tests/sei_sweep.rs b/crates/ec-h265-syntax/tests/sei_sweep.rs deleted file mode 100644 index e96c8749..00000000 --- a/crates/ec-h265-syntax/tests/sei_sweep.rs +++ /dev/null @@ -1,83 +0,0 @@ -//! The SEI reader over the JCT-VC conformance streams. -//! -//! Every prefix and suffix SEI NAL unit of every stream must parse without error, - -use std::path::{Path, PathBuf}; - -use ec_h265_syntax::nal::split_annex_b; -use ec_h265_syntax::sei::{SeiMessage, parse_sei_rbsp}; - -fn streams() -> Vec { - let root = ec_testkit::fixture("vectors/hevc-jctvc"); - fn walk(dir: &Path, depth: u32, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - let mut paths: Vec = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); - paths.sort(); - for p in paths { - if p.is_dir() && depth > 0 { - walk(&p, depth - 1, out); - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { - out.push(p); - } - } - } - let mut out = Vec::new(); - walk(&root, 2, &mut out); - out -} - -#[test] -fn every_sei_in_the_conformance_streams_parses() { - let streams = streams(); - assert!(!streams.is_empty(), "no streams under vectors/hevc-jctvc"); - let mut with_hash = 0usize; - let mut hash_streams = Vec::new(); - let mut sei_nals = 0usize; - let mut messages = 0usize; - let mut hashes = 0usize; - let mut failures = Vec::new(); - for path in &streams { - let name = path.file_name().unwrap_or_default().to_string_lossy().to_string(); - let data = match std::fs::read(path) { - Ok(d) => d, - Err(e) => { - failures.push(format!("{name}: read: {e}")); - continue; - } - }; - let mut stream_hashes = 0usize; - for nal in split_annex_b(&data) { - if nal.header.layer_id > 0 || !matches!(nal.header.nal_type.code(), 39 | 40) { - continue; - } - sei_nals += 1; - match parse_sei_rbsp(&nal.rbsp()) { - Ok(msgs) => { - messages += msgs.len(); - for msg in &msgs { - if matches!(msg, SeiMessage::DecodedPictureHash(_)) { - stream_hashes += 1; - } - } - } - Err(e) => failures.push(format!("{name}: SEI NAL #{sei_nals}: {e}")), - } - } - if stream_hashes > 0 { - with_hash += 1; - hash_streams.push(name.clone()); - } - hashes += stream_hashes; - } - eprintln!( - "SEI sweep: {} streams, {with_hash} carry decoded_picture_hash ({hashes} hash messages), \ - {sei_nals} SEI NAL units, {messages} messages, {} parse failures", - streams.len(), - failures.len() - ); - eprintln!("streams with decoded_picture_hash: {}", hash_streams.join(" ")); - assert!(failures.is_empty(), "SEI that failed to parse:\n{}", failures.join("\n")); - assert!(with_hash > 0, "no conformance stream carries decoded_picture_hash SEI"); -} diff --git a/crates/ec-h265/tests/it/conformance.rs b/crates/ec-h265/tests/it/conformance.rs deleted file mode 100644 index 8b1f45fd..00000000 --- a/crates/ec-h265/tests/it/conformance.rs +++ /dev/null @@ -1,964 +0,0 @@ -//! Conformance: every access unit this encoder writes must decode in ffmpeg, -//! and the picture ffmpeg produces must be *bit-identical* to the encoder's own -//! reconstruction. That equality is the whole point of coding with the in-loop -//! filters off: it turns "the file plays" into "the decoder and the encoder -//! agree on every sample". - -use crate::common::{natural_frame, pin_or_panic, test_frame}; -use ec_core::frame::VideoFrame; -use ec_h265::encoder::{EncodedPicture, Encoder, EncoderConfig, RateControl, TransformSkip}; -use std::path::{Path, PathBuf}; - -fn scratch_dir() -> PathBuf { - let dir = std::env::temp_dir().join("ec-h265-tests"); - std::fs::create_dir_all(&dir).expect("scratch dir"); - dir -} - -/// Decode an Annex-B file with ffmpeg into planar 8-bit 4:2:0. -fn ffmpeg_decode(path: &Path) -> Result, String> { - let out = path.with_extension("yuv"); - let status = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-i"]) - .arg(path) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .arg(&out) - .output() - .map_err(|e| e.to_string())?; - if !status.status.success() { - return Err(String::from_utf8_lossy(&status.stderr).to_string()); - } - let stderr = String::from_utf8_lossy(&status.stderr).to_string(); - if !stderr.trim().is_empty() { - return Err(format!("ffmpeg complained: {stderr}")); - } - std::fs::read(&out).map_err(|e| e.to_string()) -} - -/// Pin one access unit as an Annex-B file for [`ffmpeg_decode`]. -/// -/// lane-h26xpinloud: this used `File::create(..).expect(..)` + -/// `write_all(..).expect("write bitstream")`, which closes only the ERROR path. -/// A write that reports success and leaves a short file put a truncated stream -/// at exactly the path ffmpeg then decoded, so the shortfall now carries the -/// path, both counts, and the OS error. Panic semantics kept: this caller -/// panicked before and still does, with the failure line as the message. -fn write_au(name: &str, picture: &EncodedPicture) -> PathBuf { - let path = scratch_dir().join(format!("{name}.265")); - pin_or_panic("write_au", &path, &picture.au); - path -} - -fn planes_of(frame: &VideoFrame) -> Vec { - let mut out = Vec::new(); - let (w, h) = (frame.width as usize, frame.height as usize); - for (i, plane) in frame.planes.iter().enumerate() { - let (pw, ph) = if i == 0 { - (w, h) - } else { - (w.div_ceil(2), h.div_ceil(2)) - }; - for row in 0..ph { - out.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]); - } - } - out -} - -fn psnr(a: &[u8], b: &[u8]) -> f64 { - assert_eq!(a.len(), b.len()); - let mse: f64 = a - .iter() - .zip(b) - .map(|(x, y)| { - let d = f64::from(*x) - f64::from(*y); - d * d - }) - .sum::() - / a.len() as f64; - if mse == 0.0 { - 99.0 - } else { - 10.0 * (255.0 * 255.0 / mse).log10() - } -} - -/// Encode one picture; `ctb` of `None` takes the configured default. -fn encode(width: u32, height: u32, qp: i32, ctb: Option) -> (VideoFrame, EncodedPicture) { - encode_with(width, height, qp, ctb, false, false) -} - -fn encode_with( - width: u32, - height: u32, - qp: i32, - ctb: Option, - chroma_mode_search: bool, - intra_nxn: bool, -) -> (VideoFrame, EncodedPicture) { - let mut cfg = EncoderConfig::new(width, height); - cfg.chroma_mode_search = chroma_mode_search; - cfg.intra_nxn = intra_nxn; - cfg.rate_control = RateControl::ConstantQp(qp); - if let Some(ctb) = ctb { - cfg.ctb_size = ctb; - } - cfg.keep_recon = true; - cfg.picture_hash = true; - let encoder = Encoder::new(cfg).expect("encoder"); - let frame = test_frame(width, height, 0); - let coded = encoder.encode_idr(&frame).expect("encode"); - (frame, coded) -} - -/// Same as `encode_with`, but on the grainy natural frame and with no chroma -/// mode search — the synthetic test frame is flat enough that the quadtree -/// never keeps an 8x8 coding unit, which is the only size PART_NxN applies to. -fn encode_natural( - width: u32, - height: u32, - qp: i32, - intra_nxn: bool, -) -> (VideoFrame, EncodedPicture) { - let mut cfg = EncoderConfig::new(width, height); - cfg.intra_nxn = intra_nxn; - cfg.rate_control = RateControl::ConstantQp(qp); - cfg.keep_recon = true; - cfg.picture_hash = true; - let encoder = Encoder::new(cfg).expect("encoder"); - let frame = natural_frame(width, height, 0); - let coded = encoder.encode_idr(&frame).expect("encode"); - (frame, coded) -} - -/// The chroma mode search is off by default (it loses on screen content, see -/// `EncoderConfig::chroma_mode_search`), so the shapes above never code an -/// `intra_chroma_pred_mode` other than the derived one. This exercises the four -/// explicit modes: the stream has to differ from the derived-only one — proving -/// the search actually fired — and still decode bit-exactly. -#[test] -fn chroma_mode_search_decodes_bit_exactly() { - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { - let (source, coded) = encode_with(w, h, 27, None, true, false); - let (_, derived) = encode_with(w, h, 27, None, false, false); - let name = format!("chroma-rd-{w}x{h}"); - assert_ne!( - coded.au, derived.au, - "{name}: the search never picked a mode other than the derived one, so this decode proves nothing" - ); - let path = write_au(&name, &coded); - let decoded = match ffmpeg_decode(&path) { - Ok(bytes) => bytes, - Err(e) => panic!("{name}: ffmpeg failed: {e}"), - }; - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - if mismatches != 0 { - // Which plane and where: a luma-only divergence is the transform - // tree, a chroma-only one is the flags that ride on it. - let luma = (w * h) as usize; - let chroma = luma / 4; - let first = decoded - .iter() - .zip(&recon) - .position(|(a, b)| a != b) - .unwrap(); - let count = |range: std::ops::Range| { - decoded[range.clone()] - .iter() - .zip(&recon[range]) - .filter(|(a, b)| a != b) - .count() - }; - let mut map = String::new(); - for by in (0..h as usize).step_by(16) { - for bx in (0..w as usize).step_by(16) { - let mut c = 0; - for row in by..by + 16 { - for col in bx..bx + 16 { - let i = row * w as usize + col; - if decoded[i] != recon[i] { - c += 1; - } - } - } - map.push_str(&format!("{c:4}")); - } - map.push('\n'); - } - eprintln!("luma 16x16 mismatch map:\n{map}"); - panic!( - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ - ({}, {})", - count(0..luma), - count(luma..luma + chroma), - count(luma + chroma..luma + 2 * chroma), - first % w as usize, - first / w as usize, - ); - } - let quality = psnr(&planes_of(&source), &recon); - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27"); - } -} - -/// PART_NxN is off by default, so nothing else here codes a four-partition -/// coding unit. This does: the stream has to differ from the 2Nx2N-only one — -/// proving the partition actually fired — and still decode bit-exactly, which -/// is the only check that the inferred transform split, the four `cbf_luma` -/// flags at transform depth 1 and the chroma residual riding on the last -/// partition are all where the decoder looks for them. -#[test] -fn intra_nxn_decodes_bit_exactly() { - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { - let (source, coded) = encode_natural(w, h, 22, true); - let (_, square) = encode_natural(w, h, 22, false); - let name = format!("intra-nxn-{w}x{h}"); - assert_ne!( - coded.au, square.au, - "{name}: no coding unit ever chose PART_NxN, so this decode proves nothing" - ); - let path = write_au(&name, &coded); - let decoded = match ffmpeg_decode(&path) { - Ok(bytes) => bytes, - Err(e) => panic!("{name}: ffmpeg failed: {e}"), - }; - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - if mismatches != 0 { - // Which plane and where: a luma-only divergence is the transform - // tree, a chroma-only one is the flags that ride on it. - let luma = (w * h) as usize; - let chroma = luma / 4; - let first = decoded - .iter() - .zip(&recon) - .position(|(a, b)| a != b) - .unwrap(); - let count = |range: std::ops::Range| { - decoded[range.clone()] - .iter() - .zip(&recon[range]) - .filter(|(a, b)| a != b) - .count() - }; - let mut map = String::new(); - for by in (0..h as usize).step_by(16) { - for bx in (0..w as usize).step_by(16) { - let mut c = 0; - for row in by..by + 16 { - for col in bx..bx + 16 { - let i = row * w as usize + col; - if decoded[i] != recon[i] { - c += 1; - } - } - } - map.push_str(&format!("{c:4}")); - } - map.push('\n'); - } - eprintln!("luma 16x16 mismatch map:\n{map}"); - panic!( - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ - ({}, {})", - count(0..luma), - count(luma..luma + chroma), - count(luma + chroma..luma + 2 * chroma), - first % w as usize, - first / w as usize, - ); - } - let quality = psnr(&planes_of(&source), &recon); - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); - } -} - -/// Sign data hiding drops one bypass bin per qualifying sub-block and pays for -/// it by nudging a level, so the encoder and the decoder only agree if the -/// parity the encoder wrote is the parity the decoder reads. The stream has to -/// differ from the hiding-off one, and ffmpeg's decode has to match the -/// encoder's reconstruction sample for sample. -/// -/// Size is deliberately not asserted here: hiding is not optional per -/// sub-block, so a single small picture can come out a few bytes longer when -/// the nudges cost more than the signs saved. Whether it pays is what the -/// `EC_H265_SDH` arm of the clip gate measures. -#[test] -fn sign_hiding_decodes_bit_exactly() { - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { - let (source, coded) = encode_sdh(w, h, 22, true); - let (_, plain) = encode_sdh(w, h, 22, false); - let name = format!("sign-hiding-{w}x{h}"); - assert_ne!( - coded.au, plain.au, - "{name}: no sub-block ever qualified, so this decode proves nothing" - ); - let path = write_au(&name, &coded); - let decoded = match ffmpeg_decode(&path) { - Ok(bytes) => bytes, - Err(e) => panic!("{name}: ffmpeg failed: {e}"), - }; - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - if mismatches != 0 { - // Which plane and where: a luma-only divergence is the transform - // tree, a chroma-only one is the flags that ride on it. - let luma = (w * h) as usize; - let chroma = luma / 4; - let first = decoded - .iter() - .zip(&recon) - .position(|(a, b)| a != b) - .unwrap(); - let count = |range: std::ops::Range| { - decoded[range.clone()] - .iter() - .zip(&recon[range]) - .filter(|(a, b)| a != b) - .count() - }; - let mut map = String::new(); - for by in (0..h as usize).step_by(16) { - for bx in (0..w as usize).step_by(16) { - let mut c = 0; - for row in by..by + 16 { - for col in bx..bx + 16 { - let i = row * w as usize + col; - if decoded[i] != recon[i] { - c += 1; - } - } - } - map.push_str(&format!("{c:4}")); - } - map.push('\n'); - } - eprintln!("luma 16x16 mismatch map:\n{map}"); - panic!( - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ - ({}, {})", - count(0..luma), - count(luma..luma + chroma), - count(luma + chroma..luma + 2 * chroma), - first % w as usize, - first / w as usize, - ); - } - let quality = psnr(&planes_of(&source), &recon); - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); - } -} - -/// The natural frame coded with sign data hiding on or off, everything else -/// left at its default. -fn encode_sdh(width: u32, height: u32, qp: i32, sign_hiding: bool) -> (VideoFrame, EncodedPicture) { - let mut cfg = EncoderConfig::new(width, height); - cfg.sign_hiding = sign_hiding; - cfg.rate_control = RateControl::ConstantQp(qp); - cfg.keep_recon = true; - cfg.picture_hash = true; - let encoder = Encoder::new(cfg).expect("encoder"); - let frame = natural_frame(width, height, 0); - let coded = encoder.encode_idr(&frame).expect("encode"); - (frame, coded) -} - -/// The natural frame coded with transform skip on or off, everything else -/// left at its default. -fn encode_tskip( - width: u32, - height: u32, - qp: i32, - tskip: TransformSkip, -) -> (VideoFrame, EncodedPicture) { - let mut cfg = EncoderConfig::new(width, height); - cfg.transform_skip = tskip; - cfg.rate_control = RateControl::ConstantQp(qp); - cfg.keep_recon = true; - cfg.picture_hash = true; - let encoder = Encoder::new(cfg).expect("encoder"); - let frame = natural_frame(width, height, 0); - let coded = encoder.encode_idr(&frame).expect("encode"); - (frame, coded) -} - -/// Transform skip bypasses the integer transform on 4x4 TUs, coding residual -/// samples directly with a fixed shift. The encoder and decoder agree only if -/// the shift matches on both sides; the stream has to differ from the -/// skip-off one, and ffmpeg's decode has to match the encoder's reconstruction -/// sample for sample. -#[test] -fn transform_skip_decodes_bit_exactly() { - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { - let (source, coded) = encode_tskip(w, h, 22, TransformSkip::AlwaysFor4x4); - let (_, plain) = encode_tskip(w, h, 22, TransformSkip::Off); - let name = format!("transform-skip-{w}x{h}"); - assert_ne!( - coded.au, plain.au, - "{name}: no TU ever skipped, so this decode proves nothing" - ); - let path = write_au(&name, &coded); - let decoded = match ffmpeg_decode(&path) { - Ok(bytes) => bytes, - Err(e) => panic!("{name}: ffmpeg failed: {e}"), - }; - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - if mismatches != 0 { - // Which plane and where: a luma-only divergence is the transform - // tree, a chroma-only one is the flags that ride on it. - let luma = (w * h) as usize; - let chroma = luma / 4; - let first = decoded - .iter() - .zip(&recon) - .position(|(a, b)| a != b) - .unwrap(); - let count = |range: std::ops::Range| { - decoded[range.clone()] - .iter() - .zip(&recon[range]) - .filter(|(a, b)| a != b) - .count() - }; - let mut map = String::new(); - for by in (0..h as usize).step_by(16) { - for bx in (0..w as usize).step_by(16) { - let mut c = 0; - for row in by..by + 16 { - for col in bx..bx + 16 { - let i = row * w as usize + col; - if decoded[i] != recon[i] { - c += 1; - } - } - } - map.push_str(&format!("{c:4}")); - } - map.push('\n'); - } - eprintln!("luma 16x16 mismatch map:\n{map}"); - panic!( - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ - ({}, {})", - count(0..luma), - count(luma..luma + chroma), - count(luma + chroma..luma + 2 * chroma), - first % w as usize, - first / w as usize, - ); - } - let quality = psnr(&planes_of(&source), &recon); - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 22"); - } -} -#[test] -fn ffmpeg_decodes_bit_exactly_at_every_shape() { - // 1920x1080 needs the conformance window on the bottom (1088 coded rows are - // not used: 1080 is a multiple of 8, but 64x64 CTBs still overhang), 1916 - // needs it on the right, 130x66 exercises a partial CTB in both directions. - // Both tree sizes are coded: the default is 32, and 64 is still offered. - for &(w, h, ctb) in &[ - (64u32, 64u32, None), - (130, 66, None), - (1916, 1080, None), - (352, 288, None), - (1916, 1080, Some(64)), - (130, 66, Some(64)), - ] { - let (source, coded) = encode(w, h, 27, ctb); - let name = format!( - "shape-{w}x{h}-ctb{}", - ctb.map_or("default".to_string(), |c| c.to_string()) - ); - let path = write_au(&name, &coded); - let decoded = match ffmpeg_decode(&path) { - Ok(bytes) => bytes, - Err(e) => panic!("{name}: ffmpeg failed: {e}"), - }; - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); - assert_eq!( - decoded.len(), - recon.len(), - "{name}: decoded {} bytes, reconstruction {} bytes", - decoded.len(), - recon.len() - ); - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - if mismatches != 0 { - // Which plane and where: a luma-only divergence is the transform - // tree, a chroma-only one is the flags that ride on it. - let luma = (w * h) as usize; - let chroma = luma / 4; - let first = decoded - .iter() - .zip(&recon) - .position(|(a, b)| a != b) - .unwrap(); - let count = |range: std::ops::Range| { - decoded[range.clone()] - .iter() - .zip(&recon[range]) - .filter(|(a, b)| a != b) - .count() - }; - let mut map = String::new(); - for by in (0..h as usize).step_by(16) { - for bx in (0..w as usize).step_by(16) { - let mut c = 0; - for row in by..by + 16 { - for col in bx..bx + 16 { - let i = row * w as usize + col; - if decoded[i] != recon[i] { - c += 1; - } - } - } - map.push_str(&format!("{c:4}")); - } - map.push('\n'); - } - eprintln!("luma 16x16 mismatch map:\n{map}"); - panic!( - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ - ({}, {})", - count(0..luma), - count(luma..luma + chroma), - count(luma + chroma..luma + 2 * chroma), - first % w as usize, - first / w as usize, - ); - } - // And the encode is worth something: PSNR against the source. - let quality = psnr(&planes_of(&source), &recon); - assert!(quality > 30.0, "{name}: PSNR {quality:.2} dB at QP 27"); - } -} - -/// A 64x64 coding unit predicts and transforms in four 32x32 blocks under one -/// luma mode, with the transform split inferred rather than signalled -/// (`log2TrafoSize > MaxTbLog2SizeY`, 7.4.9.8). That inference is the part a -/// decoder disagrees with loudly, so it is gated against ffmpeg -- and the -/// stream has to differ from the same encode with `cu64` off, or the test would -/// pass without a single 64x64 coding unit ever being kept. -#[test] -fn cu64_decodes_bit_exactly() { - // 130x66 is here for the partial coding tree blocks, not for the decision: - // at that size only two tree blocks are whole and the search keeps neither, - // so its stream is allowed to come out identical. - for &(w, h, qp, fires) in &[ - (352u32, 288u32, 32i32, true), - (256, 256, 37, true), - (130, 66, 32, false), - ] { - let (source, off) = encode_cu64(w, h, qp, false); - let (_, on) = encode_cu64(w, h, qp, true); - let name = format!("cu64-{w}x{h}-qp{qp}"); - if fires { - assert_ne!(off.au, on.au, "{name}: no 64x64 coding unit was ever kept"); - } - - let path = write_au(&name, &on); - let decoded = match ffmpeg_decode(&path) { - Ok(bytes) => bytes, - Err(e) => panic!("{name}: ffmpeg failed: {e}"), - }; - let recon = planes_of(on.recon.as_ref().expect("recon kept")); - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - if mismatches != 0 { - let first = decoded - .iter() - .zip(&recon) - .position(|(a, b)| a != b) - .unwrap(); - let luma = (w * h) as usize; - panic!( - "{name}: {mismatches} samples differ, first at {first} ({}, {}), {} of them luma", - first % w as usize, - first / w as usize, - decoded[..luma] - .iter() - .zip(&recon[..luma]) - .filter(|(a, b)| a != b) - .count(), - ); - } - let quality = psnr(&planes_of(&source), &recon); - assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP {qp}"); - } -} - -fn encode_cu64(width: u32, height: u32, qp: i32, cu64: bool) -> (VideoFrame, EncodedPicture) { - let mut cfg = EncoderConfig::new(width, height); - cfg.ctb_size = 64; - cfg.cu64 = cu64; - cfg.rate_control = RateControl::ConstantQp(qp); - cfg.keep_recon = true; - cfg.picture_hash = true; - let encoder = Encoder::new(cfg).expect("encoder"); - let frame = natural_frame(width, height, 0); - let coded = encoder.encode_idr(&frame).expect("encode"); - (frame, coded) -} - -/// The 32x32 default buys wavefront rows (see `perf.rs`) by coding a shallower -/// tree; that trade is only worth taking if the bits it costs are noise. -#[test] -fn the_default_tree_costs_almost_nothing_against_64() { - let source = natural_frame(1920, 1080, 0); - let mut coded = Vec::new(); - for ctb in [32usize, 64] { - let mut cfg = EncoderConfig::new(1920, 1080); - cfg.rate_control = RateControl::ConstantQp(27); - cfg.ctb_size = ctb; - cfg.keep_recon = true; - let encoder = Encoder::new(cfg).expect("encoder"); - let picture = encoder.encode_idr(&source).expect("encode"); - let quality = psnr( - &planes_of(&source), - &planes_of(picture.recon.as_ref().unwrap()), - ); - coded.push((picture.au.len(), quality)); - } - let ((bits32, psnr32), (bits64, psnr64)) = (coded[0], coded[1]); - println!( - "1080p at QP 27: CTB 32 {bits32} bytes / {psnr32:.2} dB, CTB 64 {bits64} bytes / {psnr64:.2} dB \ - ({:+.1}% bits, {:+.2} dB)", - (bits32 as f64 / bits64 as f64 - 1.0) * 100.0, - psnr32 - psnr64 - ); - assert!( - // Measured 1.0% on this fixture; the bound leaves room for the shape of - // the picture, not for a change of coding behaviour. - (bits32 as f64) < bits64 as f64 * 1.03, - "CTB 32 spent {bits32} bytes against 64's {bits64}" - ); - assert!( - (psnr32 - psnr64).abs() < 0.1, - "CTB 32 landed {psnr32:.2} dB against 64's {psnr64:.2} dB" - ); -} - -#[test] -fn ffmpeg_verifies_the_decoded_picture_hash() { - // The MD5 SEI is the encoder's claim about its own reconstruction; ffmpeg's - // decoder checks that claim against what it decoded when asked to. This is - // the one oracle that does not depend on this crate being right about - // anything except the hash itself. - let (_, coded) = encode(352, 288, 30, None); - let path = write_au("hash-352x288", &coded); - let output = ec_testkit::ffmpeg() - .args(["-v", "debug", "-err_detect", "crccheck", "-y", "-i"]) - .arg(&path) - .args(["-f", "null", "-"]) - .output() - .expect("run ffmpeg"); - let log = String::from_utf8_lossy(&output.stderr).to_string(); - let checks: Vec<&str> = log - .lines() - .filter(|line| line.contains("Verifying checksum")) - .collect(); - assert!(!checks.is_empty(), "ffmpeg checked no picture hash: {log}"); - for line in checks { - assert_eq!(line.matches("correct").count(), 3, "hash mismatch: {line}"); - } -} - -#[test] -fn vaapi_hardware_decodes_the_stream() { - // The other half of "it decodes": a GPU decoder is a different - // implementation with different tolerances, and it is what edith's HEVC - // path actually uses. Skipped where there is no render node. - if !Path::new("/dev/dri/renderD128").exists() { - eprintln!("skipping: no VA-API render node"); - return; - } - let (_, coded) = encode(1920, 1080, 27, None); - let path = write_au("vaapi-1080p", &coded); - let output = ec_testkit::ffmpeg() - .args([ - "-v", - "error", - "-hwaccel", - "vaapi", - "-hwaccel_device", - "/dev/dri/renderD128", - "-i", - ]) - .arg(&path) - .args(["-f", "null", "-"]) - .output() - .expect("run ffmpeg"); - let stderr = String::from_utf8_lossy(&output.stderr).to_string(); - if stderr.contains("Failed to initialise VAAPI") - || stderr.contains("No VA display found") - || stderr.contains("Device creation failed") - { - eprintln!("skipping: VA-API unavailable here ({})", stderr.trim()); - return; - } - assert!( - output.status.success() && stderr.trim().is_empty(), - "VA-API decode failed: {stderr}" - ); -} - -#[test] -fn quality_rises_as_qp_falls() { - let mut previous = 0.0; - for &qp in &[40i32, 32, 27, 22] { - let (source, coded) = encode(256, 144, qp, None); - let recon = planes_of(coded.recon.as_ref().expect("recon")); - let quality = psnr(&planes_of(&source), &recon); - assert!( - quality > previous, - "QP {qp}: PSNR {quality:.2} dB is not above {previous:.2}" - ); - previous = quality; - } - assert!( - previous > 40.0, - "QP 22 should clear 40 dB, got {previous:.2}" - ); -} - -#[test] -fn threads_do_not_change_the_bitstream() { - let mut cfg = EncoderConfig::new(320, 192); - cfg.rate_control = RateControl::ConstantQp(30); - cfg.threads = 1; - let single = Encoder::new(cfg.clone()).unwrap(); - cfg.threads = 8; - let many = Encoder::new(cfg).unwrap(); - let frame = test_frame(320, 192, 3); - let a = single.encode_idr(&frame).unwrap(); - let b = many.encode_idr(&frame).unwrap(); - assert_eq!(a.au, b.au, "wavefront changed the bitstream"); -} - -#[test] -fn a_bit_target_lands_near_its_target() { - // The model picks a QP from bits-per-pixel; a picture that comes out more - // than a quarter off is coded once more at a corrected QP. What is asserted - // is the contract that mode offers — near the target, monotonic in it — not - // a bitrate to the byte, which no single-picture encoder can promise. - let mut previous = 0usize; - for target in [400_000u64, 1_200_000, 3_000_000] { - let mut cfg = EncoderConfig::new(640, 360); - cfg.rate_control = RateControl::TargetBits(target); - let encoder = Encoder::new(cfg).expect("encoder"); - let frame = test_frame(640, 360, 5); - let coded = encoder.encode_idr(&frame).expect("encode"); - let bits = coded.au.len() * 8; - assert!( - bits > previous, - "target {target}: {bits} bits did not grow with the target" - ); - previous = bits; - let ratio = bits as f64 / target as f64; - assert!( - (0.4..2.5).contains(&ratio), - "target {target}: got {bits} bits (x{ratio:.2}) at QP {}", - coded.qp - ); - } -} - -#[test] -fn the_batch_helper_codes_every_picture_as_its_own_access_unit() { - let cfg = EncoderConfig::new(128, 96); - let encoder = Encoder::new(cfg).expect("encoder"); - let frames: Vec = (0..3).map(|i| test_frame(128, 96, i * 11)).collect(); - let coded = encoder.encode_batch(frames.iter()).expect("batch encode"); - assert_eq!(coded.len(), 3); - for picture in &coded { - // Every access unit stands alone: parameter sets, then an IDR slice. - let nals = ec_h265_syntax::split_annex_b(&picture.au); - let types: Vec<_> = nals.iter().map(|n| n.header.nal_type).collect(); - assert_eq!( - &types[..4], - &[ - ec_h265_syntax::NalUnitType::Vps, - ec_h265_syntax::NalUnitType::Sps, - ec_h265_syntax::NalUnitType::Pps, - ec_h265_syntax::NalUnitType::IdrWRadl, - ], - "access unit is not self-contained" - ); - } - // Different pictures, different bitstreams. - assert_ne!(coded[0].au, coded[1].au); -} - -/// Rate-distortion quantisation changes which levels are coded, so the streams -/// it produces are a different set of bins from the plain quantiser's; ffmpeg -/// has to read them back to the same samples the encoder reconstructed. -#[test] -fn rdoq_decodes_bit_exactly() { - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { - let (source, coded) = encode_rdoq(w, h, 27, true); - let (_, plain) = encode_rdoq(w, h, 27, false); - let name = format!("rdoq-{w}x{h}"); - assert_ne!( - coded.au, plain.au, - "{name}: the level search changed no byte, so it is not running" - ); - let path = write_au(&name, &coded); - let decoded = match ffmpeg_decode(&path) { - Ok(bytes) => bytes, - Err(e) => panic!("{name}: ffmpeg failed: {e}"), - }; - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - if mismatches != 0 { - // Which plane and where: a luma-only divergence is the transform - // tree, a chroma-only one is the flags that ride on it. - let luma = (w * h) as usize; - let chroma = luma / 4; - let first = decoded - .iter() - .zip(&recon) - .position(|(a, b)| a != b) - .unwrap(); - let count = |range: std::ops::Range| { - decoded[range.clone()] - .iter() - .zip(&recon[range]) - .filter(|(a, b)| a != b) - .count() - }; - let mut map = String::new(); - for by in (0..h as usize).step_by(16) { - for bx in (0..w as usize).step_by(16) { - let mut c = 0; - for row in by..by + 16 { - for col in bx..bx + 16 { - let i = row * w as usize + col; - if decoded[i] != recon[i] { - c += 1; - } - } - } - map.push_str(&format!("{c:4}")); - } - map.push('\n'); - } - eprintln!("luma 16x16 mismatch map:\n{map}"); - panic!( - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ - ({}, {})", - count(0..luma), - count(luma..luma + chroma), - count(luma + chroma..luma + 2 * chroma), - first % w as usize, - first / w as usize, - ); - } - let quality = psnr(&planes_of(&source), &recon); - assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP 27"); - } -} - -/// The natural frame coded with the level search on or off, everything else -/// left at its default. -fn encode_rdoq(width: u32, height: u32, qp: i32, rdoq: bool) -> (VideoFrame, EncodedPicture) { - let mut cfg = EncoderConfig::new(width, height); - cfg.rdoq = rdoq; - cfg.rate_control = RateControl::ConstantQp(qp); - cfg.keep_recon = true; - cfg.picture_hash = true; - let encoder = Encoder::new(cfg).expect("encoder"); - let frame = natural_frame(width, height, 0); - let coded = encoder.encode_idr(&frame).expect("encode"); - (frame, coded) -} - -/// RQT must produce a bitstream a conformant decoder reads back to the exact -/// samples the encoder reconstructed. -#[test] -fn rqt_decodes_bit_exactly() { - for &(w, h) in &[(64u32, 64u32), (130, 66), (352, 288)] { - let (source, coded) = encode_rqt(w, h, 27, true); - let (_, plain) = encode_rqt(w, h, 27, false); - let name = format!("rqt-{w}x{h}"); - assert_ne!( - coded.au, plain.au, - "{name}: RQT changed no byte, so the split path is not running" - ); - let path = write_au(&name, &coded); - let decoded = match ffmpeg_decode(&path) { - Ok(bytes) => bytes, - Err(e) => panic!("{name}: ffmpeg failed: {e}"), - }; - let recon = planes_of(coded.recon.as_ref().expect("recon kept")); - assert_eq!(decoded.len(), recon.len(), "{name}: size mismatch"); - let mismatches = decoded.iter().zip(&recon).filter(|(a, b)| a != b).count(); - if mismatches != 0 { - // Which plane and where: a luma-only divergence is the transform - // tree, a chroma-only one is the flags that ride on it. - let luma = (w * h) as usize; - let chroma = luma / 4; - let first = decoded - .iter() - .zip(&recon) - .position(|(a, b)| a != b) - .unwrap(); - let count = |range: std::ops::Range| { - decoded[range.clone()] - .iter() - .zip(&recon[range]) - .filter(|(a, b)| a != b) - .count() - }; - let mut map = String::new(); - for by in (0..h as usize).step_by(16) { - for bx in (0..w as usize).step_by(16) { - let mut c = 0; - for row in by..by + 16 { - for col in bx..bx + 16 { - let i = row * w as usize + col; - if decoded[i] != recon[i] { - c += 1; - } - } - } - map.push_str(&format!("{c:4}")); - } - map.push('\n'); - } - eprintln!("luma 16x16 mismatch map:\n{map}"); - panic!( - "{name}: {mismatches} samples differ -- Y {}, Cb {}, Cr {}, first at {first} \ - ({}, {})", - count(0..luma), - count(luma..luma + chroma), - count(luma + chroma..luma + 2 * chroma), - first % w as usize, - first / w as usize, - ); - } - let quality = psnr(&planes_of(&source), &recon); - assert!(quality > 28.0, "{name}: PSNR {quality:.2} dB at QP 27"); - } -} - -/// The natural frame coded with RQT on or off, everything else left at its -/// default. -fn encode_rqt(width: u32, height: u32, qp: i32, rqt: bool) -> (VideoFrame, EncodedPicture) { - let mut cfg = EncoderConfig::new(width, height); - cfg.rqt = rqt; - cfg.rate_control = RateControl::ConstantQp(qp); - cfg.keep_recon = true; - cfg.picture_hash = true; - let encoder = Encoder::new(cfg).expect("encoder"); - let frame = natural_frame(width, height, 0); - let coded = encoder.encode_idr(&frame).expect("encode"); - (frame, coded) -} diff --git a/crates/ec-h265/tests/it/conformance_intra.rs b/crates/ec-h265/tests/it/conformance_intra.rs deleted file mode 100644 index d9e1200a..00000000 --- a/crates/ec-h265/tests/it/conformance_intra.rs +++ /dev/null @@ -1,276 +0,0 @@ -//! Checks every output picture of each JCT-VC conformance stream against the -//! MD5 in its decoded picture hash SEI (D.3.19). -//! -//! Streams the decoder refuses are reported with the error text. Mismatches are -//! reported, never asserted. The digest is computed with the SEI writer of -//! `ec-h265-syntax`, which is the same MD5 the hash message carries. - -use crate::common::{cropped_bytes, describe, plane_matches, whole_output_digest}; -use std::panic::{self, AssertUnwindSafe}; -use std::path::{Path, PathBuf}; - -use ec_h265::dec::Decoder; - -/// The outcome of one stream, one row of the report. -struct Row { - name: String, - accepted: &'static str, - checked: usize, - exact: usize, - detail: String, - /// Whether any picture was checked against the reference YUV (no hash SEI). - by_reference: bool, - /// Wall time of decode and flush, in seconds (0 when the stream was refused early). - decode_secs: f64, -} - -fn jctvc_root() -> PathBuf { - ec_testkit::fixture("vectors/hevc-jctvc") -} - -/// The conformance streams: the first `.bin` or `.bit` bitstream of each zip's -/// directory under the root, sorted by name. Some zips extract one directory -/// deeper, so two levels are searched. -fn streams() -> Vec { - let root = jctvc_root(); - fn bitstreams_in(dir: &Path, depth: u32, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - let mut paths: Vec = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); - paths.sort(); - for p in paths { - if p.is_dir() && depth > 0 { - bitstreams_in(&p, depth - 1, out); - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { - out.push(p); - } - } - } - let dirs = std::fs::read_dir(&root).expect("fixture directory"); - let mut dirs: Vec = dirs.filter_map(|e| e.ok().map(|e| e.path())).collect(); - dirs.sort(); - dirs.into_iter() - .filter(|d| d.is_dir()) - .filter_map(|d| { - let mut found = Vec::new(); - bitstreams_in(&d, 2, &mut found); - found.into_iter().next() - }) - .collect() -} - -/// Decodes one stream and checks every output picture against its MD5 SEI. -fn check_stream(path: &Path, name: &str) -> Row { - let mut row = Row { - name: name.to_string(), - accepted: "no", - checked: 0, - exact: 0, - detail: String::new(), - by_reference: false, - decode_secs: 0.0, - }; - let data = match std::fs::read(path) { - Ok(d) => d, - Err(e) => { - row.detail = format!("read error: {e}"); - return row; - } - }; - let reference = std::fs::read(path.with_extension("yuv")).ok(); - // A `_md5.txt` beside the bitstream is the authority for frames without a hash SEI. It - // takes precedence over the ffmpeg reference YUV, which ffmpeg cannot reproduce for such a - // stream (VPSSPSPPS_A: ffmpeg outputs 2 of its 6 frames). - let whole_output = std::fs::read_to_string(path.with_file_name(format!("{name}_md5.txt"))) - .ok() - .and_then(|text| whole_output_digest(&text)); - let mut whole_output_md5 = ec_h265_syntax::md5::Md5::new(); - let mut whole_output_checked = 0usize; - - let started = std::time::Instant::now(); - let mut dec = Decoder::new(); - if let Err(e) = dec.decode_annex_b(&data) { - row.detail = format!("error: {e}"); - return row; - } - if let Err(e) = dec.flush() { - row.detail = format!("error: {e}"); - return row; - } - row.accepted = "yes"; - - let mut out_index = 0usize; - let mut first: Option = None; - while let Some(frame) = dec.next_frame() { - let index = out_index; - out_index += 1; - let Some(expected) = frame.meta.picture_hash.as_ref() else { - if whole_output.is_some() { - whole_output_md5.update(&cropped_bytes(&frame.picture, &frame.window)); - whole_output_checked += 1; - continue; - } - // No hash SEI: the frame is checked against the reference YUV, when there is one. - if let Some(reference) = reference.as_deref() { - let want = cropped_bytes(&frame.picture, &frame.window); - let start = index * want.len(); - row.checked += 1; - if reference.get(start..start + want.len()) == Some(&want[..]) { - row.exact += 1; - } else if first.is_none() { - let at = (0..3) - .find_map(|plane| { - let d = - describe(Some(reference), index, &frame.picture, frame.poc, plane); - (!d.contains("no sample differs")).then_some(d) - }) - .unwrap_or_else(|| format!("reference YUV frame {index} differs")); - first = Some(format!("{at} (reference YUV, cropped)")); - } - row.by_reference = true; - } - continue; - }; - row.checked += 1; - let pic = &*frame.picture; - let mut exact = true; - for (plane, ok) in plane_matches(pic, expected).into_iter().enumerate() { - if ok { - continue; - } - exact = false; - if first.is_none() { - let kind = if frame.meta.intra_only { "I" } else { "P/B" }; - let at = describe(reference.as_deref(), index, pic, frame.poc, plane); - first = Some(format!("{at} slices={kind}")); - } - } - if exact { - row.exact += 1; - } - } - row.decode_secs = started.elapsed().as_secs_f64(); - if let Some(want) = whole_output { - let got = whole_output_md5.finish(); - row.checked += whole_output_checked; - if got == want { - row.exact += whole_output_checked; - } else { - let hex: String = got.iter().map(|b| format!("{b:02x}")).collect(); - first.get_or_insert(format!( - "whole-output MD5 {hex} differs from {name}_md5.txt" - )); - } - row.by_reference = true; - } - row.detail = match (first, row.checked) { - (Some(f), _) => format!("first mismatch {f}"), - (None, 0) => "no pictures with a hash SEI or reference YUV".to_string(), - (None, _) if whole_output.is_some() => { - "ok (whole-output MD5 from the conformance package)".to_string() - } - (None, _) if row.by_reference => "ok (against the reference YUV)".to_string(), - (None, _) => "ok".to_string(), - }; - row -} - -#[test] -fn conformance_pictures_match_the_sei_hash() { - let root = jctvc_root(); - let streams = streams(); - assert!( - !streams.is_empty(), - "no conformance streams under {}", - root.display() - ); - - let mut rows = Vec::new(); - for path in &streams { - let name = path - .file_stem() - .map(|s| s.to_string_lossy().into_owned()) - .unwrap_or_default(); - let outcome = panic::catch_unwind(AssertUnwindSafe(|| check_stream(path, &name))); - let mut row = match outcome { - Ok(row) => row, - Err(payload) => { - let msg = payload - .downcast_ref::<&str>() - .map(|s| s.to_string()) - .or_else(|| payload.downcast_ref::().cloned()) - .unwrap_or_default(); - Row { - name: name.clone(), - accepted: "panic", - checked: 0, - exact: 0, - detail: format!("panic: {msg}"), - by_reference: false, - decode_secs: 0.0, - } - } - }; - row.detail = row.detail.replace(['\t', '\n'], " "); - rows.push(row); - } - - let mut table = - String::from("stream\taccepted\tpictures_checked\tpictures_exact\tdetail\tdecode_s\n"); - for r in &rows { - println!( - "{} | {} | {} | {} | {} | {:.2}s", - r.name, r.accepted, r.checked, r.exact, r.detail, r.decode_secs - ); - table.push_str(&format!( - "{}\t{}\t{}\t{}\t{}\t{:.2}\n", - r.name, r.accepted, r.checked, r.exact, r.detail, r.decode_secs - )); - } - let checked: usize = rows.iter().map(|r| r.checked).sum(); - let exact: usize = rows.iter().map(|r| r.exact).sum(); - let accepted = rows.iter().filter(|r| r.accepted == "yes").count(); - println!( - "total: {checked} pictures checked, {exact} exact, {accepted}/{} streams accepted", - rows.len() - ); - let report = std::env::var("EC_H265_INTRA_REPORT") - .ok() - .filter(|p| !p.is_empty()); - let written = report.map(|path| std::fs::write(&path, &table).map_err(|e| (path, e))); - if let Some(Err((path, e))) = written { - eprintln!("could not write report {path}: {e}"); - } - - // Every accepted stream must be fully exact, except the streams named in KNOWN_INEXACT. - let failing: Vec = rows - .iter() - .filter(|r| r.accepted == "yes" && r.checked > 0 && r.exact != r.checked) - .filter(|r| !KNOWN_INEXACT.iter().any(|(name, _)| *name == r.name)) - .map(|r| format!("{} ({}/{} exact: {})", r.name, r.exact, r.checked, r.detail)) - .collect(); - assert!( - failing.is_empty(), - "accepted streams that are not exact and not in KNOWN_INEXACT:\n{}", - failing.join("\n") - ); -} - -#[test] -fn whole_output_digest_reads_the_first_word() { - let digest = whole_output_digest("1ddf74263cb4953cfdfcf99c563d88ea").unwrap(); - assert_eq!(digest[0], 0x1d); - assert_eq!(digest[15], 0xea); - let with_name = whole_output_digest("1ddf74263cb4953cfdfcf99c563d88ea out.yuv\n"); - assert_eq!(with_name, Some(digest)); - assert_eq!(whole_output_digest("1ddf7426"), None); - assert_eq!( - whole_output_digest("zzdf74263cb4953cfdfcf99c563d88ea"), - None - ); -} - -/// Accepted streams that are knowingly not fully exact, each with the reason. Remove an entry -/// once the stream is exact. Nothing else may be listed. -const KNOWN_INEXACT: &[(&str, &str)] = &[]; diff --git a/crates/ec-h265/tests/it/conformance_rext.rs b/crates/ec-h265/tests/it/conformance_rext.rs deleted file mode 100644 index ad752f0e..00000000 --- a/crates/ec-h265/tests/it/conformance_rext.rs +++ /dev/null @@ -1,325 +0,0 @@ -//! Checks every output picture of each JCT-VC range extension conformance stream -//! (D.3.19), or against the whole-output MD5 of the package when the stream has no hash. -//! -//! A stream the decoder refuses must be refused by name: the error text has to be one of -//! `REFUSED`. Every other stream has to decode exactly, picture for picture. - -use crate::common::{cropped_bytes, describe, plane_matches, whole_output_digest}; -use std::panic::{self, AssertUnwindSafe}; -use std::path::{Path, PathBuf}; - -use ec_h265::dec::Decoder; - -/// The outcome of one stream, one row of the report. -struct Row { - name: String, - accepted: &'static str, - checked: usize, - exact: usize, - detail: String, - /// Whether any picture was checked against the reference YUV (no hash SEI). - by_reference: bool, - /// Wall time of decode and flush, in seconds (0 when the stream was refused early). - decode_secs: f64, -} - -fn jctvc_root() -> PathBuf { - ec_testkit::fixture("vectors/hevc-rext") -} - -/// The conformance streams: the first `.bin` or `.bit` bitstream of each zip's -/// directory under the root, sorted by name. Some zips extract one directory -/// deeper, so two levels are searched. -fn streams() -> Vec { - let root = jctvc_root(); - fn bitstreams_in(dir: &Path, depth: u32, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - let mut paths: Vec = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); - paths.sort(); - for p in paths { - if p.is_dir() && depth > 0 { - bitstreams_in(&p, depth - 1, out); - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { - out.push(p); - } - } - } - let dirs = std::fs::read_dir(&root).expect("fixture directory"); - let mut dirs: Vec = dirs.filter_map(|e| e.ok().map(|e| e.path())).collect(); - dirs.sort(); - dirs.into_iter() - .filter(|d| d.is_dir()) - .filter(|d| { - std::env::var("EC_H265_REXT_ONLY") - .map_or(true, |only| d.to_string_lossy().contains(&only)) - }) - .filter_map(|d| { - let mut found = Vec::new(); - bitstreams_in(&d, 2, &mut found); - found.into_iter().next() - }) - .collect() -} - -/// Every 32-digit hex word of the MD5 files beside the bitstream (`*md5*`): one of them is the -/// MD5 of the whole decoded output, the others are the bitstream's own. -fn candidate_digests(path: &Path) -> Vec<[u8; 16]> { - let mut out = Vec::new(); - let Some(dir) = path.parent() else { - return out; - }; - let Ok(entries) = std::fs::read_dir(dir) else { - return out; - }; - for e in entries.flatten() { - let name = e.file_name().to_string_lossy().to_lowercase(); - if !name.contains("md5") { - continue; - } - if let Ok(text) = std::fs::read_to_string(e.path()) { - for word in text.split_whitespace() { - if let Some(d) = whole_output_digest(word) { - out.push(d); - } - } - } - } - out -} - -/// The stream cut at its start codes: each chunk is one NAL unit with its start code. -fn nal_chunks(data: &[u8]) -> Vec<&[u8]> { - let mut starts: Vec = (0..data.len().saturating_sub(2)) - .filter(|&i| data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1) - .collect(); - starts.push(data.len()); - starts.windows(2).map(|w| &data[w[0]..w[1]]).collect() -} - -/// Decodes one stream and checks every output picture against its MD5 SEI. -fn check_stream(path: &Path, name: &str) -> Row { - let mut row = Row { - name: name.to_string(), - accepted: "no", - checked: 0, - exact: 0, - detail: String::new(), - by_reference: false, - decode_secs: 0.0, - }; - let data = match std::fs::read(path) { - Ok(d) => d, - Err(e) => { - row.detail = format!("read error: {e}"); - return row; - } - }; - let reference = std::fs::read(path.with_extension("yuv")).ok(); - // A `_md5.txt` beside the bitstream is the authority for frames without a hash SEI. It - // takes precedence over the ffmpeg reference YUV, which ffmpeg cannot reproduce for such a - // stream (VPSSPSPPS_A: ffmpeg outputs 2 of its 6 frames). - let whole_output = Some(candidate_digests(path)).filter(|d| !d.is_empty()); - let mut whole_output_md5 = ec_h265_syntax::md5::Md5::new(); - let mut whole_output_checked = 0usize; - - let started = std::time::Instant::now(); - let mut dec = Decoder::new(); - let mut out_index = 0usize; - let mut first: Option = None; - let mut handle = |frame: ec_h265::dec::Frame| { - let index = out_index; - out_index += 1; - if whole_output.is_some() { - whole_output_md5.update(&cropped_bytes(&frame.picture, &frame.window)); - } - let Some(expected) = frame.meta.picture_hash.as_ref() else { - if whole_output.is_some() { - whole_output_checked += 1; - return; - } - // No hash SEI: the frame is checked against the reference YUV, when there is one. - if let Some(reference) = reference.as_deref() { - let want = cropped_bytes(&frame.picture, &frame.window); - let start = index * want.len(); - row.checked += 1; - if reference.get(start..start + want.len()) == Some(&want[..]) { - row.exact += 1; - } else if first.is_none() { - let at = (0..3) - .find_map(|plane| { - let d = - describe(Some(reference), index, &frame.picture, frame.poc, plane); - (!d.contains("no sample differs")).then_some(d) - }) - .unwrap_or_else(|| format!("reference YUV frame {index} differs")); - first = Some(format!("{at} (reference YUV, cropped)")); - } - row.by_reference = true; - } - return; - }; - row.checked += 1; - let pic = &*frame.picture; - let mut exact = true; - for (plane, ok) in plane_matches(pic, expected).into_iter().enumerate() { - if ok { - continue; - } - exact = false; - if first.is_none() { - let kind = if frame.meta.intra_only { "I" } else { "P/B" }; - let at = describe(reference.as_deref(), index, pic, frame.poc, plane); - first = Some(format!("{at} slices={kind}")); - } - } - if exact { - row.exact += 1; - } - }; - // Frames are drained after every NAL unit, so the output of a long stream is not held. - for unit in nal_chunks(&data) { - if let Err(e) = dec.decode_annex_b(unit) { - row.detail = format!("error: {e}"); - return row; - } - while let Some(frame) = dec.next_frame() { - handle(frame); - } - } - if let Err(e) = dec.flush() { - row.detail = format!("error: {e}"); - return row; - } - row.accepted = "yes"; - while let Some(frame) = dec.next_frame() { - handle(frame); - } - row.decode_secs = started.elapsed().as_secs_f64(); - if let Some(want) = whole_output.as_ref().filter(|_| whole_output_checked > 0) { - let got = whole_output_md5.finish(); - row.checked += whole_output_checked; - if want.contains(&got) { - row.exact += whole_output_checked; - } else { - let hex: String = got.iter().map(|b| format!("{b:02x}")).collect(); - first.get_or_insert(format!( - "whole-output MD5 {hex} differs from {name}_md5.txt" - )); - } - row.by_reference = true; - } - row.detail = match (first, row.checked) { - (Some(f), _) => format!("first mismatch {f}"), - (None, 0) => "no pictures with a hash SEI or reference YUV".to_string(), - (None, _) if whole_output.is_some() && whole_output_checked > 0 => { - "ok (whole-output MD5 from the conformance package)".to_string() - } - (None, _) if row.by_reference => "ok (against the reference YUV)".to_string(), - (None, _) => "ok".to_string(), - }; - row -} - -#[test] -fn rext_conformance_pictures_match_the_sei_hash() { - let root = jctvc_root(); - let streams = streams(); - assert!( - !streams.is_empty(), - "no conformance streams under {}", - root.display() - ); - - let mut rows = Vec::new(); - for path in &streams { - let name = path - .file_stem() - .map(|s| s.to_string_lossy().into_owned()) - .unwrap_or_default(); - eprintln!("stream {name}"); - let outcome = panic::catch_unwind(AssertUnwindSafe(|| check_stream(path, &name))); - let mut row = match outcome { - Ok(row) => row, - Err(payload) => { - let msg = payload - .downcast_ref::<&str>() - .map(|s| s.to_string()) - .or_else(|| payload.downcast_ref::().cloned()) - .unwrap_or_default(); - Row { - name: name.clone(), - accepted: "panic", - checked: 0, - exact: 0, - detail: format!("panic: {msg}"), - by_reference: false, - decode_secs: 0.0, - } - } - }; - row.detail = row.detail.replace(['\t', '\n'], " "); - rows.push(row); - } - - let mut table = - String::from("stream\taccepted\tpictures_checked\tpictures_exact\tdetail\tdecode_s\n"); - for r in &rows { - println!( - "{} | {} | {} | {} | {} | {:.2}s", - r.name, r.accepted, r.checked, r.exact, r.detail, r.decode_secs - ); - table.push_str(&format!( - "{}\t{}\t{}\t{}\t{}\t{:.2}\n", - r.name, r.accepted, r.checked, r.exact, r.detail, r.decode_secs - )); - } - let checked: usize = rows.iter().map(|r| r.checked).sum(); - let exact: usize = rows.iter().map(|r| r.exact).sum(); - let accepted = rows.iter().filter(|r| r.accepted == "yes").count(); - println!( - "total: {checked} pictures checked, {exact} exact, {accepted}/{} streams accepted", - rows.len() - ); - let report = std::env::var("EC_H265_REXT_REPORT") - .ok() - .filter(|p| !p.is_empty()); - let written = report.map(|path| std::fs::write(&path, &table).map_err(|e| (path, e))); - if let Some(Err((path, e))) = written { - eprintln!("could not write report {path}: {e}"); - } - - // Every accepted stream must be fully exact; a refusal must name a tool in REFUSED. - let failing: Vec = rows - .iter() - .filter(|r| r.accepted == "yes" && (r.checked == 0 || r.exact != r.checked)) - .map(|r| format!("{} ({}/{} exact: {})", r.name, r.exact, r.checked, r.detail)) - .collect(); - assert!( - failing.is_empty(), - "accepted streams that are not exact:\n{}", - failing.join("\n") - ); - let unexpected: Vec = rows - .iter() - .filter(|r| r.accepted != "yes") - .filter(|r| !REFUSED.iter().any(|name| r.detail.contains(name))) - .map(|r| format!("{} ({}: {})", r.name, r.accepted, r.detail)) - .collect(); - assert!( - unexpected.is_empty(), - "streams refused for a reason not in REFUSED:\n{}", - unexpected.join("\n") - ); -} - -/// The refusals a conformance stream may end in: tools this decoder names and does not decode. -const REFUSED: &[&str] = &[ - "extended_precision_processing_flag", - "cabac_bypass_alignment_enabled_flag", - "high_precision_offsets_enabled_flag", - "bit depth 16", - "bit depth 14", - "bit depth 13", -]; diff --git a/crates/ec-h265/tests/it/conformance_rext422.rs b/crates/ec-h265/tests/it/conformance_rext422.rs deleted file mode 100644 index 9f7ed2c2..00000000 --- a/crates/ec-h265/tests/it/conformance_rext422.rs +++ /dev/null @@ -1,128 +0,0 @@ -//! HEVC RExt 4:2:2 (Main 4:2:2 10 and the 8-bit generated clips) against ffmpeg. -//! -//! The committed 64x64 stream is decoded by ffmpeg at run time and compared sample for -//! sample. The Sony RExt conformance streams and the generated GOP/intra clips live in the - -use std::path::{Path, PathBuf}; - -use ec_h265::Decoder; - -const YUV422_10: &[u8] = include_bytes!("../data/refusals/yuv422_10.265"); - -fn decode(data: &[u8]) -> Vec { - let mut dec = Decoder::new(); - dec.decode_annex_b(data).expect("decode"); - dec.flush().expect("flush"); - let mut out = Vec::new(); - while let Some(f) = dec.next_frame() { - out.push((*f.picture).clone()); - } - out -} - -/// The first coded-size-cropped `w` x `h` window of every picture, as planar little-endian -/// samples (one byte per sample at 8 bit, two above), the layout of ffmpeg's rawvideo. -fn raw(pictures: &[ec_h265::decode::DecodedPicture], w: usize, h: usize) -> Vec { - let mut out = Vec::new(); - for p in pictures { - let wide = p.bit_depth > 8; - for (plane, pw, cw) in [ - (&p.y, p.width, w), - (&p.cb, p.width / 2, w / 2), - (&p.cr, p.width / 2, w / 2), - ] { - for y in 0..h { - for x in 0..cw { - let v = plane[y * pw + x]; - if wide { - out.extend_from_slice(&v.to_le_bytes()); - } else { - out.push(v as u8); - } - } - } - } - } - out -} - -fn first_diff(a: &[u8], b: &[u8]) -> Option { - if a.len() != b.len() { - return Some(a.len().min(b.len())); - } - a.iter().zip(b).position(|(x, y)| x != y) -} - -fn ffmpeg_422_10(src: &Path, reference: &Path) { - let st = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-i"]) - .arg(src) - .args(["-f", "rawvideo", "-pix_fmt", "yuv422p10le"]) - .arg(reference) - .status() - .unwrap(); - assert!(st.success(), "ffmpeg failed on {}", src.display()); -} - -#[test] -fn committed_422_stream_matches_ffmpeg() { - let dir = std::env::temp_dir().join("ec-h265-rext422"); - std::fs::create_dir_all(&dir).unwrap(); - let src = dir.join("yuv422_10.265"); - let reference = dir.join("yuv422_10.yuv"); - std::fs::write(&src, YUV422_10).unwrap(); - ffmpeg_422_10(&src, &reference); - let want = std::fs::read(&reference).unwrap(); - let got = raw(&decode(YUV422_10), 64, 64); - assert_eq!( - first_diff(&got, &want), - None, - "4:2:2 10-bit differs from ffmpeg" - ); -} - -fn rext_root() -> PathBuf { - ec_testkit::fixture("vectors/hevc-rext") -} - -fn find_stream(dir: &Path) -> Option { - for e in std::fs::read_dir(dir).ok()?.flatten() { - let p = e.path(); - if p.is_dir() { - if let Some(f) = find_stream(&p) { - return Some(f); - } - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { - return Some(p); - } - } - None -} - -#[test] -fn rext_422_vectors_are_byte_exact() { - let root = rext_root(); - let dir = std::env::temp_dir().join("ec-h265-rext422-vectors"); - std::fs::create_dir_all(&dir).unwrap(); - let mut checked = 0; - for (name, w, h) in [ - ("GENERAL_10b_422_RExt_Sony_1", 400, 384), - ("Main_422_10_A_RExt_Sony_2", 1920, 1080), - ("Main_422_10_B_RExt_Sony_2", 2560, 1600), - ] { - let stream = find_stream(&root.join(name)).unwrap_or_else(|| panic!("{name}: no stream")); - let reference = dir.join(format!("{name}.yuv")); - ffmpeg_422_10(&stream, &reference); - let data = std::fs::read(&stream).unwrap_or_else(|e| panic!("{}: {e}", stream.display())); - let want = std::fs::read(&reference).unwrap(); - let got = raw(&decode(&data), w, h); - assert_eq!( - first_diff(&got, &want), - None, - "{} differs from ffmpeg", - stream.display() - ); - checked += 1; - } - eprintln!("4:2:2 vectors checked byte-exact: {checked}"); -} diff --git a/crates/ec-h265/tests/it/cu_syntax.rs b/crates/ec-h265/tests/it/cu_syntax.rs deleted file mode 100644 index 29ff6133..00000000 --- a/crates/ec-h265/tests/it/cu_syntax.rs +++ /dev/null @@ -1,130 +0,0 @@ -//! CU syntax tests over the JCT-VC conformance streams: the P/B slice syntax with the -//! zero-motion stand-in (the sweep, pixel-pipeline and motion-determinism tests were removed by -//! testcut Phase 2). - -use ec_core::error::Error; -use ec_h265::dec::Decoder; -use std::path::{Path, PathBuf}; - -/// The conformance streams: the first `.bin` or `.bit` bitstream of each directory -fn streams() -> Vec { - let root = ec_testkit::fixture("vectors/hevc-jctvc"); - fn bitstreams_in(dir: &Path, depth: u32, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - let mut paths: Vec = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); - paths.sort(); - for p in paths { - if p.is_dir() && depth > 0 { - bitstreams_in(&p, depth - 1, out); - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { - out.push(p); - } - } - } - let dirs = std::fs::read_dir(&root).expect("fixture directory"); - let mut dirs: Vec = dirs.filter_map(|e| e.ok().map(|e| e.path())).collect(); - dirs.sort(); - dirs.into_iter() - .filter(|d| d.is_dir()) - .filter_map(|d| { - let mut found = Vec::new(); - bitstreams_in(&d, 2, &mut found); - found.into_iter().next() - }) - .collect() -} - -/// Split an Annex-B byte stream into NAL units (header included, start codes and -/// trailing zero bytes removed). -fn nal_units(data: &[u8]) -> Vec<&[u8]> { - let mut starts = Vec::new(); - let mut i = 0; - while i + 3 <= data.len() { - if data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 { - starts.push(i + 3); - i += 3; - } else { - i += 1; - } - } - let mut out = Vec::new(); - for (k, &s) in starts.iter().enumerate() { - let mut e = starts.get(k + 1).map_or(data.len(), |&next| next - 3); - while e > s && data[e - 1] == 0 { - e -= 1; - } - if e > s { - out.push(&data[s..e]); - } - } - out -} - -/// Whether a NAL unit is a coded slice segment (types 0 to 9 and 16 to 21). -fn is_slice(nal: &[u8]) -> bool { - let t = (nal[0] >> 1) & 0x3f; - t <= 9 || (16..=21).contains(&t) -} - -/// The P/B slice syntax ([`ec_h265::dec::cu_syntax::parse_slice`] with the zero-motion -/// stand-in, no DPB to derive motion from) over every P and B slice segment of every -/// stream. Pixel decode is off so the decoder only keeps parameter sets. Refusals are -/// fine; any other error is a failure. -#[test] -fn inter_placeholder_runs_over_pb_slices() { - use ec_core::bitio::BitReader; - use ec_h265_syntax::nal::{NalUnitType, unescape_rbsp}; - use ec_h265_syntax::slice::{SliceHeader, SliceType}; - let streams = streams(); - assert!(!streams.is_empty(), "no conformance streams"); - let (mut pb_slices, mut decoded, mut refused) = (0usize, 0usize, 0usize); - for path in &streams { - let data = std::fs::read(path).expect("read bitstream"); - let mut dec = Decoder::new(); - dec.set_pixel_decode(false); - for nal in nal_units(&data) { - let code = (nal[0] >> 1) & 0x3f; - if is_slice(nal) { - let rbsp = unescape_rbsp(&nal[2..]); - let mut r = BitReader::new(&rbsp); - let _first = r.read_bit(); - if (16..=21).contains(&code) { - let _no_output_of_prior_pics = r.read_bit(); - } - let pps_id = r.read_ue().unwrap_or(u32::MAX); - if let Some(pps) = dec.pps(pps_id) - && let Some(sps) = dec.sps(pps.sps_id) - && let Ok((header, pos)) = - SliceHeader::parse(&rbsp, sps, pps, NalUnitType::from_code(code)) - && header.slice_type != SliceType::I - && header.first_slice_segment_in_pic - { - pb_slices += 1; - let off = (pos.header_bits / 8) as usize; - let slice_data = rbsp.get(off..).unwrap_or(&[]); - let mut zero = ec_h265::dec::cu_syntax::ZeroMotion; - match ec_h265::dec::cu_syntax::parse_slice( - sps, - pps, - &header, - slice_data, - &mut zero, - &mut |_| {}, - ) { - Ok(_) => decoded += 1, - Err(Error::Unsupported { .. }) => refused += 1, - Err(err) => { - panic!("{}: P/B placeholder failed: {err}", path.display()) - } - } - } - } - let _ = dec.push_nal(nal); - } - } - println!( - "inter syntax: {decoded} P/B slices parsed, {refused} refused by name, of {pb_slices} first-slice P/B segments" - ); -} diff --git a/crates/ec-h265/tests/it/dec_meta.rs b/crates/ec-h265/tests/it/dec_meta.rs deleted file mode 100644 index c7a2bd55..00000000 --- a/crates/ec-h265/tests/it/dec_meta.rs +++ /dev/null @@ -1,244 +0,0 @@ -//! Metadata on the decoder's output frames: HDR SEI from the IRAP on, the VUI -//! colour description, the decoded picture hash, and the rule that Dolby Vision -//! NAL units (62, 63) and malformed SEI change nothing. -//! -//! The streams come from `fixtures/vectors/hevc-jctvc`. Without them the tests - -use std::path::{Path, PathBuf}; - -use ec_h265::dec::{Decoder, Frame}; -use ec_h265_syntax::nal::{escape_rbsp, split_annex_b}; -use ec_h265_syntax::sei::{ContentLightLevel, MasteringDisplay, PictureHash}; - -fn stream_files() -> Vec { - let root = ec_testkit::fixture("vectors/hevc-jctvc"); - fn walk(dir: &Path, depth: u32, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - let mut paths: Vec = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); - paths.sort(); - for p in paths { - if p.is_dir() && depth > 0 { - walk(&p, depth - 1, out); - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { - out.push(p); - } - } - } - let mut out = Vec::new(); - walk(&root, 2, &mut out); - out -} - -/// The raw NAL units (two-byte header and escaped payload) of an Annex-B stream. -fn raw_nals(data: &[u8]) -> Vec> { - split_annex_b(data) - .iter() - .map(|n| { - let mut v = n.header.to_bytes().to_vec(); - v.extend_from_slice(n.payload); - v - }) - .collect() -} - -/// Decode with picture management only, returning every frame, or the first error. -fn decode(nals: &[Vec]) -> Result, String> { - let mut dec = Decoder::new(); - dec.set_pixel_decode(false); - for nal in nals { - dec.push_nal(nal).map_err(|e| e.to_string())?; - } - dec.flush().map_err(|e| e.to_string())?; - let mut frames = Vec::new(); - while let Some(f) = dec.next_frame() { - frames.push(f); - } - Ok(frames) -} - -/// The first conformance stream that decodes without error, with its NAL units. -fn clean_stream() -> Option<(String, Vec>)> { - for path in stream_files() { - let Ok(data) = std::fs::read(&path) else { - continue; - }; - let nals = raw_nals(&data); - if decode(&nals).is_ok() { - let name = path - .file_name() - .unwrap_or_default() - .to_string_lossy() - .to_string(); - return Some((name, nals)); - } - } - None -} - -fn require_stream() -> (String, Vec>) { - clean_stream().expect("no clean conformance stream") -} - -/// What a frame looks like to a caller, for comparing two decodes. -fn key(f: &Frame) -> (i32, u32, usize, usize, Vec, Vec, Vec) { - ( - f.poc, - f.au_index, - f.picture.width, - f.picture.height, - f.picture.y.clone(), - f.picture.cb.clone(), - f.picture.cr.clone(), - ) -} - -/// A NAL unit of the given type, with the payload escaped. -fn nal_unit(nal_type: u8, rbsp: &[u8]) -> Vec { - let mut v = vec![nal_type << 1, 1]; - escape_rbsp(rbsp, &mut v); - v -} - -fn is_vcl(nal: &[u8]) -> bool { - matches!((nal[0] >> 1) & 0x3f, 0..=21) -} - -/// The HDR10 mastering display of a 1000 nit, 0.0050 nit BT.2020 grade, then a -/// content light level of MaxCLL 1000 and MaxFALL 400, as one prefix SEI RBSP. -fn hdr10_prefix_rbsp() -> Vec { - let mut mdcv = Vec::new(); - for (x, y) in [ - (8500u16, 39_850u16), - (6550, 2300), - (35_400, 14_600), - (15_635, 16_450), - ] { - mdcv.extend_from_slice(&x.to_be_bytes()); - mdcv.extend_from_slice(&y.to_be_bytes()); - } - mdcv.extend_from_slice(&10_000_000u32.to_be_bytes()); - mdcv.extend_from_slice(&50u32.to_be_bytes()); - let mut rbsp = vec![137, 24]; - rbsp.extend_from_slice(&mdcv); - rbsp.extend_from_slice(&[144, 4, 0x03, 0xe8, 0x01, 0x90, 0x80]); - rbsp -} - -#[test] -fn dolby_vision_nal_units_change_nothing() { - let (name, nals) = require_stream(); - let base = decode(&nals).unwrap(); - let mut injected = Vec::new(); - for nal in &nals { - injected.push(vec![62 << 1, 1, 0xde, 0xad, 0xbe, 0xef]); - injected.push(vec![63 << 1, 1, 0x80]); - injected.push(nal.clone()); - } - let with_rpu = decode(&injected).unwrap(); - assert!(!base.is_empty(), "{name}: no frames"); - assert_eq!(base.len(), with_rpu.len(), "{name}: frame count changed"); - for (a, b) in base.iter().zip(&with_rpu) { - assert_eq!( - key(a), - key(b), - "{name}: a frame changed with type 62/63 NAL units" - ); - } -} - -#[test] -fn malformed_sei_is_skipped_and_the_stream_decodes_the_same() { - let (name, nals) = require_stream(); - let base = decode(&nals).unwrap(); - let mut injected = Vec::new(); - for nal in &nals { - // A message that runs past the RBSP, a suffix SEI with a reserved hash type, - // and one with a short mastering display payload. - injected.push(nal_unit(39, &[5, 9, 1, 2, 0x80])); - injected.push(nal_unit(40, &[132, 2, 3, 0, 0x80])); - let mut short_mdcv = vec![137, 23]; - short_mdcv.extend_from_slice(&[0; 23]); - short_mdcv.push(0x80); - injected.push(nal_unit(39, &short_mdcv)); - injected.push(nal.clone()); - } - let with_bad = decode(&injected).unwrap(); - assert_eq!(base.len(), with_bad.len(), "{name}: frame count changed"); - for (a, b) in base.iter().zip(&with_bad) { - assert_eq!(key(a), key(b), "{name}: a frame changed with malformed SEI"); - assert!( - b.mastering_display().is_none(), - "{name}: a malformed SEI produced metadata" - ); - } -} - -#[test] -fn hdr_sei_applies_to_every_frame_from_the_irap_on() { - let (name, nals) = require_stream(); - let mut injected = Vec::new(); - let mut placed = false; - for nal in &nals { - if !placed && is_vcl(nal) { - // A prefix SEI in the first access unit, before its first slice. - injected.push(nal_unit(39, &hdr10_prefix_rbsp())); - placed = true; - } - injected.push(nal.clone()); - } - let frames = decode(&injected).unwrap(); - assert!(!frames.is_empty(), "{name}: no frames"); - for f in &frames { - let md: &MasteringDisplay = f.mastering_display().expect("MDCV on every frame"); - assert_eq!(md.display_primaries[0], (8500, 39_850)); - assert_eq!(md.white_point, (15_635, 16_450)); - assert_eq!(md.max_nits(), 1000.0); - assert!((md.min_nits() - 0.005).abs() < 1e-6); - let cll: &ContentLightLevel = f.content_light_level().expect("CLL on every frame"); - assert_eq!( - (cll.max_content_light_level, cll.max_pic_average_light_level), - (1000, 400) - ); - assert_eq!(f.alternative_transfer_characteristics(), None); - } -} - -#[test] -fn picture_hash_attaches_to_the_picture_it_follows() { - let (name, nals) = require_stream(); - // One MD5 plane: payloadType 132, payloadSize 17, hash_type 0, the digest. - let digest = [0x5au8; 16]; - let mut hash_rbsp = vec![132, 17, 0]; - hash_rbsp.extend_from_slice(&digest); - hash_rbsp.push(0x80); - - let mut injected = Vec::new(); - let mut placed = false; - for nal in &nals { - injected.push(nal.clone()); - // A suffix SEI right after the first slice: it belongs to access unit 0. - if !placed && is_vcl(nal) { - injected.push(nal_unit(40, &hash_rbsp)); - placed = true; - } - } - let frames = decode(&injected).unwrap(); - assert!(placed, "{name}: no slice NAL unit"); - let first = frames - .iter() - .find(|f| f.au_index == 0) - .expect("access unit 0 is output"); - match first.picture_hash() { - Some(PictureHash::Md5(d)) => assert_eq!(d, &[digest]), - other => panic!("{name}: access unit 0 hash is {other:?}"), - } - assert!( - frames - .iter() - .filter(|f| f.au_index != 0) - .all(|f| f.picture_hash().is_none()), - "{name}: a hash leaked to another picture" - ); -} diff --git a/crates/ec-h265/tests/it/dec_shell.rs b/crates/ec-h265/tests/it/dec_shell.rs deleted file mode 100644 index 027386b4..00000000 --- a/crates/ec-h265/tests/it/dec_shell.rs +++ /dev/null @@ -1,454 +0,0 @@ -//! Picture management of the stateful decoder (`ec_h265::dec`): POC, RPS and -//! marking, bumping, reference lists, and the JCT-VC conformance sweep. -//! -//! The sweep parses every slice of every stream through the picture-management -//! path (pixel decode off) and checks the output order against ffprobe. Streams -//! whose slices are all intra are also pixel-decoded and compared with ffmpeg's - -use std::collections::VecDeque; -use std::path::{Path, PathBuf}; - -use ec_h265::dec::dpb::{Dpb, DpbLimits, Marking, PendingFrame}; -use ec_h265::dec::poc::derive_poc; -use ec_h265::dec::rps::{RpsInput, build_ref_lists}; -use ec_h265::dec::shared::SharedPic; -use ec_h265::dec::{Decoder, NalOutcome}; -use ec_h265::decode::DecodedPicture; -use ec_h265_syntax::slice::{LongTermRef, SliceHeader, SliceType}; -use ec_h265_syntax::{ConformanceWindow, Pps, ShortTermRefPicSet}; - -fn picture(w: usize, h: usize) -> DecodedPicture { - DecodedPicture { - width: w, - height: h, - bit_depth: 8, - bit_depth_c: 8, - chroma_format_idc: 1, - y: Vec::new(), - cb: Vec::new(), - cr: Vec::new(), - } -} - -fn st_set(before: &[i32], after: &[i32]) -> ShortTermRefPicSet { - let mut st = ShortTermRefPicSet { - num_negative: before.len() as u32, - num_positive: after.len() as u32, - ..ShortTermRefPicSet::default() - }; - for (i, &d) in before.iter().enumerate() { - st.delta_poc_s0[i] = d; - st.used_s0[i] = true; - } - for (i, &d) in after.iter().enumerate() { - st.delta_poc_s1[i] = d; - st.used_s1[i] = true; - } - st -} - -fn rps_input<'a>( - poc: i32, - st: &'a ShortTermRefPicSet, - lt: &'a [LongTermRef], - fill: Option<(u32, u32)>, -) -> RpsInput<'a> { - RpsInput { - poc, - log2_max_poc_lsb: 4, - st, - lt, - irap_no_rasl: false, - width: 16, - height: 16, - chroma_format_idc: 1, - fill, - } -} - -fn add(dpb: &mut Dpb, poc: i32, marking: Marking, output: bool) -> u32 { - dpb.insert( - poc, - marking, - output, - std::sync::Arc::new(SharedPic::from_planes(poc, picture(16, 16))), - ConformanceWindow::default(), - poc as u32, - ) -} - -#[test] -fn poc_follows_the_lsb_without_wrapping() { - assert_eq!(derive_poc(5, 4, 7, false), 7); - assert_eq!(derive_poc(0, 4, 0, false), 0); -} - -#[test] -fn poc_msb_wraps_forward_at_the_half_window() { - // prevTid0 = 0, lsb 14 of 16: 14 - 0 > 8, so the MSB is -16 and POC is -2. - assert_eq!(derive_poc(0, 4, 14, false), -2); -} - -#[test] -fn poc_msb_wraps_backward_past_the_maximum() { - // prevTid0 = 14 (lsb 14), lsb 2: 14 - 2 >= 8, so the MSB advances to 16. - assert_eq!(derive_poc(14, 4, 2, false), 18); -} - -#[test] -fn poc_of_an_irap_with_no_rasl_output_has_no_msb() { - assert_eq!(derive_poc(37, 4, 5, true), 5); -} - -#[test] -fn rps_marks_what_it_names_and_drops_the_rest() { - let mut dpb = Dpb::new(); - let ids: Vec = [0, 1, 2, 3, 4, 5, 6, 7] - .iter() - .map(|&p| add(&mut dpb, p, Marking::ShortTerm, false)) - .collect(); - // Current POC 8 names 7, 5 and 4 (deltas -1, -3, -4). 0..3 and 6 drop out. - let st = st_set(&[-1, -3, -4], &[]); - let set = dpb.apply_rps(&rps_input(8, &st, &[], Some((8, 8)))); - let before: Vec = set.st_curr_before.iter().map(|e| e.poc).collect(); - assert_eq!(before, vec![7, 5, 4]); - assert!(set.st_curr_after.is_empty()); - assert!(set.lt_curr.is_empty()); - assert_eq!(set.st_curr_before[0].id, ids[7]); - for &p in &[0usize, 1, 2, 3, 6] { - assert_eq!(dpb.get(ids[p]).unwrap().marking, Marking::Unused, "POC {p}"); - } - assert_eq!(dpb.get(ids[5]).unwrap().marking, Marking::ShortTerm); - dpb.remove_unneeded(); - assert_eq!(dpb.len(), 3); -} - -#[test] -fn rps_generates_a_missing_reference_as_grey() { - let mut dpb = Dpb::new(); - add(&mut dpb, 4, Marking::ShortTerm, false); - // Current POC 8 names POC 6 (absent) and POC 4. - let st = st_set(&[-2, -4], &[]); - let set = dpb.apply_rps(&rps_input(8, &st, &[], Some((8, 8)))); - assert_eq!(set.st_curr_before.len(), 2); - let generated = dpb - .get(set.st_curr_before[0].id) - .expect("generated picture"); - assert_eq!(generated.poc, 6); - assert!(!generated.needed_for_output); - let planes = generated.picture.read_planes(); - assert_eq!(planes.y.len(), 16 * 16); - assert!(planes.y.iter().all(|&v| v == 128)); -} - -#[test] -fn rps_long_term_entry_matches_by_lsb_and_converts_marking() { - let mut dpb = Dpb::new(); - let lt_id = add(&mut dpb, 16, Marking::ShortTerm, false); - // PocLsbLt 0 with no MSB: the picture with POC & 15 == 0 is POC 16. - let lt = [LongTermRef { - poc_lsb_lt: 0, - used_by_curr: true, - delta_poc_msb_present: false, - delta_poc_msb_cycle: 0, - }]; - let st = ShortTermRefPicSet::default(); - let set = dpb.apply_rps(&rps_input(20, &st, <, Some((8, 8)))); - assert_eq!(set.lt_curr.len(), 1); - assert_eq!(set.lt_curr[0].id, lt_id); - assert!(set.lt_curr[0].long_term); - assert_eq!(dpb.get(lt_id).unwrap().marking, Marking::LongTerm); -} - -#[test] -fn bumping_outputs_in_poc_order_under_the_reorder_limit() { - let limits = DpbLimits { - max_dec_pic_buffering: 6, - max_num_reorder: 2, - max_latency_plus1: 0, - }; - let mut dpb = Dpb::new(); - let mut out: VecDeque = VecDeque::new(); - // Decode order 0, 8, 4, 2: a reorder limit of 2 forces output as it goes. - for poc in [0, 8, 4, 2] { - add(&mut dpb, poc, Marking::Unused, true); - while dpb.needs_bumping(&limits, false) && dpb.bump(&mut out) {} - } - let early: Vec = out.iter().map(|f| f.poc).collect(); - assert_eq!(early, vec![0, 2]); - dpb.drain(&mut out); - let all: Vec = out.iter().map(|f| f.poc).collect(); - assert_eq!(all, vec![0, 2, 4, 8]); - assert!(dpb.is_empty()); -} - -#[test] -fn bumping_honours_the_latency_limit() { - let limits = DpbLimits { - max_dec_pic_buffering: 6, - max_num_reorder: 4, - max_latency_plus1: 1, - }; - let mut dpb = Dpb::new(); - let mut out = VecDeque::new(); - add(&mut dpb, 0, Marking::Unused, true); - assert!(!dpb.needs_bumping(&limits, false)); - // SpsMaxLatencyPictures = 4 + 1 - 1 = 4: a picture that waited 4 times goes out. - dpb.pictures_mut()[0].latency = 4; - assert!(dpb.needs_bumping(&limits, false)); - assert!(dpb.bump(&mut out)); - assert_eq!(out.len(), 1); -} - -#[test] -fn bumping_drops_a_full_buffer_only_when_asked() { - let limits = DpbLimits { - max_dec_pic_buffering: 2, - max_num_reorder: 8, - max_latency_plus1: 0, - }; - let mut dpb = Dpb::new(); - add(&mut dpb, 0, Marking::ShortTerm, false); - add(&mut dpb, 2, Marking::ShortTerm, false); - assert!(dpb.needs_bumping(&limits, true)); - assert!(!dpb.needs_bumping(&limits, false)); -} - -#[test] -fn reference_lists_cycle_and_follow_the_modification() { - let mut dpb = Dpb::new(); - let a = add(&mut dpb, 4, Marking::ShortTerm, false); - let b = add(&mut dpb, 6, Marking::ShortTerm, false); - let c = add(&mut dpb, 10, Marking::ShortTerm, false); - let st = st_set(&[-4, -2], &[2]); - let set = dpb.apply_rps(&rps_input(8, &st, &[], Some((8, 8)))); - assert_eq!( - set.st_curr_before.iter().map(|e| e.id).collect::>(), - vec![a, b] - ); - assert_eq!( - set.st_curr_after.iter().map(|e| e.id).collect::>(), - vec![c] - ); - - let pps = Pps::default(); - let mut header = SliceHeader::intra(&pps, 0); - header.slice_type = SliceType::B; - header.num_ref_idx_l0_active_minus1 = 3; - header.num_ref_idx_l1_active_minus1 = 1; - let lists = build_ref_lists(&set, &header).expect("lists"); - let l0: Vec = lists.l0.iter().map(|e| e.id).collect(); - assert_eq!(l0, vec![a, b, c, a]); - let l1: Vec = lists.l1.iter().map(|e| e.id).collect(); - assert_eq!(l1, vec![c, a]); - - header.list_entry = [vec![2, 2, 0, 1], vec![1, 0]]; - let lists = build_ref_lists(&set, &header).expect("modified lists"); - assert_eq!( - lists.l0.iter().map(|e| e.id).collect::>(), - vec![c, c, a, b] - ); - assert_eq!( - lists.l1.iter().map(|e| e.id).collect::>(), - vec![a, c] - ); -} - -#[test] -fn decoder_refuses_out_of_scope_parameter_sets_and_skips_layers() { - let mut dec = Decoder::new(); - // A VPS-typed NAL on layer 1 is skipped whatever its payload. - let layer1 = [32u8 << 1, 0b0000_1001, 0xff]; - assert_eq!(dec.push_nal(&layer1).unwrap(), NalOutcome::Skipped); - // SEI and filler are ignored. - assert_eq!( - dec.push_nal(&[39 << 1, 1, 0x80]).unwrap(), - NalOutcome::Skipped - ); - assert_eq!( - dec.push_nal(&[62 << 1, 1, 0x80]).unwrap(), - NalOutcome::Skipped - ); - assert!(dec.next_frame().is_none()); -} - -fn run(args: &[&str], file: &Path) -> Result, String> { - let out = ec_testkit::ffprobe() - .args(["-v", "error"]) - .args(args) - .arg(file) - .output() - .map_err(|e| e.to_string())?; - if !out.status.success() { - return Err(String::from_utf8_lossy(&out.stderr).trim().to_string()); - } - Ok(out.stdout) -} - -fn numbers(text: &[u8]) -> Vec { - String::from_utf8_lossy(text) - .lines() - .filter_map(|l| l.trim().trim_end_matches(',').parse().ok()) - .collect() -} - -/// The conformance streams: the first `.bin` or `.bit` bitstream of each zip's -/// by name. Some zips extract one directory deeper, so two levels are searched. -fn streams() -> Vec { - let root = ec_testkit::fixture("vectors/hevc-jctvc"); - fn bitstreams_in(dir: &Path, depth: u32, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - let mut paths: Vec = entries.filter_map(|e| e.ok().map(|e| e.path())).collect(); - paths.sort(); - for p in paths { - if p.is_dir() && depth > 0 { - bitstreams_in(&p, depth - 1, out); - } else if matches!(p.extension().and_then(|x| x.to_str()), Some("bin" | "bit")) { - out.push(p); - } - } - } - let dirs = std::fs::read_dir(&root).expect("fixture directory"); - let mut dirs: Vec = dirs.filter_map(|e| e.ok().map(|e| e.path())).collect(); - dirs.sort(); - dirs.into_iter() - .filter(|d| d.is_dir()) - .filter_map(|d| { - let mut found = Vec::new(); - bitstreams_in(&d, 2, &mut found); - found.into_iter().next() - }) - .collect() -} - -/// Output order from our decoder, picture management only: (POC, AU index). -fn our_order(data: &[u8]) -> Result, String> { - let mut dec = Decoder::new(); - dec.set_pixel_decode(false); - dec.decode_annex_b(data).map_err(|e| e.to_string())?; - dec.flush().map_err(|e| e.to_string())?; - let mut order = Vec::new(); - while let Some(f) = dec.next_frame() { - order.push((f.poc, f.au_index)); - } - Ok(order) -} - -/// Output order from ffprobe: the access-unit index (by packet position in -/// decode order) of each frame, in display order. -fn ffprobe_order(path: &Path) -> Result, String> { - let packets = numbers(&run( - &[ - "-select_streams", - "v:0", - "-show_entries", - "packet=pos", - "-of", - "csv=p=0", - ], - path, - )?); - let frames = numbers(&run( - &[ - "-select_streams", - "v:0", - "-show_entries", - "frame=pkt_pos", - "-of", - "csv=p=0", - ], - path, - )?); - frames - .iter() - .map(|pos| { - packets - .iter() - .position(|p| p == pos) - .map(|i| i as u32) - .ok_or_else(|| format!("frame position {pos} is no packet position")) - }) - .collect() -} - -/// Streams where ffprobe is not the reference: the spec's frame count (from the -/// conformance description) and why ffprobe differs. Our count must equal the spec's. -fn spec_expectation(name: &str) -> Option<(usize, &'static str)> { - match name { - // Unequal luma (10) and chroma (9) bit depth: ffmpeg decodes nothing. - "TSUNEQBD_A_MAIN10_Technicolor_2" => Some((8, "ffmpeg unsupported (unequal bit depths)")), - // Six IDR pictures, each with its own VPS/SPS/PPS and resolution: ffmpeg outputs 2. - "VPSSPSPPS_A_MainConcept_1" => Some((6, "ffmpeg outputs 2")), - _ => None, - } -} - -#[test] -fn conformance_output_order_matches_ffprobe() { - let streams = streams(); - assert!(!streams.is_empty(), "no conformance streams"); - let mut table = String::from("stream\tpictures_out\tffprobe_out\tresult\tdetail\n"); - let mut pass = 0usize; - let mut spec_ok = 0usize; - for path in &streams { - let name = path - .file_stem() - .unwrap_or_default() - .to_string_lossy() - .to_string(); - let data = match std::fs::read(path) { - Ok(d) => d, - Err(e) => { - table.push_str(&format!("{name}\t-\t-\tFAIL\tread: {e}\n")); - continue; - } - }; - let ours = our_order(&data); - let theirs = ffprobe_order(path); - let row = match (ours, theirs) { - (Ok(ours), Ok(theirs)) => { - let our_aus: Vec = ours.iter().map(|(_, au)| *au).collect(); - let pocs: Vec = ours.iter().take(8).map(|(p, _)| p.to_string()).collect(); - let detail = format!("first POCs {}", pocs.join(",")); - match spec_expectation(&name) { - // The spec's own count is the reference where ffprobe is wrong. - Some((frames, why)) => { - let verdict = if ours.len() == frames { "SPEC" } else { "FAIL" }; - if verdict == "SPEC" { - spec_ok += 1; - } - format!( - "{name}\t{}\t{}\t{verdict}\tspec: {frames} frames, {why}; {detail}\n", - ours.len(), - theirs.len(), - ) - } - None => { - let verdict = if our_aus == theirs { "PASS" } else { "FAIL" }; - if verdict == "PASS" { - pass += 1; - } - format!( - "{name}\t{}\t{}\t{verdict}\t{detail}\n", - ours.len(), - theirs.len(), - ) - } - } - } - (Err(e), _) => format!("{name}\t-\t-\tREFUSED\t{e}\n"), - (_, Err(e)) => format!("{name}\t-\t-\tSKIP\tffprobe: {e}\n"), - }; - table.push_str(&row); - } - match std::env::var("EC_H265_POC_TABLE") { - Ok(path) => std::fs::write(&path, &table).expect("write POC table"), - Err(_) => print!("{table}"), - } - eprintln!( - "POC/output order: {pass}/{} streams PASS, {spec_ok} SPEC (spec frame count, ffprobe differs)", - streams.len() - ); -} diff --git a/crates/ec-h265/tests/it/dolby_vision_p8.rs b/crates/ec-h265/tests/it/dolby_vision_p8.rs deleted file mode 100644 index ebf9bf1e..00000000 --- a/crates/ec-h265/tests/it/dolby_vision_p8.rs +++ /dev/null @@ -1,197 +0,0 @@ -//! Dolby Vision profile 8 layout: the HEVC base layer decodes, and the RPU NAL -//! units (type 62) are ignored. -//! -//! The base layer is generated here with ffmpeg's libx265 from a test pattern, so no -//! copyrighted media is involved. Type 62 NAL units with arbitrary payload are then -//! inserted in front of every VCL NAL unit. ec-h265 must decode the injected stream -//! to exactly the pictures it decodes from the clean one, and ffmpeg must decode the -//! injected stream to the same bytes. - -use ec_h265::Decoder; -use ec_h265::dec::Frame; -use ec_h265_syntax::nal::{escape_rbsp, split_annex_b}; -use std::path::Path; - -const WIDTH: usize = 352; -const HEIGHT: usize = 288; -const FRAMES: usize = 12; - -/// The base layer: libx265, an IDR every 4 pictures, P pictures in between, no B. -fn encode_base_layer(dir: &Path) -> Result, String> { - let out = dir.join("base.hevc"); - let frames = FRAMES.to_string(); - let source = format!("testsrc2=size={WIDTH}x{HEIGHT}:rate=30"); - let status = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-f", "lavfi", "-i"]) - .arg(&source) - .arg("-frames:v") - .arg(&frames) - .args([ - "-c:v", "libx265", "-preset", "veryfast", "-pix_fmt", "yuv420p", - ]) - .args([ - "-x265-params", - "keyint=4:min-keyint=4:bframes=0:scenecut=0:log-level=error", - "-f", - "hevc", - ]) - .arg(&out) - .output() - .map_err(|e| e.to_string())?; - if !status.status.success() { - return Err(String::from_utf8_lossy(&status.stderr).to_string()); - } - std::fs::read(&out).map_err(|e| e.to_string()) -} - -/// A type 62 NAL unit with arbitrary payload: zero runs, start-code-like bytes and -/// a trailing zero, escaped as a NAL unit must be. `seed` varies it per slice. -fn rpu_nal(seed: u8) -> Vec { - let rbsp = [ - 0x19, 0x08, 0x00, 0x00, 0x01, seed, 0x00, 0x00, 0x03, 0xff, 0x80, 0x00, - ]; - let mut v = vec![62 << 1, 1]; - escape_rbsp(&rbsp, &mut v); - v -} - -/// The stream with a type 62 NAL unit in front of every VCL NAL unit, each with -/// a four-byte start code. -fn inject_rpu(annex_b: &[u8]) -> Vec { - let mut out = Vec::with_capacity(annex_b.len() * 2); - let mut slice = 0u8; - for n in split_annex_b(annex_b) { - let mut nal = n.header.to_bytes().to_vec(); - nal.extend_from_slice(n.payload); - if matches!((nal[0] >> 1) & 0x3f, 0..=21) { - out.extend_from_slice(&[0, 0, 0, 1]); - out.extend_from_slice(&rpu_nal(slice)); - slice = slice.wrapping_add(1); - } - out.extend_from_slice(&[0, 0, 0, 1]); - out.extend_from_slice(&nal); - } - out -} - -/// Count of NAL units of `nal_type` in an Annex B stream. -fn count_nal_type(annex_b: &[u8], nal_type: u8) -> usize { - split_annex_b(annex_b) - .iter() - .filter(|n| (n.header.to_bytes()[0] >> 1) & 0x3f == nal_type) - .count() -} - -/// One picture as 4:2:0 bytes, cropped to the conformance window. -fn cropped_yuv(frame: &Frame) -> Vec { - let pic = &frame.picture; - let win = &frame.window; - let (lx0, lx1) = (2 * win.left as usize, pic.width - 2 * win.right as usize); - let (ly0, ly1) = (2 * win.top as usize, pic.height - 2 * win.bottom as usize); - let (cx0, cx1) = (win.left as usize, pic.width / 2 - win.right as usize); - let (cy0, cy1) = (win.top as usize, pic.height / 2 - win.bottom as usize); - let mut out = Vec::new(); - for row in ly0..ly1 { - out.extend( - pic.y[row * pic.width + lx0..row * pic.width + lx1] - .iter() - .map(|&v| v as u8), - ); - } - let cw = pic.width / 2; - for plane in [&pic.cb, &pic.cr] { - for row in cy0..cy1 { - out.extend( - plane[row * cw + cx0..row * cw + cx1] - .iter() - .map(|&v| v as u8), - ); - } - } - out -} - -/// Every picture ec-h265 outputs, as one yuv420p byte string, and the picture count. -fn decode_ec(annex_b: &[u8]) -> Result<(Vec, usize), String> { - let mut dec = Decoder::new(); - dec.decode_annex_b(annex_b).map_err(|e| e.to_string())?; - dec.flush().map_err(|e| e.to_string())?; - let mut out = Vec::new(); - let mut count = 0; - while let Some(frame) = dec.next_frame() { - out.extend(cropped_yuv(&frame)); - count += 1; - } - Ok((out, count)) -} - -/// Every picture ffmpeg outputs, as yuv420p. -fn decode_ffmpeg(path: &Path, out: &Path) -> Result, String> { - let status = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-i"]) - .arg(path) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .arg(out) - .output() - .map_err(|e| e.to_string())?; - if !status.status.success() { - return Err(String::from_utf8_lossy(&status.stderr).to_string()); - } - std::fs::read(out).map_err(|e| e.to_string()) -} - -fn first_difference(a: &[u8], b: &[u8]) -> Option { - a.iter() - .zip(b) - .position(|(x, y)| x != y) - .or_else(|| (a.len() != b.len()).then(|| a.len().min(b.len()))) -} - -#[test] -fn dolby_vision_p8_base_layer_decodes_and_rpu_is_ignored() { - let dir = std::env::temp_dir().join(format!("ec-h265-dvp8-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("temp dir"); - - let clean = encode_base_layer(&dir).expect("libx265 base layer"); - let injected = inject_rpu(&clean); - let vcl = split_annex_b(&clean) - .iter() - .filter(|n| matches!((n.header.to_bytes()[0] >> 1) & 0x3f, 0..=21)) - .count(); - assert_eq!( - count_nal_type(&clean, 62), - 0, - "clean base layer has type 62 NAL units" - ); - assert_eq!( - count_nal_type(&injected, 62), - vcl, - "one type 62 NAL unit per slice" - ); - - let (ec_clean, n_clean) = decode_ec(&clean).expect("ec-h265 decodes the clean base layer"); - let (ec_injected, n_injected) = - decode_ec(&injected).expect("ec-h265 decodes the stream with type 62 NAL units"); - assert_eq!(n_clean, FRAMES, "clean stream picture count"); - assert_eq!(n_injected, FRAMES, "injected stream picture count"); - let frame_bytes = WIDTH * HEIGHT * 3 / 2; - assert_eq!(ec_clean.len(), FRAMES * frame_bytes); - if let Some(at) = first_difference(&ec_clean, &ec_injected) { - panic!("type 62 NAL units changed ec-h265's output at byte {at}"); - } - - let injected_path = dir.join("dv-p8.hevc"); - std::fs::write(&injected_path, &injected).expect("write injected stream"); - let ffmpeg = decode_ffmpeg(&injected_path, &dir.join("ffmpeg.yuv")) - .expect("ffmpeg decodes the injected stream"); - assert_eq!( - ffmpeg.len(), - ec_injected.len(), - "ffmpeg picture bytes differ from ec-h265's" - ); - if let Some(at) = first_difference(&ec_injected, &ffmpeg) { - panic!("ec-h265 and ffmpeg differ on the injected stream at byte {at}"); - } - - let _ = std::fs::remove_dir_all(&dir); -} diff --git a/crates/ec-h265/tests/it/encode.rs b/crates/ec-h265/tests/it/encode.rs deleted file mode 100644 index 6c4b2f51..00000000 --- a/crates/ec-h265/tests/it/encode.rs +++ /dev/null @@ -1,922 +0,0 @@ -//! Encoder rate-quality gate: BD-PSNR of this encoder against x265 at matched -//! features over a QP sweep, modelled on ec-h264's `bd_psnr_vs_x264`. -//! -//! Both encoders code the same synthetic 352x288 24-picture clip, both are read -//! the same way — on ffmpeg's decode of the stream, not on either encoder's -//! own reconstruction — and x265's psychovisual and adaptive tools are off so -//! the comparison is at matched features, not at matched marketing. - -use crate::common::{pin_loud, pin_or_bail}; -use ec_core::frame::VideoFrame; -use ec_h265::encoder::{Encoder, EncoderConfig, RateControl, TransformSkip}; - -/// One decoded picture: Y, Cb and Cr planes, cropped and tightly packed. -type Planes = (Vec, Vec, Vec); - -/// Floor for [`bd_psnr_vs_x265`] on the synthetic clip. Calibrated on the -/// measured value with 0.15 dB of room for platform noise, so the advantage can -/// shrink but not grow unnoticed; it is not a claim that the number is fine. -/// -/// Measured +2.507 dB luma / +3.238 dB YUV at `rdo_candidates: 5` (352x288, -/// 24 pictures of `Clip::render_smooth`, x265 at QP 22/26/30/34, our ladder -/// auto-shifted from a QP-26 probe to 16/20/24/28, both sides decoded through -/// ffmpeg, union-range BD-PSNR, 0% extrapolation both sides). This is a -/// smooth-gradient result: it does NOT hold on real content, where our -/// encoder is no leaner than x265 at matched QP (the probe measures a shift of -/// 0) and the aligned BD is negative. Real-clip numbers, 24 pictures after -/// 1500, ladders auto-aligned to 22/26/30/34, 0% extrapolation both sides: -/// • 3840x1608 film: -0.685 dB luma / -0.703 dB YUV -/// • 1138x640 web clip: -0.507 dB luma / -0.556 dB YUV -/// • 2560x1440 screen capture: -2.465 dB luma / -2.360 dB YUV -/// • 1080p phone clip: -0.366 dB luma / -0.387 dB YUV -/// Those two are the real gap to close; the synthetic number only guards -/// against regression on a clip whose content is pinned. -/// -/// Previous run measured -38.258 dB luma with both sides at QP 22/26/30/34; -/// that number was meaningless because the two curves' bitrate ranges did not -/// overlap (50% extrapolation on our side) — a fixed QP offset could not -/// bridge encoders whose relative leanness varies with content. The shallow -/// all-intra rate-quality slope is genuine content behaviour (x264 forced -/// all-intra shows the same shape); the fix is to auto-align the ladders from -/// a probe encode, not to change x265's rate control. -const BD_PSNR_VS_X265_FLOOR: f64 = 2.357; - -/// A synthetic source with real structure: smooth gradients, a band of -/// sinusoidal texture and a translating box, so prediction matters — the half -/// a rate-quality comparison is about. Ported verbatim from ec-h264's `Clip` -/// (minus the `view()` method this encoder's `encode_idr_planes` does not -/// need). -struct Clip { - w: usize, - h: usize, - y: Vec, - u: Vec, - v: Vec, -} - -impl Clip { - fn new(w: usize, h: usize) -> Clip { - Clip { - w, - h, - y: vec![0; w * h], - u: vec![0; w / 2 * h / 2], - v: vec![0; w / 2 * h / 2], - } - } - - /// Frame `t` without a per-sample noise field: smooth gradients, a band of - /// sinusoidal texture and a box translating by whole and sub-sample - /// amounts. Content where prediction matters, not where residual is - /// incompressible. - fn render_smooth(&mut self, t: usize) { - let (w, h) = (self.w, self.h); - let ft = t as f64; - for y in 0..h { - for x in 0..w { - let (fx, fy) = (x as f64, y as f64); - let ramp = (fx + fy * 0.5 - ft * 1.5) * 0.35; - let texture = if y > h / 3 && y < 2 * h / 3 { - 18.0 * ((fx * 0.19 + ft * 0.9).sin() + (fy * 0.11).cos()) - } else { - 0.0 - }; - let box_x = ((ft * 2.7) as usize) % (w.saturating_sub(48).max(1)); - let inside = x >= box_x && x < box_x + 48 && y >= h / 5 && y < h / 5 + 36; - let v = if inside { - 196.0 - texture * 0.5 - } else { - 40.0 + (ramp % 90.0).abs() + texture - }; - self.y[y * w + x] = v.clamp(0.0, 255.0) as u8; - } - } - for y in 0..h / 2 { - for x in 0..w / 2 { - let (fx, fy) = (x as f64, y as f64); - self.u[y * (w / 2) + x] = - (118.0 + 12.0 * ((fx * 0.05 + ft * 0.3).sin())).clamp(0.0, 255.0) as u8; - self.v[y * (w / 2) + x] = - (134.0 + 10.0 * ((fy * 0.04 - ft * 0.25).cos())).clamp(0.0, 255.0) as u8; - } - } - } -} - -/// Crop and tightly pack the Y, Cb and Cr planes of a reconstruction. -fn planes_of(frame: &VideoFrame) -> Planes { - let (w, h) = (frame.width as usize, frame.height as usize); - let mut out = Vec::new(); - for (i, (pw, ph)) in [(w, h), (w / 2, h / 2), (w / 2, h / 2)] - .into_iter() - .enumerate() - { - let plane = &frame.planes[i]; - let mut buf = Vec::with_capacity(pw * ph); - for row in 0..ph { - buf.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + pw]); - } - out.push(buf); - } - let v = out.pop().unwrap(); - let u = out.pop().unwrap(); - let y = out.pop().unwrap(); - (y, u, v) -} - -/// Mean squared error between two equal-length planes. -fn plane_mse(a: &[u8], b: &[u8]) -> f64 { - a.iter() - .zip(b) - .map(|(&x, &y)| { - let d = f64::from(x) - f64::from(y); - d * d - }) - .sum::() - / a.len() as f64 -} - -/// PSNR over all three planes, pooled by sample count the way x265 reports it: -/// for 4:2:0 that weights luma 6 and each chroma plane 1. A luma-only number -/// rewards an encoder for throwing chroma away, so any decision that can move -/// chroma bits is read here instead. -fn psnr_yuv(a: &Planes, b: &Planes) -> f64 { - let (n_y, n_c) = (a.0.len() as f64, a.1.len() as f64); - let sse = - plane_mse(&a.0, &b.0) * n_y + plane_mse(&a.1, &b.1) * n_c + plane_mse(&a.2, &b.2) * n_c; - let mse = sse / (n_y + 2.0 * n_c); - if mse == 0.0 { - 99.0 - } else { - 10.0 * (255.0 * 255.0 / mse).log10() - } -} - -fn psnr(a: &[u8], b: &[u8]) -> f64 { - let mse: f64 = a - .iter() - .zip(b) - .map(|(&x, &y)| { - let d = f64::from(x) - f64::from(y); - d * d - }) - .sum::() - / a.len() as f64; - if mse == 0.0 { - 99.0 - } else { - 10.0 * (255.0 * 255.0 / mse).log10() - } -} - -#[allow(clippy::needless_range_loop)] -fn cubic_fit(xs: [f64; 4], ys: [f64; 4]) -> [f64; 4] { - let mut a = [[0.0; 5]; 4]; - for i in 0..4 { - a[i] = [1.0, xs[i], xs[i] * xs[i], xs[i] * xs[i] * xs[i], ys[i]]; - } - for col in 0..4 { - let mut pivot = col; - for row in col + 1..4 { - if a[row][col].abs() > a[pivot][col].abs() { - pivot = row; - } - } - a.swap(col, pivot); - let div = a[col][col]; - assert!(div.abs() > 1e-12, "singular BD-PSNR fit"); - for j in col..5 { - a[col][j] /= div; - } - for row in 0..4 { - if row == col { - continue; - } - let f = a[row][col]; - for j in col..5 { - a[row][j] -= f * a[col][j]; - } - } - } - [a[0][4], a[1][4], a[2][4], a[3][4]] -} - -fn cubic_integral(c: [f64; 4], x: f64) -> f64 { - c[0] * x + c[1] * x * x / 2.0 + c[2] * x * x * x / 3.0 + c[3] * x * x * x * x / 4.0 -} - -/// BD-PSNR: average PSNR difference between two rate-quality curves over a -/// shared bitrate range. Modelled on ec-h264's `bd_psnr_delta`, with one -/// departure: the integration range is the *union* of the two curves' bitrate -/// extents, not their intersection. -/// -/// The h264 gate's encoders land in the same bitrate band at the same QP, so -/// the intersection is non-empty and the standard Bjøntegaard cubic integral -/// over it is well defined. Our h265 encoder's bitrate at matched QP can be -/// leaner or fatter than x265's depending on content, so the QP-ladder shift -/// is measured from a probe encode, not fixed — the union range is kept (not -/// clipped to the intersection) so the extrapolation share can be measured: -/// if either curve is extrapolated over more than 20% of the range, the test -/// fails with a named message instead of reporting a BD number that is a cubic -/// guess, not a measurement. The extrapolation shares are returned alongside -/// the number. -/// -/// Returns `(bd, cand_extrap, anc_extrap)` where the extrap shares are the -/// fraction of the integration range that each curve's measured bitrate span -/// does not cover (0 = fully measured, 1 = entirely extrapolated). -fn bd_psnr_delta(candidate: &[(f64, f64)], anchor: &[(f64, f64)]) -> (f64, f64, f64) { - let xs_candidate = std::array::from_fn(|i| candidate[i].0.ln()); - let ys_candidate = std::array::from_fn(|i| candidate[i].1); - let xs_anchor = std::array::from_fn(|i| anchor[i].0.ln()); - let ys_anchor = std::array::from_fn(|i| anchor[i].1); - // Union, not intersection: see the doc comment above. - let lo = xs_candidate - .iter() - .copied() - .fold(f64::INFINITY, f64::min) - .min(xs_anchor.iter().copied().fold(f64::INFINITY, f64::min)); - let hi = xs_candidate - .iter() - .copied() - .fold(f64::NEG_INFINITY, f64::max) - .max(xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max)); - let c_candidate = cubic_fit(xs_candidate, ys_candidate); - let c_anchor = cubic_fit(xs_anchor, ys_anchor); - let (cand_lo, cand_hi) = ( - xs_candidate.iter().copied().fold(f64::INFINITY, f64::min), - xs_candidate - .iter() - .copied() - .fold(f64::NEG_INFINITY, f64::max), - ); - let (anc_lo, anc_hi) = ( - xs_anchor.iter().copied().fold(f64::INFINITY, f64::min), - xs_anchor.iter().copied().fold(f64::NEG_INFINITY, f64::max), - ); - let cand_extrap = ((lo - cand_lo).max(0.0) + (hi - cand_hi).max(0.0)) / (cand_hi - cand_lo); - let anc_extrap = ((lo - anc_lo).max(0.0) + (hi - anc_hi).max(0.0)) / (anc_hi - anc_lo); - eprintln!( - " cubic extrapolation: candidate {cand_extrap:.0}% anchor {anc_extrap:.0}% of measured range" - ); - let bd = (cubic_integral(c_candidate, hi) - - cubic_integral(c_candidate, lo) - - cubic_integral(c_anchor, hi) - + cubic_integral(c_anchor, lo)) - / (hi - lo); - (bd, cand_extrap, anc_extrap) -} - -fn have_x265() -> bool { - ec_testkit::ffmpeg() - .args(["-v", "error", "-hide_banner", "-encoders"]) - .output() - .is_ok_and(|o| o.status.success() && String::from_utf8_lossy(&o.stdout).contains("libx265")) -} - -#[cfg(unix)] -#[test] -fn pin_loud_reds_on_an_ok_but_short_write() { - // The shape the two sites above left open: a write that reports success and - // leaves a file of a different length. A symlink to /dev/null accepts every - // byte and stores none, so `fs::write` returns Ok and the file is 0 bytes -- - // a stream path, silently empty. - let dir = std::env::temp_dir().join(format!("ec-h265-pinloud-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let path = dir.join("ok-but-short.265"); - let _ = std::fs::remove_file(&path); - std::os::unix::fs::symlink("/dev/null", &path).expect("symlink to /dev/null"); - let why = pin_loud("ok_but_short", &path, &[7u8; 1234]).unwrap_err(); - assert!(why.contains(&path.display().to_string()), "{why}"); - assert!(why.contains("file holds 0 of 1234 bytes"), "{why}"); - std::fs::remove_file(&path).ok(); - - // The control: the same call on a real file succeeds and leaves every byte. - let good = dir.join("whole.265"); - let bytes = vec![7u8; 1234]; - pin_loud("control", &good, &bytes).expect("a whole write is not short"); - assert_eq!(std::fs::read(&good).expect("read back"), bytes); - std::fs::remove_file(&good).ok(); - std::fs::remove_dir_all(&dir).ok(); -} - -#[cfg(unix)] -#[test] -fn pin_loud_reports_what_landed_under_a_size_cap() { - // The Err arm, driven for real: `ulimit -f` caps the file, the kernel stores - // everything up to the cap and only then returns EFBIG. The line must carry - // the bytes that actually LANDED (512 of a 1 KiB-block cap), not the count - // the writer confirmed, which is zero. - use std::process::Command; - let Ok(exe) = std::env::current_exe() else { - return; - }; - // SIGXFSZ's default action would kill the child before it can print; - // `trap '' XFSZ` sets SIG_IGN, which survives the exec. - let script = format!( - "ulimit -f 1; trap '' XFSZ; exec {} --exact encode::pin_loud_cap_child --nocapture", - exe.display() - ); - let out = Command::new("sh") - .args(["-c", &script]) - .env("EC_PINLOUD_CHILD", "1") - .output() - .expect("run the capped child"); - let text = format!( - "{}{}", - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr) - ); - assert!(!out.status.success(), "the capped write must fail: {text}"); - assert!(text.contains("file holds 512 of 4096 bytes"), "{text}"); - assert!( - text.contains("EFBIG") || text.contains("File too large"), - "{text}" - ); -} - -/// Child of [`pin_loud_reports_what_landed_under_a_size_cap`]: runs under -/// `ulimit -f 1` (a 1 KiB block cap) and pins 4096 bytes, so the write fails -/// partway. Inert unless the parent set `EC_PINLOUD_CHILD`. -#[test] -fn pin_loud_cap_child() { - if std::env::var_os("EC_PINLOUD_CHILD").is_none() { - return; - } - let dir = std::env::temp_dir().join(format!("ec-h265-pinloud-cap-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let path = dir.join("capped.265"); - let why = - pin_loud("capped", &path, &[7u8; 4096]).expect_err("4096 bytes cannot fit a 1 KiB cap"); - std::fs::remove_file(&path).ok(); - std::fs::remove_dir_all(&dir).ok(); - panic!("{why}"); -} - -/// Decode an Annex-B stream with ffmpeg, returning one I420 triple per picture. -fn ffmpeg_decode(stream: &[u8], w: usize, h: usize) -> Option> { - let dir = std::env::temp_dir().join(format!("ec-h265-enc-{}", std::process::id())); - std::fs::create_dir_all(&dir).ok()?; - let path = dir.join(format!("s{}.265", stream.len())); - pin_or_bail("ffmpeg_decode", &path, stream)?; - let out = ec_testkit::ffmpeg() - .args(["-v", "error"]) - .arg("-i") - .arg(&path) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "pipe:1"]) - .output() - .ok()?; - let _ = std::fs::remove_file(&path); - if !out.status.success() { - eprintln!("ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr)); - return None; - } - let frame = w * h * 3 / 2; - if frame == 0 || out.stdout.len() % frame != 0 { - eprintln!( - "ffmpeg returned {} bytes, not a whole number of {frame}-byte frames", - out.stdout.len() - ); - return None; - } - Some( - out.stdout - .chunks(frame) - .map(|f| { - let (y, rest) = f.split_at(w * h); - let (u, v) = rest.split_at(w / 2 * h / 2); - (y.to_vec(), u.to_vec(), v.to_vec()) - }) - .collect(), - ) -} - -/// Encode raw I420 pictures with x265 at constant QP, matched to what this -/// encoder actually does: intra-only (keyint 1), no B pictures, no scene cut -/// or lookahead, in-loop filters (SAO, deblock) off, adaptive quantisation off, -/// psychovisual RD and RDOQ off, RDOQ itself off, the shallowest intra TU -/// depth x265 allows (1, the closest it has to our -/// `max_transform_hierarchy_depth_intra=0`), and ipratio/pbratio/qcomp 1.0 so -/// constant-QP codes I pictures at the QP asked for. Returns the Annex-B -/// stream. -fn x265_encode_qp(sources: &[Planes], w: usize, h: usize, qp: i32) -> Option> { - let dir = std::env::temp_dir().join(format!("ec-h265-x265-{}", std::process::id())); - std::fs::create_dir_all(&dir).ok()?; - let raw = dir.join(format!("in-q{qp}.yuv")); - let out = dir.join(format!("out-q{qp}.265")); - let mut buf = Vec::with_capacity(sources.len() * w * h * 3 / 2); - for (y, u, v) in sources { - buf.extend_from_slice(y); - buf.extend_from_slice(u); - buf.extend_from_slice(v); - } - pin_or_bail("x265_encode_qp", &raw, &buf)?; - // The param list is the h264 gate's x264 list translated to x265's option - // names: psychovisual (psy-rd, psy-rdoq) and adaptive (aq-mode) tools off, - // plus the in-loop filters x265 adds and x264 does not have (no-sao, - // no-deblock), plus RDOQ off (rdoq-level=0) so the quantiser spends bits - // the same way ours does. The quantiser goes inside the param string as - // `qp=N`; `-x265-params qp=22` and `-x265-params rc=cqp:qp=22` produce - // byte-identical streams, so the `rc=cqp:` prefix is unnecessary. - // EC_H265_X265_PARAMS appends to attribute a single feature the same way - // EC_H264_X264_PARAMS does. - let params = format!( - "qp={qp}:keyint=1:bframes=0:scenecut=0:rc-lookahead=0:no-sao:{deblock}\ - aq-mode=0:psy-rd=0:psy-rdoq=0:rdoq-level=0:tu-intra-depth=1:ipratio=1.0:\ - pbratio=1.0:qcomp=1.0:chroma-qp-offset=0{extra}", - // x265 deblocks by default; `no-deblock` matches an encoder that does - // not, and EC_H265_X265_DEBLOCK=1 drops it so both sides filter. - deblock = if std::env::var("EC_H265_X265_DEBLOCK").is_ok_and(|v| v != "0") { - "" - } else { - "no-deblock:" - }, - extra = match std::env::var("EC_H265_X265_PARAMS") { - Ok(extra) if !extra.trim().trim_matches(':').is_empty() => - format!(":{}", extra.trim().trim_matches(':')), - _ => String::new(), - } - ); - let status = ec_testkit::ffmpeg() - .args(["-v", "error", "-y"]) - .args(["-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .args(["-s", &format!("{w}x{h}"), "-r", "1"]) - .arg("-i") - .arg(&raw) - .args(["-c:v", "libx265", "-preset", "medium"]) - .args(["-x265-params", ¶ms]) - .args(["-f", "hevc"]) - .arg(&out) - .status() - .ok()?; - let _ = std::fs::remove_file(&raw); - if !status.success() { - return None; - } - let stream = std::fs::read(&out).ok(); - let _ = std::fs::remove_file(&out); - stream -} - -/// BD-PSNR of this encoder against x265 at matched features. x265 is anchored -/// at QP 22/26/30/34; our ladder is shifted by a QP delta measured from a -/// probe encode at QP 26 (both sides), so the bitrate ranges overlap and the -/// cubic fit interpolates instead of extrapolating — regardless of whether -/// our encoder is leaner or fatter than x265 at matched QP on the content at -/// hand. Runs on the synthetic clip by default, so the number cannot rot -/// behind an `#[ignore]`; point `EC_H265_CLIP` at a media file to measure the -/// same thing on real content. -/// -/// Both curves are (bits, luma PSNR against the same source pictures), and -/// both are measured on ffmpeg's decode of the stream rather than on an -/// encoder's own reconstruction, so the two halves are read the same way. -/// BD-PSNR-YUV pools all three planes by sample count (luma weighted 6, each -/// chroma 1 for 4:2:0), the way x265 reports it. -/// -/// cargo test --release -p ec-h265 --test encode bd_psnr_vs_x265 -- --nocapture -/// EC_H265_CLIP= cargo test --release -p ec-h265 --test encode \ -/// bd_psnr_vs_x265 -- --nocapture -#[test] -fn bd_psnr_vs_x265() { - assert!(have_x265(), "the pinned ffmpeg has no libx265"); - let (w, h, sources) = match std::env::var_os("EC_H265_CLIP") { - Some(path) => clip_sources(&path, 24), - None => { - let (w, h, frames) = (352, 288, 24); - let mut clip = Clip::new(w, h); - let mut sources = Vec::with_capacity(frames); - for t in 0..frames { - clip.render_smooth(t); - sources.push((clip.y.clone(), clip.u.clone(), clip.v.clone())); - } - eprintln!("synthetic clip: {w}x{h}, {frames} pictures"); - (w, h, sources) - } - }; - - let ours = |qp: i32| { - let mut cfg = EncoderConfig::new(w as u32, h as u32); - cfg.rate_control = RateControl::ConstantQp(qp); - cfg.keep_recon = true; - cfg.threads = 0; - // Ablation knob: how many SATD survivors reach the full rate-distortion - // trial in the luma mode search. The shipped default is 5. - if let Ok(v) = std::env::var("EC_H265_CHROMA_RD") { - cfg.chroma_mode_search = v != "0"; - } - if let Ok(w) = std::env::var("EC_H265_CHROMA_W") { - cfg.chroma_rd_weight = w.parse().expect("EC_H265_CHROMA_W must be a number"); - } - if let Ok(v) = std::env::var("EC_H265_SDH") { - cfg.sign_hiding = v != "0"; - } - if let Ok(v) = std::env::var("EC_H265_RDOQ") { - cfg.rdoq = v != "0"; - } - if let Ok(v) = std::env::var("EC_H265_RDOQ_ESTIMATE") { - cfg.rdoq_estimate = v != "0"; - } - if let Ok(v) = std::env::var("EC_H265_TSKIP") { - cfg.transform_skip = match v.as_str() { - "0" => TransformSkip::Off, - "always" => TransformSkip::AlwaysFor4x4, - _ => TransformSkip::Rd, - }; - } - if let Ok(v) = std::env::var("EC_H265_NXN") { - cfg.intra_nxn = v != "0"; - } - if let Ok(v) = std::env::var("EC_H265_CTB") { - cfg.ctb_size = v.parse().expect("EC_H265_CTB must be 32 or 64"); - } - if let Ok(v) = std::env::var("EC_H265_CU64") { - cfg.cu64 = v != "0"; - } - if let Ok(v) = std::env::var("EC_H265_DEBLOCK") { - cfg.deblock = v != "0"; - } - if let Ok(v) = std::env::var("EC_H265_RQT") { - cfg.rqt = v != "0"; - } - if let Ok(k) = std::env::var("EC_H265_RDO_CANDIDATES") { - cfg.rdo_candidates = k.parse().expect("EC_H265_RDO_CANDIDATES must be a number"); - } - let enc = Encoder::new(cfg).expect("encoder"); - let (mut stream, mut sum_recon) = (Vec::new(), 0.0); - for (y, u, v) in &sources { - let coded = enc - .encode_idr_planes(y, w, u, w / 2, v, w / 2) - .expect("encode"); - stream.extend_from_slice(&coded.au); - let recon = coded.recon.as_ref().expect("reconstruction"); - let (ry, _ru, _rv) = planes_of(recon); - sum_recon += psnr(y, &ry); - } - // Measured the same way x265 is: on what a decoder shows, not on the - // encoder's own reconstruction. The two are printed together because a - // gap between them is a bug in one of the halves, not a rate-quality - // result. - let decoded = ffmpeg_decode(&stream, w, h).expect("ffmpeg decodes our stream"); - assert_eq!(decoded.len(), sources.len(), "our encoder dropped pictures"); - let n = sources.len() as f64; - let sum: f64 = sources - .iter() - .zip(&decoded) - .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) - .sum(); - let sum_yuv: f64 = sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr_yuv(s, d)) - .sum(); - let (sum_u, sum_v) = ( - sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr(&s.1, &d.1)) - .sum::(), - sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr(&s.2, &d.2)) - .sum::(), - ); - eprintln!( - " ours qp {qp}: u {:.2} dB v {:.2} dB", - sum_u / n, - sum_v / n - ); - let (decoded_psnr, recon_psnr) = (sum / n, sum_recon / n); - assert!( - (decoded_psnr - recon_psnr).abs() < 0.05, - "qp {qp}: our reconstruction reads {recon_psnr:.2} dB but our own \ - stream decodes to {decoded_psnr:.2} dB" - ); - ((stream.len() * 8) as f64, decoded_psnr, sum_yuv / n) - }; - let x265 = |qp: i32| { - let stream = x265_encode_qp(&sources, w, h, qp).expect("x265 encodes"); - let decoded = ffmpeg_decode(&stream, w, h).expect("ffmpeg decodes x265's own stream"); - assert_eq!( - decoded.len(), - sources.len(), - "x265 returned {} pictures for {} sources", - decoded.len(), - sources.len() - ); - let n = sources.len() as f64; - let sum: f64 = sources - .iter() - .zip(&decoded) - .map(|((y, _, _), (dy, _, _))| psnr(y, dy)) - .sum(); - let sum_yuv: f64 = sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr_yuv(s, d)) - .sum(); - eprintln!( - " x265 qp {qp}: u {:.2} dB v {:.2} dB", - sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr(&s.1, &d.1)) - .sum::() - / n, - sources - .iter() - .zip(&decoded) - .map(|(s, d)| psnr(&s.2, &d.2)) - .sum::() - / n - ); - ((stream.len() * 8) as f64, sum / n, sum_yuv / n) - }; - - // x265 stays anchored at QP 22/26/30/34. Our ladder is shifted by a QP - // delta measured from a single probe encode, not a constant: both sides - // are encoded at QP 26, the bit ratio is converted to a QP shift (≈6 QP - // per factor of 2 in bits), and our four QPs run at 22/26/30/34 plus that - // shift. If the extrapolation share still exceeds 20% after measuring, the - // shift is re-estimated from the geometric-mean bit ratio of the two full - // curves and the ladder is rebuilt; once the rates match and the curves - // still do not meet, our ladder is drawn in towards its own centre until - // its bitrate range fits inside the anchor's — at most 8 alignment rounds - // before the existing panic fires. - const EXTRAP_LIMIT: f64 = 0.20; - let x265_qps = [22, 26, 30, 34]; - let probe_qp = 26; - - // Probe both encoders at QP 26 to measure the bit ratio. - let probe_ours = ours(probe_qp); - let probe_x265 = x265(probe_qp); - // A sample window with nothing in it (a film's black head, a fade) codes - // to a handful of bits and decodes back to the source exactly, so every - // point on both curves sits at the PSNR cap and the BD number is a flat - // +0.000 that looks like a measurement. Refuse it by name. - const FLAT_WINDOW_DB: f64 = 90.0; - assert!( - probe_x265.1 < FLAT_WINDOW_DB && probe_ours.1 < FLAT_WINDOW_DB, - "the sample window is flat — both encoders reach the PSNR cap on it \ - (ours {:.2} dB, x265 {:.2} dB at qp {probe_qp}); this is a black head \ - or a fade, not content: pass EC_H265_CLIP_SKIP to sample past it", - probe_ours.1, - probe_x265.1, - ); - let mut shift = (6.0 * (probe_ours.0 / probe_x265.0).log2()).round() as i32; - eprintln!( - "ladder shift {shift:+} (probe q{probe_qp}: ours {:.1} Mbit vs x265 {:.1} Mbit)", - probe_ours.0 / 1e6, - probe_x265.0 / 1e6, - ); - - let curve = |v: &[(f64, f64, f64)], luma: bool| -> Vec<(f64, f64)> { - v.iter() - .map(|&(b, p, y)| (b, if luma { p } else { y })) - .collect() - }; - - // x265 ladder is fixed; reuse the probe for its QP-26 point. - let theirs: Vec<(f64, f64, f64)> = x265_qps - .iter() - .map(|&q| if q == probe_qp { probe_x265 } else { x265(q) }) - .collect(); - - let gm = |v: &[(f64, f64, f64)]| (v[0].0 * v[1].0 * v[2].0 * v[3].0).powf(0.25); - let qps_str = |qs: &[i32; 4]| { - qs.iter() - .map(|q| q.to_string()) - .collect::>() - .join("/") - }; - - #[allow(unused_assignments)] - let ( - mut bd, - mut bd_yuv, - mut cand_extrap, - mut anc_extrap, - mut cand_extrap_yuv, - mut anc_extrap_yuv, - ) = (0.0_f64, 0.0, 0.0, 0.0, 0.0, 0.0); - let mut mine: Vec<(f64, f64, f64)>; - let mut our_qps: [i32; 4]; - // How wide our QP ladder is against the anchor's, as a fraction of its - // spacing: one encoder can answer a QP step with far more bitrate than the - // other, and a BD number needs both curves over the same range. - let mut spread = 1.0_f64; - - for round in 0..=8u32 { - our_qps = x265_qps.map(|q| { - let centre = f64::from(probe_qp + shift); - let offset = f64::from(q - probe_qp) * spread; - ((centre + offset).round() as i32).clamp(1, 45) - }); - let mut distinct = our_qps; - distinct.sort_unstable(); - let collapsed = distinct.windows(2).any(|w| w[0] == w[1]); - assert!( - !collapsed, - "our QP ladder collapsed to {:?}: the shift has pushed it into the \ - qp floor, so two points share an x and the cubic has no unique fit", - our_qps, - ); - mine = our_qps - .iter() - .map(|&q| if q == probe_qp { probe_ours } else { ours(q) }) - .collect(); - for (i, &qp) in our_qps.iter().enumerate() { - let (ob, op, oy) = mine[i]; - eprintln!("qp {qp}: ours {ob:.0} bits {op:.2} dB ({oy:.2} yuv)"); - } - for (i, &qp) in x265_qps.iter().enumerate() { - let (xb, xp, xy) = theirs[i]; - eprintln!("qp {qp}: x265 {xb:.0} bits {xp:.2} dB ({xy:.2} yuv)"); - } - (bd, cand_extrap, anc_extrap) = bd_psnr_delta(&curve(&mine, true), &curve(&theirs, true)); - (bd_yuv, cand_extrap_yuv, anc_extrap_yuv) = - bd_psnr_delta(&curve(&mine, false), &curve(&theirs, false)); - eprintln!( - "BD-PSNR ours (q{}) vs x265 (q{}): {bd:+.3} dB", - qps_str(&our_qps), - qps_str(&x265_qps), - ); - eprintln!( - "BD-PSNR-YUV ours (q{}) vs x265 (q{}): {bd_yuv:+.3} dB", - qps_str(&our_qps), - qps_str(&x265_qps), - ); - let aligned = cand_extrap <= EXTRAP_LIMIT - && anc_extrap <= EXTRAP_LIMIT - && cand_extrap_yuv <= EXTRAP_LIMIT - && anc_extrap_yuv <= EXTRAP_LIMIT; - if aligned || round == 8 { - break; - } - // Re-estimate the shift from the geometric-mean bit ratio of the two - // full curves, then rebuild the ladder. A single-QP correction is - // ignored: it is within the rounding of the estimate and only makes the - // ladder oscillate between two neighbouring shifts. - let delta = (6.0 * (gm(&mine) / gm(&theirs)).log2()).round() as i32; - if delta.abs() > 1 { - shift += delta; - eprintln!( - "alignment round {}: shift {delta:+} -> {shift:+} \ - (gm ours {:.1} Mbit vs x265 {:.1} Mbit)", - round + 1, - gm(&mine) / 1e6, - gm(&theirs) / 1e6, - ); - continue; - } - // The rates match and the curves still do not overlap, so our ladder - // spans a much wider bitrate range than the anchor's: their union is - // then mostly outside what x265 measured and the cubic through its four - // points extrapolates over most of it. Draw our ladder in. - spread *= 0.5; - eprintln!( - "alignment round {}: ladder spread -> {spread:.2} of the anchor's", - round + 1 - ); - } - - // A BD number over a range where the two QP ladders do not overlap is not a - // measurement — the cubic is extrapolating, not interpolating. Fail loudly - // with the side that is out of range instead of reporting a meaningless gap. - let out_of_range = |c: f64, a: f64| { - let mut parts = Vec::new(); - if c > EXTRAP_LIMIT { - parts.push(format!("ours {:.0}%", c * 100.0)); - } - if a > EXTRAP_LIMIT { - parts.push(format!("x265 {:.0}%", a * 100.0)); - } - parts - }; - let luma_oor = out_of_range(cand_extrap, anc_extrap); - let yuv_oor = out_of_range(cand_extrap_yuv, anc_extrap_yuv); - if !luma_oor.is_empty() { - panic!( - "BD-PSNR luma: the two QP ladders do not overlap — {} of the \ - integration range is extrapolated (limit {:.0}%); widen the QP \ - sweep until the curves meet", - luma_oor.join(", "), - EXTRAP_LIMIT * 100.0 - ); - } - if !yuv_oor.is_empty() { - panic!( - "BD-PSNR-YUV: the two QP ladders do not overlap — {} of the \ - integration range is extrapolated (limit {:.0}%); widen the QP \ - sweep until the curves meet", - yuv_oor.join(", "), - EXTRAP_LIMIT * 100.0 - ); - } - - // The floor is calibrated on the synthetic clip; a clip of the user's is a - // measurement, not a gate, because its content is not pinned. - if std::env::var_os("EC_H265_CLIP").is_none() { - assert!( - bd > BD_PSNR_VS_X265_FLOOR, - "BD-PSNR against x265 fell to {bd:+.3} dB, past the \ - {BD_PSNR_VS_X265_FLOOR:+.3} dB floor" - ); - } -} - -/// Decode `want` pictures from a media file as tightly packed I420 triples. -/// `EC_H265_CLIP_SKIP` passes over that many pictures before sampling (film -/// heads are titles and fades). -fn clip_sources(path: &std::ffi::OsStr, want: usize) -> (usize, usize, Vec) { - let dims = ec_testkit::ffprobe() - .args([ - "-v", - "error", - "-select_streams", - "v:0", - "-show_entries", - "stream=width,height", - "-of", - "csv=p=0", - ]) - .arg(path) - .output() - .expect("ffprobe"); - assert!( - dims.status.success(), - "ffprobe failed: {}", - String::from_utf8_lossy(&dims.stderr) - ); - let csv = String::from_utf8_lossy(&dims.stdout); - // ffprobe prints one comma-separated line per stream, and recent builds - // end it with a trailing separator, so the fields are taken by position - // rather than by splitting the line in two. - let mut fields = csv.lines().next().unwrap_or_default().split(','); - let (w, h) = (|| { - Some(( - fields.next()?.trim().parse::().ok()?, - fields.next()?.trim().parse::().ok()?, - )) - })() - .unwrap_or_else(|| panic!("ffprobe returned dimensions, got {csv:?}")); - // Pictures to pass over before sampling: the head of a film is titles and - // fades, which are not what a codec is measured on. - let skip: usize = std::env::var("EC_H265_CLIP_SKIP") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(0); - // Trim on ffmpeg's side, not ours. Asking for the whole file and slicing - // afterwards buffers the entire decoded clip in memory: a 1080p feature is - // hundreds of gigabytes of raw I420, which the kernel answers with the OOM - // killer. `select` drops the skipped pictures inside ffmpeg and - // `-frames:v` stops the decode once `want` have come out, so what reaches - // this process is exactly `want` frames. - let raw = ec_testkit::ffmpeg() - .args(["-v", "error", "-i"]) - .arg(path) - .args([ - "-vf", - &format!("select=gte(n\\,{skip})"), - "-fps_mode", - "passthrough", - "-frames:v", - &want.to_string(), - "-f", - "rawvideo", - "-pix_fmt", - "yuv420p", - "pipe:1", - ]) - .output() - .expect("ffmpeg raw extract"); - assert!( - raw.status.success(), - "ffmpeg failed: {}", - String::from_utf8_lossy(&raw.stderr) - ); - let frame = w * h * 3 / 2; - assert!( - raw.stdout.len().is_multiple_of(frame) && raw.stdout.len() / frame >= want, - "clip {} yielded {} bytes after skipping {skip}, need {want}x{frame}", - path.to_string_lossy(), - raw.stdout.len() - ); - let sources: Vec = raw - .stdout - .chunks(frame) - .take(want) - .map(|f| { - let (y, rest) = f.split_at(w * h); - let (u, v) = rest.split_at(w / 2 * h / 2); - (y.to_vec(), u.to_vec(), v.to_vec()) - }) - .collect(); - eprintln!( - "{}: {}x{}, {} pictures (skipped {skip})", - path.to_string_lossy(), - w, - h, - sources.len() - ); - (w, h, sources) -} diff --git a/crates/ec-h265/tests/it/main.rs b/crates/ec-h265/tests/it/main.rs index 08bba744..79a6dce7 100644 --- a/crates/ec-h265/tests/it/main.rs +++ b/crates/ec-h265/tests/it/main.rs @@ -5,23 +5,10 @@ #![forbid(unsafe_code)] mod common; -mod conformance; -mod conformance_intra; -mod conformance_rext; -mod conformance_rext422; -mod cu_syntax; -mod dec_meta; -mod dec_shell; mod decode; -mod dolby_vision_p8; mod enc8_bitstream_hash; -mod encode; mod encode_threads; mod fuzz_regressions; mod main10; -mod rate_control; -mod rdoq_cache_hash; -mod real_library; mod refusals; mod rext_generated; -mod scaling_lists; diff --git a/crates/ec-h265/tests/it/rate_control.rs b/crates/ec-h265/tests/it/rate_control.rs deleted file mode 100644 index 33891ff1..00000000 --- a/crates/ec-h265/tests/it/rate_control.rs +++ /dev/null @@ -1,207 +0,0 @@ -//! Bitrate control of the sequence encoder: a clip coded at a target lands within -//! 5% of that target, and the output does not depend on the worker count. -//! -//! The clip is a textured pattern that moves a few samples per picture, so the -//! pictures differ in cost and the model has to follow them. The 5% bound is the -//! same one the 60 s measurement is held to (`scripts/hevc-rc.sh`). - -use ec_core::frame::{PixelFormat, Plane, VideoFrame}; -use ec_h265::encoder::{EncodedPicture, Encoder, EncoderConfig, RateControl}; - -const W: usize = 320; -const H: usize = 240; -const FPS: f64 = 30.0; -const FRAMES: usize = 150; -const KEYINT: usize = 30; - -fn moving_clip(frames: usize) -> Vec { - let (cw, ch) = (W / 2, H / 2); - (0..frames) - .map(|t| { - let mut y = vec![0u8; W * H]; - for r in 0..H { - for c in 0..W { - let (x, yy) = (c + 3 * t, r + t); - let mut v = (x * 7 + yy * 5) as u32; - v ^= (x as u32).wrapping_mul(0x9e37) ^ (yy as u32).wrapping_mul(0x85eb); - y[r * W + c] = (v.wrapping_mul(2_654_435_761) >> 24) as u8; - } - } - let chroma = |scale: usize| -> Vec { - (0..cw * ch) - .map(|i| { - let (c, r) = (i % cw, i / cw); - ((c * scale + r * 3 + t * 2) % 251) as u8 - }) - .collect() - }; - VideoFrame::try_new( - PixelFormat::I420, - W as u32, - H as u32, - vec![ - Plane::new(y, W), - Plane::new(chroma(5), cw), - Plane::new(chroma(9), cw), - ], - ) - .expect("I420 planes at the stated size") - }) - .collect() -} - -/// Encode the clip at `kbps` with `threads` workers; returns the stream bytes. -fn encode_at(frames: &[VideoFrame], kbps: u32, threads: usize) -> Vec { - let mut cfg = EncoderConfig::new(W as u32, H as u32); - cfg.rate_control = RateControl::Bitrate { kbps, fps: FPS }; - cfg.keyint = KEYINT; - cfg.threads = threads; - let enc = Encoder::new(cfg).expect("encoder"); - let coded = enc.encode_sequence(frames).expect("encode"); - coded.iter().flat_map(|p| p.au.iter().copied()).collect() -} - -#[test] -fn bitrate_lands_within_five_percent_of_each_target() { - let frames = moving_clip(FRAMES); - for kbps in [1000u32, 2500, 5000] { - let stream = encode_at(&frames, kbps, 1); - let seconds = FRAMES as f64 / FPS; - let achieved = stream.len() as f64 * 8.0 / seconds / 1000.0; - let error = (achieved - f64::from(kbps)) / f64::from(kbps); - eprintln!( - "target {kbps} kbps: achieved {achieved:.1} kbps ({:+.2}%)", - error * 100.0 - ); - assert!( - error.abs() <= 0.05, - "target {kbps} kbps: achieved {achieved:.1} kbps is {:+.2}% off", - error * 100.0 - ); - } -} - -/// A flat picture at `luma` (chroma at 128): nothing in it costs more than a skipped block -/// at any QP, so it is the case where the rate cannot be spent. -fn flat_clip(frames: usize, luma: u8) -> Vec { - let (cw, ch) = (W / 2, H / 2); - (0..frames) - .map(|_| { - VideoFrame::try_new( - PixelFormat::I420, - W as u32, - H as u32, - vec![ - Plane::new(vec![luma; W * H], W), - Plane::new(vec![128; cw * ch], cw), - Plane::new(vec![128; cw * ch], cw), - ], - ) - .expect("I420 planes at the stated size") - }) - .collect() -} - -/// A flat clip at 2000 kbps cannot spend its budget even at QP 0, so the rate model must -/// walk the quantiser down to the HEVC floor and hold it there, rather than stall high. -/// The floor is the codec's, not a rate floor of this encoder: whatever bits remain are the -/// content's own cost at QP 0. -#[test] -fn flat_near_black_descends_to_the_qp_floor() { - let frames = flat_clip(60, 16); - let pics: Vec = encode_pictures(&frames, 2000); - // The first predicted pictures walk the quantiser down from the IDR's QP (at most four - // steps each); from picture 10 on, every predicted picture must sit at QP 0. - let tail: Vec<(usize, i32)> = pics - .iter() - .enumerate() - .filter(|(i, _)| i % KEYINT != 0 && *i >= 10) - .map(|(i, p)| (i, p.qp)) - .collect(); - assert!(!tail.is_empty()); - let stalled: Vec<&(usize, i32)> = tail.iter().filter(|(_, qp)| *qp != 0).collect(); - assert!( - stalled.is_empty(), - "QP did not reach the floor: {stalled:?}" - ); -} - -/// Encode `frames` at `kbps` and return the coded pictures, so the test can see each QP. -fn encode_pictures(frames: &[VideoFrame], kbps: u32) -> Vec { - let mut cfg = EncoderConfig::new(W as u32, H as u32); - cfg.rate_control = RateControl::Bitrate { kbps, fps: FPS }; - cfg.keyint = KEYINT; - cfg.threads = 1; - Encoder::new(cfg) - .expect("encoder") - .encode_sequence(frames) - .expect("encode") -} - -#[test] -fn bitrate_output_is_identical_at_any_thread_count() { - let frames = moving_clip(FRAMES); - let one = encode_at(&frames, 2500, 1); - for threads in [2usize, 4] { - assert!( - encode_at(&frames, 2500, threads) == one, - "stream differs at {threads} threads" - ); - } -} - -/// Near-black with temporal noise at 720p: luma 16 plus a deterministic PRNG offset of -2..=2 -/// that differs every picture. Cost against QP is a cliff here (a few hundred bytes per -/// picture above QP ~17, tens of kilobytes a few steps below), so the `2^(QP/6)` model alone -/// dives into the cliff after a run of cheap pictures and the stream overshoots. The cliff -/// only shows at this size, which is why this clip is not 320x240. -fn noisy_black_clip(frames: usize, w: usize, h: usize) -> Vec { - let (cw, ch) = (w / 2, h / 2); - let mut state = 0x2545_f491_4f6c_dd1du64; - let mut next = move || { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - (state >> 33) as u32 - }; - (0..frames) - .map(|_| { - let y: Vec = (0..w * h).map(|_| (14 + next() % 5) as u8).collect(); - VideoFrame::try_new( - PixelFormat::I420, - w as u32, - h as u32, - vec![ - Plane::new(y, w), - Plane::new(vec![128; cw * ch], cw), - Plane::new(vec![128; cw * ch], cw), - ], - ) - .expect("I420 planes at the stated size") - }) - .collect() -} - -#[test] -fn noisy_near_black_lands_within_five_percent() { - let (w, h, frames) = (1280usize, 720usize, noisy_black_clip(90, 1280, 720)); - for kbps in [500u32, 2000] { - let mut cfg = EncoderConfig::new(w as u32, h as u32); - cfg.rate_control = RateControl::Bitrate { kbps, fps: FPS }; - cfg.keyint = KEYINT; - cfg.threads = 1; - let pics = Encoder::new(cfg) - .expect("encoder") - .encode_sequence(&frames) - .expect("encode"); - let bytes: usize = pics.iter().map(|p| p.au.len()).sum(); - let achieved = bytes as f64 * 8.0 / (frames.len() as f64 / FPS) / 1000.0; - let error = (achieved - f64::from(kbps)) / f64::from(kbps); - eprintln!("target {kbps}: {achieved:.1} kbps ({:+.2}%)", error * 100.0); - assert!( - error.abs() <= 0.05, - "target {kbps} kbps: achieved {achieved:.1} kbps is {:+.2}% off", - error * 100.0 - ); - } -} diff --git a/crates/ec-h265/tests/it/rdoq_cache_hash.rs b/crates/ec-h265/tests/it/rdoq_cache_hash.rs deleted file mode 100644 index 9d47af33..00000000 --- a/crates/ec-h265/tests/it/rdoq_cache_hash.rs +++ /dev/null @@ -1,70 +0,0 @@ -//! lane-h265rdoq r3: the sub-block frozen-prefix cursor must not change a -//! single output byte. Hashes two natural-content encodes (1920x1080 and -//! 416x240) with FNV-1a; the number itself means nothing, only that it is the -//! same before and after this round's change to `rdoq()` (checked by hand: -//! stash `residual.rs`, rerun, compare). - -use crate::common::{fnv1a, natural_frame}; -use ec_h265::encoder::{Encoder, EncoderConfig, RateControl}; - -fn encode_hash(width: u32, height: u32) -> u64 { - let mut cfg = EncoderConfig::new(width, height); - cfg.rate_control = RateControl::ConstantQp(24); - cfg.threads = 1; - let encoder = Encoder::new(cfg).expect("encoder"); - let mut all = Vec::new(); - for i in 0..3u32 { - let frame = natural_frame(width, height, i * 5); - all.extend(encoder.encode_idr(&frame).expect("encode").au); - } - fnv1a(&all) -} - -#[test] -fn rdoq_cache_hash_1920x1080() { - println!("hash 1920x1080 = {:016x}", encode_hash(1920, 1080)); -} - -#[test] -fn rdoq_cache_hash_416x240() { - println!("hash 416x240 = {:016x}", encode_hash(416, 240)); -} - -/// lane-h265simd: pinned bit-identity gate for the transform's hot path. The -/// value is the same hash the two tests above print, verified by hand -/// (`git stash` the transform.rs change, rerun, compare) to be identical -/// before and after replacing `m32()`'s per-element branch with a -/// compile-time-mirrored flat table in `forward_1d`/`inverse_1d` — this pins -/// that equality so a future change to the hot path is caught if it ever -/// produces a different byte. -/// -/// lane-h265prune: re-pinned after the RQT split trial gained an all-zero-CBF -/// early out (mirrors the CU-quadtree's existing `last_cu_empty` skip one -/// level down at the transform tree): a coding unit whose luma+chroma already -/// quantised to nothing is committed as one leaf transform unit without -/// trying the four-child split first, since splitting a zero-SSD block can -/// only add split_transform_flag and mode-signalling bits. This changes the -/// bitstream on any content where that trial used to flip a leaf to split -/// (BD-gated, not bit-identical — see `EncoderConfig::rqt` and this crate's -/// `bd_psnr_vs_x265`). -/// -/// lane-h265rdoq: re-pinned after RDOQ's trial costing switched from exact -/// per-trial CABAC replay to an estimated per-context fracbits table -/// (`EncoderConfig::rdoq_estimate`, now on by default) — deliberately -/// bit-different, not exact-mode-preserving; see that field's doc comment -/// for the BD/speed numbers that justified flipping the default. -/// -/// lane-h265screen: re-pinned after every committed 4x4 luma block gained a -/// rate-distortion decision on `transform_skip_flag` (`TransformSkip::Rd`, now -/// the default) — deliberately bit-different; see that field's doc comment for -/// the BD numbers per clip. -/// -/// lane-hevcenctools: re-pinned after the sequence parameter set's -/// `sps_temporal_mvp_enabled_flag` went on, which the P pictures' slice headers -/// need. That is one SPS bit; the intra slices are otherwise unchanged, and the -/// 9203-picture conformance check still matches. -#[test] -fn rdoq_cache_hash_is_pinned() { - assert_eq!(encode_hash(416, 240), 0xd501713b57091906); - assert_eq!(encode_hash(1920, 1080), 0x5eb50f5a747ca1c2); -} diff --git a/crates/ec-h265/tests/it/real_library.rs b/crates/ec-h265/tests/it/real_library.rs deleted file mode 100644 index a2ca81bc..00000000 --- a/crates/ec-h265/tests/it/real_library.rs +++ /dev/null @@ -1,367 +0,0 @@ -//! Every file either decodes bit-exactly, is refused by name (a pixel format or -//! a bit depth outside 4:2:0 8/10-bit, or a decoder refusal that says -//! "unsupported"), or fails. A refusal is reported, not counted as a failure. - -use std::io::Read; -use std::path::{Path, PathBuf}; -use std::process::Stdio; - -use ec_h265::dec::Decoder; -use ec_h265::decode::DecodedPicture; -use ec_h265_syntax::{ConformanceWindow, split_annex_b}; - -/// Pictures compared per file. -const FRAMES: usize = 300; - -/// Pixel formats inside the decoder's scope: 4:2:0 at 8 or 10 bits. -const IN_SCOPE_PIX_FMTS: [&str; 2] = ["yuv420p", "yuv420p10le"]; - -fn scratch(tag: &str) -> PathBuf { - let base = std::env::var_os("TMPDIR").map_or_else(std::env::temp_dir, PathBuf::from); - let dir = base.join(format!("ec-h265-{tag}-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("scratch dir"); - dir -} - -/// One manifest row: the columns the sweep reads. -struct Entry { - path: PathBuf, - container: String, - width: String, - height: String, - pix_fmt: String, -} - -fn hevc_entries() -> Vec { - [ - ( - "derived/sintel720-x265-main10.mp4", - "yuv420p10le", - "1280", - "720", - ), - ("open/sintel_trailer-1080p.mp4", "yuv420p", "1920", "1080"), - ] - .into_iter() - .map(|(rel, pix_fmt, width, height)| Entry { - path: ec_testkit::fixture(rel), - container: "mp4".to_string(), - width: width.to_string(), - height: height.to_string(), - pix_fmt: pix_fmt.to_string(), - }) - .collect() -} - -/// The samples of a picture cropped to its conformance window, as the bytes of a -/// planar rawvideo frame: one byte per sample at 8 bits, little-endian u16 above. -fn cropped(pic: &DecodedPicture, win: &ConformanceWindow, bps: usize) -> Vec { - let (l, r, t, b) = ( - win.left as usize, - win.right as usize, - win.top as usize, - win.bottom as usize, - ); - let (w, h) = (pic.width, pic.height); - // Conformance offsets are in chroma units for 4:2:0: luma is twice as large. - let planes = [ - ( - &pic.y, - w, - h, - 2 * l, - w.saturating_sub(2 * r), - 2 * t, - h.saturating_sub(2 * b), - ), - ( - &pic.cb, - w / 2, - h / 2, - l, - (w / 2).saturating_sub(r), - t, - (h / 2).saturating_sub(b), - ), - ( - &pic.cr, - w / 2, - h / 2, - l, - (w / 2).saturating_sub(r), - t, - (h / 2).saturating_sub(b), - ), - ]; - let mut out = Vec::new(); - for (samples, pw, ph, x0, x1, y0, y1) in planes { - for y in y0..y1.min(ph) { - for x in x0..x1.min(pw) { - let s = samples.get(y * pw + x).copied().unwrap_or(0); - if bps == 1 { - out.push(s as u8); - } else { - out.extend_from_slice(&s.to_le_bytes()); - } - } - } - } - out -} - -/// Where byte `offset` of a cropped frame lies: plane name, x and y in that plane. -fn locate(offset: usize, bps: usize, lw: usize, lh: usize) -> (&'static str, usize, usize) { - let s = offset / bps; - let (cw, ch) = (lw / 2, lh / 2); - if s < lw * lh { - ("Y", s % lw, s / lw) - } else if s < lw * lh + cw * ch { - let c = s - lw * lh; - ("Cb", c % cw, c / cw) - } else { - let c = s - lw * lh - cw * ch; - ("Cr", c % cw, c / cw) - } -} - -/// Running comparison of decoded frames against the oracle's rawvideo stream. -#[derive(Default)] -struct Compare { - compared: usize, - /// First mismatch: "frame N plane P x= y= (poc)". - first_diff: Option, - differing_frames: usize, - oracle_short: bool, -} - -/// The oracle's stream and the decoder's frames, compared frame by frame. -struct Sweep { - out: std::process::ChildStdout, - child: std::process::Child, - open: bool, - cmp: Compare, - index: usize, - frame_len: usize, - bps: usize, -} - -impl Sweep { - fn take(&mut self, pic: &DecodedPicture, win: &ConformanceWindow, poc: i32) { - let want = cropped(pic, win, self.bps); - let index = self.index; - self.index += 1; - if !self.open { - return; - } - let mut oracle = vec![0u8; want.len()]; - if self.out.read_exact(&mut oracle).is_err() { - self.open = false; - self.cmp.oracle_short = true; - return; - } - self.frame_len = want.len(); - self.cmp.compared += 1; - if want != oracle { - self.cmp.differing_frames += 1; - if self.cmp.first_diff.is_none() { - let lw = pic.width - 2 * (win.left as usize + win.right as usize); - let lh = pic.height - 2 * (win.top as usize + win.bottom as usize); - let at = want - .iter() - .zip(&oracle) - .position(|(a, b)| a != b) - .unwrap_or(0); - let (plane, x, y) = locate(at, self.bps, lw, lh); - self.cmp.first_diff = Some(format!( - "frame {index} plane {plane} x={x} y={y} (poc {poc})" - )); - } - } - } - - /// End of the decoder's output: any frame still in the oracle is missing here. - fn finish(mut self) -> Compare { - if self.open { - let mut probe = vec![0u8; self.frame_len.max(1)]; - if self.frame_len > 0 && self.out.read_exact(&mut probe).is_ok() { - self.cmp.first_diff.get_or_insert(format!( - "decoder produced {} frames, ffmpeg produced more", - self.index - )); - self.cmp.oracle_short = false; - self.cmp.differing_frames += 1; - } - } - let _ = self.child.kill(); - let _ = self.child.wait(); - self.cmp - } -} - -fn short_name(path: &Path) -> String { - path.file_name() - .map(|n| n.to_string_lossy().chars().take(38).collect()) - .unwrap_or_default() -} - -/// Decodes one file and compares it with ffmpeg. `Err` is a refusal or an error, -/// with the text the table prints. -fn sweep_file(entry: &Entry, es: &Path, bit_depth: u32) -> Result { - let bps = if bit_depth > 8 { 2 } else { 1 }; - let mut child = ec_testkit::ffmpeg() - .args(["-v", "error", "-c:v", "hevc", "-i"]) - .arg(es) - .args([ - "-frames:v", - &FRAMES.to_string(), - "-f", - "rawvideo", - "-pix_fmt", - ]) - .arg(&entry.pix_fmt) - .arg("-") - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .spawn() - .map_err(|e| e.to_string())?; - let out = child.stdout.take().expect("piped stdout"); - let mut sweep = Sweep { - out, - child, - open: true, - cmp: Compare::default(), - index: 0, - frame_len: 0, - bps, - }; - - let data = std::fs::read(es).map_err(|e| e.to_string())?; - let mut dec = Decoder::new(); - let drain = |dec: &mut Decoder, sweep: &mut Sweep| { - while let Some(frame) = dec.next_frame() { - sweep.take(&frame.picture, &frame.window, frame.poc); - } - }; - let result = (|| -> Result<(), String> { - for nal in split_annex_b(&data) { - let mut bytes = nal.header.to_bytes().to_vec(); - bytes.extend_from_slice(nal.payload); - if let Err(e) = dec.push_nal(&bytes) { - return Err(format!("{e}")); - } - drain(&mut dec, &mut sweep); - } - dec.flush().map_err(|e| format!("{e}"))?; - drain(&mut dec, &mut sweep); - Ok(()) - })(); - let cmp = sweep.finish(); - result?; - Ok(cmp) -} - -/// Extracts the first `FRAMES` pictures of the video as Annex B. -fn extract(src: &Path, dst: &Path) -> bool { - ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-i"]) - .arg(src) - .args([ - "-map", - "0:v:0", - "-c", - "copy", - "-bsf:v", - "hevc_mp4toannexb", - "-frames:v", - &FRAMES.to_string(), - "-f", - "hevc", - ]) - .arg(dst) - .status() - .is_ok_and(|s| s.success()) -} - -#[test] -#[ignore = "slow: decodes and compares two open clips with ffmpeg; run with --ignored."] -fn real_library_hevc_streams_match_ffmpeg() { - let entries = hevc_entries(); - let dir = scratch("real-library-hevc"); - let mut table = String::new(); - let mut decoded = 0usize; - let mut refused = 0usize; - let mut failures = Vec::new(); - - for entry in &entries { - let name = short_name(&entry.path); - let res = format!("{}x{}", entry.width, entry.height); - let bit_depth: u32 = if entry.pix_fmt == "yuv420p10le" { - 10 - } else { - 8 - }; - if !IN_SCOPE_PIX_FMTS.contains(&entry.pix_fmt.as_str()) { - refused += 1; - table.push_str(&format!( - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} refused: pixel format {} is outside 4:2:0 8/10-bit\n", - entry.container, "-", entry.pix_fmt - )); - continue; - } - let es = dir.join("stream.265"); - if !extract(&entry.path, &es) { - failures.push(format!("{name}: extraction failed")); - table.push_str(&format!( - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} ERROR extraction\n", - entry.container, "-" - )); - continue; - } - match sweep_file(entry, &es, bit_depth) { - Ok(c) if c.differing_frames > 0 => { - failures.push(format!("{name}: {} frames differ", c.differing_frames)); - table.push_str(&format!( - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} MISMATCH {} of {} frames; first: {}\n", - entry.container, c.compared, c.differing_frames, c.compared, - c.first_diff.clone().unwrap_or_default() - )); - } - Ok(c) => { - decoded += 1; - table.push_str(&format!( - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} bit-exact{}\n", - entry.container, - c.compared, - if c.oracle_short { - " (ffmpeg stopped early)" - } else { - "" - } - )); - } - Err(e) if e.contains("unsupported") => { - refused += 1; - table.push_str(&format!( - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} refused: {e}\n", - entry.container, "-" - )); - } - Err(e) => { - failures.push(format!("{name}: {e}")); - table.push_str(&format!( - "{name:<38} {:<12} {res:>10} {bit_depth:>2}-bit {:>4} ERROR {e}\n", - entry.container, "-" - )); - } - } - let _ = std::fs::remove_file(&es); - } - let _ = std::fs::remove_dir_all(&dir); - eprintln!("{table}"); - eprintln!( - "real library hevc: {decoded} bit-exact, {refused} refused by name, {} failed", - failures.len() - ); - assert!(failures.is_empty(), "{failures:#?}"); - assert!(decoded >= 1, "no real HEVC file was swept end to end"); -} diff --git a/crates/ec-h265/tests/it/scaling_lists.rs b/crates/ec-h265/tests/it/scaling_lists.rs deleted file mode 100644 index 426bad59..00000000 --- a/crates/ec-h265/tests/it/scaling_lists.rs +++ /dev/null @@ -1,111 +0,0 @@ -//! Scaling-list streams, checked against ffmpeg. -//! -//! The SLIST conformance streams code their own lists in the SPS and PPS. Most of -//! their pictures are B slices, which this decoder does not pixel-decode yet, so the -//! check is on the first picture in output order: an IDR, intra only, decoded with -//! the stream's lists. It must match ffmpeg sample for sample after cropping. - -use ec_h265::Decoder; -use ec_h265::dec::Frame; -use std::path::{Path, PathBuf}; - -/// The four scaling-list streams the picture-management sweep covers; `str` is -/// the SLIST_D stream. -const STREAMS: [&str; 4] = [ - "SLIST_A_Sony_5/SLIST_A_Sony_5/SLIST_A_Sony_5.bin", - "SLIST_B_Sony_9/SLIST_B_Sony_9/SLIST_B_Sony_9.bin", - "SLIST_C_Sony_4/SLIST_C_Sony_4/SLIST_C_Sony_4.bin", - "SLIST_D_Sony_9/SLIST_D_Sony_9/str.bin", -]; - -fn vectors_dir() -> PathBuf { - ec_testkit::fixture("vectors/hevc-jctvc") -} - -/// The first output picture as 4:2:0 bytes cropped to the conformance window. -fn cropped_yuv(frame: &Frame) -> Vec { - let pic = &frame.picture; - let win = &frame.window; - // Conformance window offsets are in chroma samples for 4:2:0. - let (lx0, lx1) = (2 * win.left as usize, pic.width - 2 * win.right as usize); - let (ly0, ly1) = (2 * win.top as usize, pic.height - 2 * win.bottom as usize); - let (cx0, cx1) = (win.left as usize, pic.width / 2 - win.right as usize); - let (cy0, cy1) = (win.top as usize, pic.height / 2 - win.bottom as usize); - let mut out = Vec::new(); - for row in ly0..ly1 { - out.extend( - pic.y[row * pic.width + lx0..row * pic.width + lx1] - .iter() - .map(|&v| v as u8), - ); - } - let cw = pic.width / 2; - for plane in [&pic.cb, &pic.cr] { - for row in cy0..cy1 { - out.extend( - plane[row * cw + cx0..row * cw + cx1] - .iter() - .map(|&v| v as u8), - ); - } - } - out -} - -/// The first frame of `path` as ffmpeg decodes it, in yuv420p. -fn ffmpeg_first_frame(path: &Path, tag: &str) -> Result, String> { - let out = std::env::temp_dir().join(format!("ec-h265-scaling-{tag}.yuv")); - let status = ec_testkit::ffmpeg() - .args(["-v", "error", "-y", "-i"]) - .arg(path) - .args(["-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "yuv420p"]) - .arg(&out) - .output() - .map_err(|e| e.to_string())?; - if !status.status.success() { - return Err(String::from_utf8_lossy(&status.stderr).to_string()); - } - std::fs::read(&out).map_err(|e| e.to_string()) -} - -// Ignored until the intra path decodes the syntax these streams use: the decode -// desyncs at the last CTB of the IDR, and the intra CTU loop has no SAO or -// cu_qp_delta parsing. Run with `--ignored` to see the failure. -#[ignore = "intra path lacks the syntax these streams use (desync at the IDR's last CTB)"] -#[test] -fn first_picture_of_each_scaling_list_stream_matches_ffmpeg() { - let dir = vectors_dir(); - let mut checked = 0usize; - for rel in STREAMS { - let path = dir.join(rel); - let data = std::fs::read(&path).unwrap_or_else(|e| panic!("{rel}: {e}")); - let mut decoder = Decoder::new(); - decoder - .decode_annex_b(&data) - .unwrap_or_else(|e| panic!("{rel}: decode failed: {e}")); - decoder - .flush() - .unwrap_or_else(|e| panic!("{rel}: flush failed: {e}")); - let frame = decoder - .next_frame() - .unwrap_or_else(|| panic!("{rel}: no picture out")); - let ours = cropped_yuv(&frame); - let tag = rel.replace('/', "_"); - let theirs = - ffmpeg_first_frame(&path, &tag).unwrap_or_else(|e| panic!("{rel}: ffmpeg failed: {e}")); - assert_eq!( - ours.len(), - theirs.len(), - "{rel}: picture is {} bytes, ffmpeg's is {}", - ours.len(), - theirs.len() - ); - let differing = ours.iter().zip(&theirs).filter(|(a, b)| a != b).count(); - assert_eq!( - differing, 0, - "{rel}: {differing} samples differ from ffmpeg in the first picture" - ); - checked += 1; - } - eprintln!("scaling-list check: {checked} first pictures bit-exact against ffmpeg"); -}