diff --git a/Cargo.lock b/Cargo.lock index 252b0a60..187e2618 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1333,13 +1333,6 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" -[[package]] -name = "oracle" -version = "0.1.0" -dependencies = [ - "ec-testkit", -] - [[package]] name = "paste" version = "1.0.15" diff --git a/Cargo.toml b/Cargo.toml index 53c642ef..4c583efb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "3" -members = ["crates/*", "shims/cros-libva", "shims/vk-video-ffi", "tools/ec-bench", "tools/golden", "tools/oracle"] +members = ["crates/*", "shims/cros-libva", "shims/vk-video-ffi", "tools/ec-bench", "tools/golden"] exclude = ["crates/*/fuzz"] [workspace.package] diff --git a/tools/gen_dts_tables.py b/crates/ec-dts/gen_dts_tables.py similarity index 98% rename from tools/gen_dts_tables.py rename to crates/ec-dts/gen_dts_tables.py index 02053af3..bfb60fd3 100644 --- a/tools/gen_dts_tables.py +++ b/crates/ec-dts/gen_dts_tables.py @@ -7,7 +7,7 @@ https://www.etsi.org/deliver/etsi_ts/102100_102199/102114/01.06.01_60/ts_102114v Usage: pdftotext -layout ts_102114v010601p.pdf ts102114.txt - python3 -I tools/gen_dts_tables.py ts102114.txt \ + python3 -I crates/ec-dts/gen_dts_tables.py ts102114.txt \ crates/ec-dts/src/tables_data.rs crates/ec-dts/tests/spec_ts102114_tables.txt The spec text (decimal commas, "1 926" style thousands separators) is parsed @@ -254,7 +254,7 @@ def main(): # ---- write the raw spec numbers with open(out_spec, 'w') as f: f.write('# Numbers exactly as printed in ETSI TS 102 114 V1.6.1 (2019-08), Annex D / clause 5.\n') - f.write('# Written by tools/gen_dts_tables.py; decimal commas written as points.\n') + f.write('# Written by crates/ec-dts/gen_dts_tables.py; decimal commas written as points.\n') f.write('# table NAME | clause | values... (invalid entries kept as the word "invalid")\n') f.write('# huff TABLE | clause | level:length:code ... (code = value of the code word)\n') for name, cl, vals in raw: @@ -281,7 +281,7 @@ def main(): R = {n: v for n, _, v in raw} out.append('//! Constant tables for DTS Coherent Acoustics (ETSI TS 102 114).') out.append('//!') - out.append('//! GENERATED by tools/gen_dts_tables.py from the numeric tables of') + out.append('//! GENERATED by crates/ec-dts/gen_dts_tables.py from the numeric tables of') out.append('//! ETSI TS 102 114 V1.6.1 (2019-08); the clause of each table is named on') out.append('//! it. The raw printed numbers are committed in') out.append('//! tests/spec_ts102114_tables.txt and tests/spec_tables.rs checks every') diff --git a/crates/ec-dts/src/lib.rs b/crates/ec-dts/src/lib.rs index 043e0635..c7a2e338 100644 --- a/crates/ec-dts/src/lib.rs +++ b/crates/ec-dts/src/lib.rs @@ -29,7 +29,7 @@ //! [`Error::Unsupported`] naming what and why. No input panics. //! //! The constant tables in [`tables_data`] are generated by -//! `tools/gen_dts_tables.py` from the numeric tables printed in ETSI TS 102 114 +//! `crates/ec-dts/gen_dts_tables.py` from the numeric tables printed in ETSI TS 102 114 //! V1.6.1 and checked against them by `tests/spec_tables.rs`; the few tables //! the standard does not print usably are in `tables_residual.rs`. diff --git a/crates/ec-dts/src/tables_data.rs b/crates/ec-dts/src/tables_data.rs index be713780..75e7acf8 100644 --- a/crates/ec-dts/src/tables_data.rs +++ b/crates/ec-dts/src/tables_data.rs @@ -1,6 +1,6 @@ //! Constant tables for DTS Coherent Acoustics (ETSI TS 102 114). //! -//! GENERATED by tools/gen_dts_tables.py from the numeric tables of +//! GENERATED by crates/ec-dts/gen_dts_tables.py from the numeric tables of //! ETSI TS 102 114 V1.6.1 (2019-08); the clause of each table is named on //! it. The raw printed numbers are committed in //! tests/spec_ts102114_tables.txt and tests/spec_tables.rs checks every diff --git a/crates/ec-dts/tests/spec_tables.rs b/crates/ec-dts/tests/spec_tables.rs index c2950f50..3f650cde 100644 --- a/crates/ec-dts/tests/spec_tables.rs +++ b/crates/ec-dts/tests/spec_tables.rs @@ -1,6 +1,6 @@ //! The constant tables in `tables_data.rs` against the numbers printed in //! ETSI TS 102 114 V1.6.1 (2019-08), committed in `spec_ts102114_tables.txt` -//! (written by `tools/gen_dts_tables.py`, with the clause of every table). +//! (written by `crates/ec-dts/gen_dts_tables.py`, with the clause of every table). //! //! The conversions from printed number to Rust value are repeated here //! independently of the generator. diff --git a/crates/ec-dts/tests/spec_ts102114_tables.txt b/crates/ec-dts/tests/spec_ts102114_tables.txt index 75523480..d0d4dd4b 100644 --- a/crates/ec-dts/tests/spec_ts102114_tables.txt +++ b/crates/ec-dts/tests/spec_ts102114_tables.txt @@ -1,5 +1,5 @@ # Numbers exactly as printed in ETSI TS 102 114 V1.6.1 (2019-08), Annex D / clause 5. -# Written by tools/gen_dts_tables.py; decimal commas written as points. +# Written by crates/ec-dts/gen_dts_tables.py; decimal commas written as points. # table NAME | clause | values... (invalid entries kept as the word "invalid") # huff TABLE | clause | level:length:code ... (code = value of the code word) table QUANT_LEVELS | Table 5-26 | 0 3 5 7 9 13 17 25 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 diff --git a/tools/gen_h263_tables.py b/crates/ec-mpeg4/gen_h263_tables.py similarity index 99% rename from tools/gen_h263_tables.py rename to crates/ec-mpeg4/gen_h263_tables.py index 02b54efd..0ead1e56 100644 --- a/tools/gen_h263_tables.py +++ b/crates/ec-mpeg4/gen_h263_tables.py @@ -3,7 +3,7 @@ Usage: pdftotext -layout T-REC-H.263-200501-I!!PDF-E.pdf h263.txt - python3 -I tools/gen_h263_tables.py h263.txt crates/ec-mpeg4/src/h263data.rs + python3 -I crates/ec-mpeg4/gen_h263_tables.py h263.txt crates/ec-mpeg4/src/h263data.rs rustfmt --edition 2021 crates/ec-mpeg4/src/h263data.rs The PDF is freely downloadable from https://www.itu.int/rec/T-REC-H.263 and is the @@ -277,7 +277,7 @@ def arr1(name, ty, a, doc): w(f"pub const {name}: [{ty}; {len(a)}] = [" + ", ".join(str(x) for x in a) + "];\n") -w("""// Generated by tools/gen_h263_tables.py from the text of ITU-T Rec. H.263 (01/2005) +w("""// Generated by crates/ec-mpeg4/gen_h263_tables.py from the text of ITU-T Rec. H.263 (01/2005) // (https://www.itu.int/rec/T-REC-H.263). Do not edit by hand. // // Every table in this file is transcribed from the Recommendation; the clause or table diff --git a/crates/ec-mpeg4/src/h263data.rs b/crates/ec-mpeg4/src/h263data.rs index 5a4317e7..8d693d3f 100644 --- a/crates/ec-mpeg4/src/h263data.rs +++ b/crates/ec-mpeg4/src/h263data.rs @@ -1,4 +1,4 @@ -// Generated by tools/gen_h263_tables.py from the text of ITU-T Rec. H.263 (01/2005) +// Generated by crates/ec-mpeg4/gen_h263_tables.py from the text of ITU-T Rec. H.263 (01/2005) // (https://www.itu.int/rec/T-REC-H.263). Do not edit by hand. // // Every table in this file is transcribed from the Recommendation; the clause or table diff --git a/crates/ec-riff/tests/it/wav.rs b/crates/ec-riff/tests/it/wav.rs index 7687f265..340aa40f 100644 --- a/crates/ec-riff/tests/it/wav.rs +++ b/crates/ec-riff/tests/it/wav.rs @@ -1,9 +1,4 @@ //! Round-trip, header and tolerance checks, plus the fixtures on disk. -//! -//! The oracle artifacts this writes into `CARGO_TARGET_TMPDIR/oracle` are the -//! ffmpeg half of the story: after `cargo test -p ec-riff`, each `.wav` -//! is compared against its `.raw` (the samples that went in, as f32le) -//! with `oracle audio-compare .raw .wav`. use std::io::Cursor; diff --git a/tools/ec-bench/Cargo.toml b/tools/ec-bench/Cargo.toml index af4f2082..7c81ed4c 100644 --- a/tools/ec-bench/Cargo.toml +++ b/tools/ec-bench/Cargo.toml @@ -19,7 +19,6 @@ ec-h264 = { workspace = true } ec-h265 = { workspace = true } ec-av1 = { workspace = true } ec-hw = { workspace = true } -ec-va = { workspace = true } ec-probe = { workspace = true } ec-h264-syntax = { workspace = true } ec-image = { workspace = true } @@ -33,3 +32,6 @@ ec-alac = { workspace = true } ec-ac3 = { workspace = true } ec-truehd = { workspace = true } ec-testkit.workspace = true + +[target.'cfg(target_os = "linux")'.dependencies] +ec-va = { workspace = true } diff --git a/tools/ec-bench/src/main.rs b/tools/ec-bench/src/main.rs index 64f6643a..7f2dd128 100644 --- a/tools/ec-bench/src/main.rs +++ b/tools/ec-bench/src/main.rs @@ -37,14 +37,35 @@ struct Row { rtf: Option, } +impl Row { + fn timed( + component: &'static str, + direction: &'static str, + content: String, + media_s: f64, + wall: f64, + ) -> Row { + Row { + component, + direction, + content, + media: format!("{media_s:.1}s"), + wall_ms: wall * 1000.0, + rtf: (wall > 0.0).then_some(media_s / wall), + } + } +} + fn main() -> ec_core::Result<()> { let mut rows = Vec::new(); bench_h264(&mut rows)?; bench_h265_encode(&mut rows); bench_av1_encode(&mut rows); - bench_hw_av1_encode(&mut rows); - bench_hw_av1_encode_10bit(&mut rows); + #[cfg(target_os = "linux")] + bench_hw_av1_encode(&mut rows, false); + #[cfg(target_os = "linux")] + bench_hw_av1_encode(&mut rows, true); bench_audio_decode(&mut rows)?; bench_audio_encode(&mut rows); bench_truehd(&mut rows); @@ -166,25 +187,20 @@ fn bench_h264(rows: &mut Vec) -> ec_core::Result<()> { .and_then(|s| parse_ratio(&s)) .unwrap_or(25.0); let media_s = frames as f64 / fps; - rows.push(Row { - component: "ec-h264", - direction: "decode", - content: format!("{w}x{h} film, {frames} frames"), - media: format!("{media_s:.1}s"), - wall_ms: wall * 1000.0, - rtf: (wall > 0.0).then_some(media_s / wall), - }); + rows.push(Row::timed("ec-h264", "decode", format!("{w}x{h} film, {frames} frames"), media_s, wall)); } else { rows.push(missing("ec-h264", "decode")); } // encode: 30 raw yuv420p frames scaled to 640x360 from the same clip. - let (planes, ew, eh, n) = extract_yuv420p(&src, 640, 360, 30); + let (ew, eh) = (640, 360); + let planes = extract_raw(&src, ew, eh, 30, "yuv420p"); + let frame_len = yuv420_frame_len(ew, eh, 1); + let n = (planes.len() / frame_len) as u32; if n > 0 { let mut cfg = H264Config::new(ew, eh); cfg.threads = 1; // one worker: single-core cost, not a parallelism claim let mut enc = H264Encoder::new(cfg).expect("h264 encoder"); - let frame_len = (ew * eh + 2 * (ew.div_ceil(2) * eh.div_ceil(2))) as usize; let start = Instant::now(); for frame in planes.chunks_exact(frame_len) { let (y, rest) = frame.split_at((ew * eh) as usize); @@ -194,23 +210,20 @@ fn bench_h264(rows: &mut Vec) -> ec_core::Result<()> { } let wall = start.elapsed().as_secs_f64(); let media_s = n as f64 / 30.0; - rows.push(Row { - component: "ec-h264", - direction: "encode", - content: format!("{ew}x{eh}, {n} frames, 1 thread"), - media: format!("{media_s:.1}s"), - wall_ms: wall * 1000.0, - rtf: (wall > 0.0).then_some(media_s / wall), - }); + rows.push(Row::timed("ec-h264", "encode", format!("{ew}x{eh}, {n} frames, 1 thread"), media_s, wall)); } else { rows.push(missing("ec-h264", "encode")); } Ok(()) } -/// `n` progressive frames of raw I420 at `w x h`, scaled and trimmed inside -/// ffmpeg. -fn extract_yuv420p(src: &Path, w: u32, h: u32, n: u32) -> (Vec, u32, u32, u32) { +fn yuv420_frame_len(w: u32, h: u32, bytes_per_sample: usize) -> usize { + (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize * bytes_per_sample +} + +/// Up to `n` progressive frames at `w x h` in `pix_fmt`, scaled and trimmed +/// inside ffmpeg from `SEEK_SECONDS` on. Empty when ffmpeg fails. +fn extract_raw(src: &Path, w: u32, h: u32, n: u32, pix_fmt: &str) -> Vec { let out = ec_testkit::ffmpeg() .args(["-v", "error", "-ss", SEEK_SECONDS, "-i"]) .arg(src) @@ -220,19 +233,14 @@ fn extract_yuv420p(src: &Path, w: u32, h: u32, n: u32) -> (Vec, u32, u32, u3 "-frames:v", &n.to_string(), "-pix_fmt", - "yuv420p", + pix_fmt, "-f", "rawvideo", "-", ]) .output() - .expect("ffmpeg extract yuv420p"); - if !out.status.success() || out.stdout.is_empty() { - return (Vec::new(), w, h, 0); - } - let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize; - let frames = (out.stdout.len() / frame_len) as u32; - (out.stdout, w, h, frames) + .expect("ffmpeg extract raw"); + if out.status.success() { out.stdout } else { Vec::new() } } fn parse_ratio(s: &str) -> Option { @@ -251,16 +259,17 @@ fn bench_h265_encode(rows: &mut Vec) { rows.push(missing("ec-h265", "encode")); return; }; - let (planes, w, h, n) = extract_yuv420p(&src, 640, 360, 10); + let (w, h) = (640, 360); + let planes = extract_raw(&src, w, h, 10, "yuv420p"); + let frame_len = yuv420_frame_len(w, h, 1); + let n = (planes.len() / frame_len) as u32; if n == 0 { rows.push(missing("ec-h265", "encode")); rows.push(missing("ec-h265", "decode")); return; } let enc = H265Encoder::new(H265Config::new(w, h)).expect("h265 encoder"); - let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize; let cw = w.div_ceil(2); - let ch = h.div_ceil(2); let mut aus = Vec::new(); let start = Instant::now(); for frame in planes.chunks_exact(frame_len) { @@ -277,196 +286,115 @@ fn bench_h265_encode(rows: &mut Vec) { ], ) .expect("i420 frame"); - let _ = ch; // silence unused if plane_geometry ignores it aus.push(enc.encode_idr(&vf).expect("h265 encode").au); } let wall = start.elapsed().as_secs_f64(); let media_s = n as f64 / 30.0; - rows.push(Row { - component: "ec-h265", - direction: "encode", - content: format!("{w}x{h}, {n} frames, IDR-only"), - media: format!("{media_s:.1}s"), - wall_ms: wall * 1000.0, - rtf: (wall > 0.0).then_some(media_s / wall), - }); + rows.push(Row::timed("ec-h265", "encode", format!("{w}x{h}, {n} frames, IDR-only"), media_s, wall)); let start = Instant::now(); for au in &aus { ec_h265::decode::decode_idr_au(au).expect("h265 decode"); } let wall = start.elapsed().as_secs_f64(); - rows.push(Row { - component: "ec-h265", - direction: "decode", - content: format!("{w}x{h}, {n} frames, own IDR stream"), - media: format!("{media_s:.1}s"), - wall_ms: wall * 1000.0, - rtf: (wall > 0.0).then_some(media_s / wall), - }); + rows.push(Row::timed("ec-h265", "decode", format!("{w}x{h}, {n} frames, own IDR stream"), media_s, wall)); } // --------------------------------------------------------------------------- -// hardware av1: the GPU encoder, at the size his library is in. +// hardware av1: the GPU encoder (`ec-hw`, VA-API), at 8 or 10 bits. // --------------------------------------------------------------------------- -/// AV1 encode on the GPU (`ec-hw`, VA-API). Skips as a row rather than a -/// failure when there is no VA device or the driver has no AV1 encode -/// entrypoint -- a machine without one is not a slow machine. -fn bench_hw_av1_encode(rows: &mut Vec) { - let Some(src) = real_video("h264").or_else(|| real_video("hevc")) else { - rows.push(missing("ec-hw av1", "encode")); - return; +/// AV1 encode on the GPU. Skips as a row rather than a failure when there is +/// no VA device or the driver has no AV1 encode entrypoint -- a machine +/// without one is not a slow machine. +#[cfg(target_os = "linux")] +fn bench_hw_av1_encode(rows: &mut Vec, ten_bit: bool) { + let (component, pix_fmt, bytes) = if ten_bit { + ("ec-hw av1 10-bit", "yuv420p10le", 2) + } else { + ("ec-hw av1", "yuv420p", 1) }; - let display = match ec_va::open() { - Ok(display) => display, - Err(e) => { - rows.push(missing_direction("ec-hw av1", "encode", &format!("no VA display ({e})"))); - return; - } + let src = if ten_bit { + real_video("hevc").or_else(|| real_video("h264")) + } else { + real_video("h264").or_else(|| real_video("hevc")) }; - let (planes, w, h, n) = extract_yuv420p(&src, 1920, 1080, 30); - if n == 0 { - rows.push(missing("ec-hw av1", "encode")); - return; - } - let mut cfg = ec_hw::EncoderConfig::new(ec_hw::EncCodec::Av1, w, h); - cfg.rate_control = ec_hw::RateControlMode::ConstantQp { qp: 120 }; - let mut enc = match ec_hw::Encoder::new(&display, cfg) { - Ok(enc) => enc, - Err(e) => { - rows.push(missing_direction("ec-hw av1", "encode", &format!("driver refused ({e})"))); - return; - } - }; - let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); - let frame_len = (w * h + 2 * cw * ch) as usize; - let start = Instant::now(); - let mut coded = 0usize; - for (i, frame) in planes.chunks_exact(frame_len).enumerate() { - let (y, rest) = frame.split_at((w * h) as usize); - let (u, v) = rest.split_at(rest.len() / 2); - let picture = ec_hw::I420 { - y: y.to_vec(), - u: u.to_vec(), - v: v.to_vec(), - width: w, - height: h, - }; - let meta = ec_hw::FrameMetadata { - timestamp: i as i64, - force_keyframe: false, - }; - match enc.encode(&picture, meta) { - Ok(out) => coded += out.data.len(), - Err(e) => { - rows.push(missing_direction("ec-hw av1", "encode", &format!("encode failed ({e})"))); - return; - } - } - } - let wall = start.elapsed().as_secs_f64(); - let media_s = n as f64 / 30.0; - rows.push(Row { - component: "ec-hw av1", - direction: "encode", - content: format!("{w}x{h}, {n} frames, CQP 120, {} kB", coded / 1000), - media: format!("{media_s:.1}s"), - wall_ms: wall * 1000.0, - rtf: (wall > 0.0).then_some(media_s / wall), - }); -} - -/// The same row at 10 bits, which is the depth his own AV1 library is stored -/// at (`yuv420p10le`, both films). Skips as a row when there is no VA device, -/// no AV1 encode entrypoint, or no source to read. -fn bench_hw_av1_encode_10bit(rows: &mut Vec) { - let Some(src) = real_video("av1").or_else(|| real_video("hevc")).or_else(|| real_video("h264")) - else { - rows.push(missing("ec-hw av1 10-bit", "encode")); + let Some(src) = src else { + rows.push(missing(component, "encode")); return; }; let display = match ec_va::open() { Ok(display) => display, Err(e) => { - rows.push(missing_direction("ec-hw av1 10-bit", "encode", &format!("no VA display ({e})"))); + rows.push(missing_direction(component, "encode", &format!("no VA display ({e})"))); return; } }; - let (w, h) = (1920u32, 1080u32); - let raw = extract_yuv420p10(&src, w, h, 30); - let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); - let frame_len = ((w * h + 2 * cw * ch) * 2) as usize; + let (w, h) = (1920, 1080); + let raw = extract_raw(&src, w, h, 30, pix_fmt); + let frame_len = yuv420_frame_len(w, h, bytes); let n = (raw.len() / frame_len) as u32; if n == 0 { - rows.push(missing("ec-hw av1 10-bit", "encode")); + rows.push(missing(component, "encode")); return; } - let mut cfg = ec_hw::EncoderConfig::new(ec_hw::EncCodec::Av1, w, h).ten_bit(); + let mut cfg = ec_hw::EncoderConfig::new(ec_hw::EncCodec::Av1, w, h); + if ten_bit { + cfg = cfg.ten_bit(); + } cfg.rate_control = ec_hw::RateControlMode::ConstantQp { qp: 120 }; let mut enc = match ec_hw::Encoder::new(&display, cfg) { Ok(enc) => enc, Err(e) => { - rows.push(missing_direction("ec-hw av1 10-bit", "encode", &format!("driver refused ({e})"))); + rows.push(missing_direction(component, "encode", &format!("driver refused ({e})"))); return; } }; - let read = |s: &[u8]| -> Vec { + let read16 = |s: &[u8]| -> Vec { s.as_chunks::<2>().0.iter().map(|p| u16::from_le_bytes([p[0], p[1]])).collect() }; let start = Instant::now(); let mut coded = 0usize; for (i, frame) in raw.chunks_exact(frame_len).enumerate() { - let (y, rest) = frame.split_at((w * h * 2) as usize); + let (y, rest) = frame.split_at((w * h) as usize * bytes); let (u, v) = rest.split_at(rest.len() / 2); - let picture = ec_hw::I420_16 { - y: read(y), - u: read(u), - v: read(v), - width: w, - height: h, - bit_depth: 10, - }; let meta = ec_hw::FrameMetadata { timestamp: i as i64, force_keyframe: false }; - match enc.encode_16(&picture, meta) { + let result = if ten_bit { + enc.encode_16( + &ec_hw::I420_16 { + y: read16(y), + u: read16(u), + v: read16(v), + width: w, + height: h, + bit_depth: 10, + }, + meta, + ) + } else { + enc.encode( + &ec_hw::I420 { + y: y.to_vec(), + u: u.to_vec(), + v: v.to_vec(), + width: w, + height: h, + }, + meta, + ) + }; + match result { Ok(out) => coded += out.data.len(), Err(e) => { - rows.push(missing_direction("ec-hw av1 10-bit", "encode", &format!("encode failed ({e})"))); + rows.push(missing_direction(component, "encode", &format!("encode failed ({e})"))); return; } } } let wall = start.elapsed().as_secs_f64(); let media_s = f64::from(n) / 30.0; - rows.push(Row { - component: "ec-hw av1 10-bit", - direction: "encode", - content: format!("{w}x{h} yuv420p10le, {n} frames from 00:00:30, CQP 120, {} kB", coded / 1000), - media: format!("{media_s:.1}s"), - wall_ms: wall * 1000.0, - rtf: (wall > 0.0).then_some(media_s / wall), - }); -} - -/// `extract_yuv420p` at ten bits, planar 16-bit little endian, seeked -/// into the clip: frame 0 of a film is its black leader, and a black leader codes -/// to nothing and benchmarks nothing. -fn extract_yuv420p10(src: &Path, w: u32, h: u32, n: u32) -> Vec { - let out = ec_testkit::ffmpeg() - .args(["-v", "error", "-ss", SEEK_SECONDS, "-i"]) - .arg(src) - .args([ - "-vf", &format!("scale={w}:{h}"), - "-frames:v", &n.to_string(), - "-pix_fmt", "yuv420p10le", - "-f", "rawvideo", "-", - ]) - .output() - .expect("ffmpeg extract yuv420p10le"); - if !out.status.success() { - return Vec::new(); - } - out.stdout + let content = format!("{w}x{h} {pix_fmt}, {n} frames, CQP 120, {} kB", coded / 1000); + rows.push(Row::timed(component, "encode", content, media_s, wall)); } // --------------------------------------------------------------------------- @@ -480,7 +408,10 @@ fn bench_av1_encode(rows: &mut Vec) { return; }; // AV1's block grid is 32x32 superblocks: pick a size already a multiple of it. - let (planes, w, h, n) = extract_yuv420p(&src, 640, 384, 10); + let (w, h) = (640, 384); + let planes = extract_raw(&src, w, h, 10, "yuv420p"); + let frame_len = yuv420_frame_len(w, h, 1); + let n = (planes.len() / frame_len) as u32; if n == 0 { rows.push(missing("ec-av1", "encode")); rows.push(missing("ec-av1", "decode")); @@ -530,7 +461,6 @@ fn bench_av1_encode(rows: &mut Vec) { None => Av1Encoder::with_speed(cfg, speed).expect("av1 encoder"), Some(p) => Av1Encoder::with_pyramid(cfg, p).expect("av1 encoder"), }; - let frame_len = (w * h + 2 * (w.div_ceil(2) * h.div_ceil(2))) as usize; let mut stream = Vec::new(); let mut hidden = 0usize; let start = Instant::now(); @@ -571,17 +501,11 @@ fn bench_av1_encode(rows: &mut Vec) { }; let fps = if wall > 0.0 { f64::from(n) / wall } else { 0.0 }; let bytes_per_frame = stream.len() as f64 / f64::from(n); - rows.push(Row { - component: "ec-av1", - direction: "encode", - content: format!( - "speed {speed} [{levers}], {w}x{h}, {n} frames, gop=10, {coded_under}, \ - {hidden} hidden, {fps:.1} fps, {bytes_per_frame:.0} B/frame" - ), - media: format!("{media_s:.1}s"), - wall_ms: wall * 1000.0, - rtf: (wall > 0.0).then_some(media_s / wall), - }); + let content = format!( + "speed {speed} [{levers}], {w}x{h}, {n} frames, gop=10, {coded_under}, \ + {hidden} hidden, {fps:.1} fps, {bytes_per_frame:.0} B/frame" + ); + rows.push(Row::timed("ec-av1", "encode", content, media_s, wall)); if first_stream.is_empty() { first_stream = stream; } @@ -595,14 +519,7 @@ fn bench_av1_encode(rows: &mut Vec) { let pictures = ec_av1::stream::decode_stream(&stream).expect("av1 decode_stream"); let wall = start.elapsed().as_secs_f64(); assert_eq!(pictures.len(), n as usize, "decode_stream frame count"); - rows.push(Row { - component: "ec-av1", - direction: "decode", - content: format!("{w}x{h}, {n} frames, gop=10"), - media: format!("{media_s:.1}s"), - wall_ms: wall * 1000.0, - rtf: (wall > 0.0).then_some(media_s / wall), - }); + rows.push(Row::timed("ec-av1", "decode", format!("{w}x{h}, {n} frames, gop=10"), media_s, wall)); } // --------------------------------------------------------------------------- @@ -719,14 +636,7 @@ fn bench_audio_encode(rows: &mut Vec) { .expect("opus encode"); } let wall = start.elapsed().as_secs_f64(); - rows.push(Row { - component: "ec-opus", - direction: "encode", - content: content.clone(), - media: format!("{media_s:.1}s"), - wall_ms: wall * 1000.0, - rtf: (wall > 0.0).then_some(media_s / wall), - }); + rows.push(Row::timed("ec-opus", "encode", content.clone(), media_s, wall)); } // vorbis: quality 0.6, the level the oracle tests already encode at. @@ -751,14 +661,7 @@ fn bench_audio_encode(rows: &mut Vec) { } let wall = start.elapsed().as_secs_f64(); let _ = n; - rows.push(Row { - component: "ec-vorbis", - direction: "encode", - content: content.clone(), - media: format!("{media_s:.1}s"), - wall_ms: wall * 1000.0, - rtf: (wall > 0.0).then_some(media_s / wall), - }); + rows.push(Row::timed("ec-vorbis", "encode", content.clone(), media_s, wall)); } // aac: 128 kbit/s, raw (no ADTS wrap) -- the default config. @@ -769,14 +672,7 @@ fn bench_audio_encode(rows: &mut Vec) { enc.finish(); while enc.next_packet().is_ok() {} let wall = start.elapsed().as_secs_f64(); - rows.push(Row { - component: "ec-aac", - direction: "encode", - content: content.clone(), - media: format!("{media_s:.1}s"), - wall_ms: wall * 1000.0, - rtf: (wall > 0.0).then_some(media_s / wall), - }); + rows.push(Row::timed("ec-aac", "encode", content.clone(), media_s, wall)); } // mp3: CBR 192 kbit/s, the incumbent-matching default the tests gate on. @@ -791,14 +687,7 @@ fn bench_audio_encode(rows: &mut Vec) { enc.finish(); while enc.next_packet().is_ok() {} let wall = start.elapsed().as_secs_f64(); - rows.push(Row { - component: "ec-mp3", - direction: "encode", - content: content.clone(), - media: format!("{media_s:.1}s"), - wall_ms: wall * 1000.0, - rtf: (wall > 0.0).then_some(media_s / wall), - }); + rows.push(Row::timed("ec-mp3", "encode", content.clone(), media_s, wall)); } // flac: single-shot, default config (4096-sample blocks, LPC-12), 16-bit. @@ -811,14 +700,7 @@ fn bench_audio_encode(rows: &mut Vec) { let start = Instant::now(); let _ = ec_flac::encode(&cfg, &samples, channels, 16, rate).expect("flac encode"); let wall = start.elapsed().as_secs_f64(); - rows.push(Row { - component: "ec-flac", - direction: "encode", - content: content.clone(), - media: format!("{media_s:.1}s"), - wall_ms: wall * 1000.0, - rtf: (wall > 0.0).then_some(media_s / wall), - }); + rows.push(Row::timed("ec-flac", "encode", content.clone(), media_s, wall)); } // alac: 4096-sample frames, 16-bit -- same shape the round-trip tests use. @@ -834,14 +716,7 @@ fn bench_audio_encode(rows: &mut Vec) { enc.encode_frame(chunk).expect("alac frame"); } let wall = start.elapsed().as_secs_f64(); - rows.push(Row { - component: "ec-alac", - direction: "encode", - content: content.clone(), - media: format!("{media_s:.1}s"), - wall_ms: wall * 1000.0, - rtf: (wall > 0.0).then_some(media_s / wall), - }); + rows.push(Row::timed("ec-alac", "encode", content.clone(), media_s, wall)); } // ac3: 192 kbit/s -- only if the source's channel count is one A/52 codes. @@ -863,14 +738,7 @@ fn bench_audio_encode(rows: &mut Vec) { } } let wall = start.elapsed().as_secs_f64(); - rows.push(Row { - component: "ec-ac3", - direction: "encode", - content, - media: format!("{media_s:.1}s"), - wall_ms: wall * 1000.0, - rtf: (wall > 0.0).then_some(media_s / wall), - }); + rows.push(Row::timed("ec-ac3", "encode", content, media_s, wall)); } else { rows.push(missing_direction( "ec-ac3", @@ -930,14 +798,7 @@ fn bench_truehd(rows: &mut Vec) { thd.extend_from_slice(&pkt.data); } let wall = start.elapsed().as_secs_f64(); - rows.push(Row { - component: "ec-truehd", - direction: "encode", - content: format!("{media_s:.1}s wav16 stereo @ {rate}Hz"), - media: format!("{media_s:.1}s"), - wall_ms: wall * 1000.0, - rtf: (wall > 0.0).then_some(media_s / wall), - }); + rows.push(Row::timed("ec-truehd", "encode", format!("{media_s:.1}s wav16 stereo @ {rate}Hz"), media_s, wall)); let mut dec = ec_truehd::TrueHdDecoder::new(); let start = Instant::now(); @@ -957,14 +818,7 @@ fn bench_truehd(rows: &mut Vec) { } let wall = start.elapsed().as_secs_f64(); let media_s = samples as f64 / f64::from(rate); - rows.push(Row { - component: "ec-truehd", - direction: "decode", - content: "own encoded stream, stereo".to_string(), - media: format!("{media_s:.1}s"), - wall_ms: wall * 1000.0, - rtf: (wall > 0.0).then_some(media_s / wall), - }); + rows.push(Row::timed("ec-truehd", "decode", "own encoded stream, stereo".to_string(), media_s, wall)); } // --------------------------------------------------------------------------- diff --git a/tools/oracle/Cargo.toml b/tools/oracle/Cargo.toml deleted file mode 100644 index b3b8683c..00000000 --- a/tools/oracle/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "oracle" -version.workspace = true -edition.workspace = true -license.workspace = true -authors.workspace = true -publish = false - -[[bin]] -name = "oracle" -path = "src/main.rs" - -# No dependencies on purpose: the oracle drives ffmpeg/ffprobe through std process -# pipes so that comparison tooling can never leak into any ec-* crate's dep graph. -[dependencies] -ec-testkit.workspace = true diff --git a/tools/oracle/src/main.rs b/tools/oracle/src/main.rs deleted file mode 100644 index ad4a7091..00000000 --- a/tools/oracle/src/main.rs +++ /dev/null @@ -1,579 +0,0 @@ -//! `oracle` — ffmpeg-backed comparison harness for the edith_codecs family. -//! -//! ffmpeg/ffprobe are ORACLE tooling: they are driven here through `std::process` -//! pipes so no `ec-*` crate ever gains a media dependency, sync or async. -//! -//! Subcommands: -//! `bit-exact ` byte-identical check -//! `audio-compare ` per-channel correlation + RMS delta -//! `video-compare ` per-frame PSNR, min/mean -//! -//! `` is our decoder's raw output: interleaved f32 LE for audio, raw -//! planar/packed frames in `--pix-fmt` order for video. The reference is any file -//! ffmpeg can decode; it is decoded to the same raw layout and compared. -//! -//! stdout is TSV (every line `type...`), stderr is the human summary. -//! Exit code: 0 = PASS, 1 = FAIL, 2 = usage/IO error. - -#![forbid(unsafe_code)] - -use std::collections::HashMap; -use std::process::Stdio; - -const USAGE: &str = "\ -oracle — comparison harness (ffmpeg is test tooling only) - - oracle bit-exact - oracle audio-compare [--channels N] [--min-corr F] [--max-rms F] - oracle video-compare [--pix-fmt FMT] [--size WxH] [--min-psnr DB] - -Defaults: --min-corr 0.999 --max-rms 1e-3 --min-psnr 40 -Missing --channels/--pix-fmt/--size are probed from with ffprobe. -"; - -fn main() { - let argv: Vec = std::env::args().skip(1).collect(); - let rc = match argv.first().map(String::as_str) { - Some("bit-exact") => run(cmd_bit_exact(&argv[1..])), - Some("audio-compare") => run(cmd_audio_compare(&argv[1..])), - Some("video-compare") => run(cmd_video_compare(&argv[1..])), - Some("-h") | Some("--help") => { - print!("{USAGE}"); - 0 - } - _ => { - eprint!("{USAGE}"); - 2 - } - }; - std::process::exit(rc); -} - -fn run(r: Result) -> i32 { - match r { - Ok(true) => 0, - Ok(false) => 1, - Err(e) => { - eprintln!("oracle: {e}"); - 2 - } - } -} - -// ------------------------------------------------------------------ args --- - -struct Args { - pos: Vec, - flags: HashMap, -} - -impl Args { - fn parse(argv: &[String]) -> Result { - let mut pos = Vec::new(); - let mut flags = HashMap::new(); - let mut it = argv.iter(); - while let Some(a) = it.next() { - if let Some(key) = a.strip_prefix("--") { - let v = it - .next() - .ok_or_else(|| format!("flag --{key} needs a value"))?; - flags.insert(key.to_string(), v.clone()); - } else { - pos.push(a.clone()); - } - } - Ok(Self { pos, flags }) - } - - fn num(&self, key: &str, default: T) -> Result { - match self.flags.get(key) { - None => Ok(default), - Some(v) => v.parse().map_err(|_| format!("bad --{key} value: {v}")), - } - } -} - -// --------------------------------------------------------------- ffmpeg ---- - -/// Decode `input` with ffmpeg and return the raw bytes it writes to stdout. -/// stderr is inherited so a large error log can never deadlock the pipe. -fn ffmpeg_raw(input: &str, extra: &[&str]) -> Result, String> { - let out = ec_testkit::ffmpeg() - .args(["-nostdin", "-v", "error", "-i", input]) - .args(extra) - .arg("-") - .stdout(Stdio::piped()) - .stderr(Stdio::inherit()) - .output() - .map_err(|e| format!("spawning ffmpeg: {e}"))?; - if !out.status.success() { - return Err(format!("ffmpeg failed on {input} ({})", out.status)); - } - if out.stdout.is_empty() { - return Err(format!("ffmpeg produced no data for {input}")); - } - Ok(out.stdout) -} - -/// `ffprobe -show_entries stream=` as a key -> value map (first stream wins). -fn ffprobe(input: &str, select: &str, entries: &str) -> Result, String> { - let out = ec_testkit::ffprobe() - .args(["-v", "error", "-select_streams", select, "-show_entries"]) - .arg(format!("stream={entries}")) - .args(["-of", "default=nw=1"]) - .arg(input) - .stderr(Stdio::inherit()) - .output() - .map_err(|e| format!("spawning ffprobe: {e}"))?; - if !out.status.success() { - return Err(format!("ffprobe failed on {input} ({})", out.status)); - } - let mut map = HashMap::new(); - for line in String::from_utf8_lossy(&out.stdout).lines() { - if let Some((k, v)) = line.split_once('=') - && v != "N/A" - { - map.entry(k.to_string()).or_insert_with(|| v.to_string()); - } - } - Ok(map) -} - -fn read_file(path: &str) -> Result, String> { - std::fs::read(path).map_err(|e| format!("reading {path}: {e}")) -} - -// ------------------------------------------------------------ bit-exact ---- - -fn cmd_bit_exact(argv: &[String]) -> Result { - let a = Args::parse(argv)?; - if a.pos.len() != 2 { - return Err("bit-exact needs exactly two files".into()); - } - let (x, y) = (read_file(&a.pos[0])?, read_file(&a.pos[1])?); - let first_diff = x.iter().zip(&y).position(|(p, q)| p != q); - let pass = x.len() == y.len() && first_diff.is_none(); - - println!("meta\ta\t{}", a.pos[0]); - println!("meta\tb\t{}", a.pos[1]); - println!("meta\tlen_a\t{}", x.len()); - println!("meta\tlen_b\t{}", y.len()); - match first_diff { - Some(off) => println!("diff\tfirst_offset\t{off}"), - None => println!("diff\tfirst_offset\t-"), - } - println!("verdict\t{}", if pass { "PASS" } else { "FAIL" }); - eprintln!( - "bit-exact: {} ({} vs {} bytes, first diff {})", - if pass { "PASS" } else { "FAIL" }, - x.len(), - y.len(), - first_diff.map_or("-".into(), |o| o.to_string()) - ); - Ok(pass) -} - -// -------------------------------------------------------------- audio ------ - -fn deinterleave_f32(buf: &[u8], channels: usize) -> Vec> { - let frames = buf.len() / 4 / channels; - let mut out = vec![Vec::with_capacity(frames); channels]; - for f in 0..frames { - for (c, ch) in out.iter_mut().enumerate() { - let i = (f * channels + c) * 4; - ch.push(f32::from_le_bytes([buf[i], buf[i + 1], buf[i + 2], buf[i + 3]]) as f64); - } - } - out -} - -/// Pearson correlation. Two constant signals correlate perfectly iff equal. -fn corr(a: &[f64], b: &[f64]) -> f64 { - let n = a.len().min(b.len()); - if n == 0 { - return 0.0; - } - let (ma, mb) = ( - a[..n].iter().sum::() / n as f64, - b[..n].iter().sum::() / n as f64, - ); - let (mut num, mut da, mut db) = (0.0, 0.0, 0.0); - for i in 0..n { - let (x, y) = (a[i] - ma, b[i] - mb); - num += x * y; - da += x * x; - db += y * y; - } - if da == 0.0 || db == 0.0 { - return if da == db && (ma - mb).abs() < 1e-12 { - 1.0 - } else { - 0.0 - }; - } - num / (da * db).sqrt() -} - -fn rms_delta(a: &[f64], b: &[f64]) -> (f64, f64) { - let n = a.len().min(b.len()); - if n == 0 { - return (f64::INFINITY, f64::INFINITY); - } - let mut sum = 0.0; - let mut peak: f64 = 0.0; - for i in 0..n { - let d = a[i] - b[i]; - sum += d * d; - peak = peak.max(d.abs()); - } - ((sum / n as f64).sqrt(), peak) -} - -fn cmd_audio_compare(argv: &[String]) -> Result { - let a = Args::parse(argv)?; - if a.pos.len() != 2 { - return Err("audio-compare needs ".into()); - } - let (ours_path, ref_path) = (&a.pos[0], &a.pos[1]); - let min_corr: f64 = a.num("min-corr", 0.999)?; - let max_rms: f64 = a.num("max-rms", 1e-3)?; - - let probe = ffprobe(ref_path, "a:0", "channels,sample_rate")?; - let channels: usize = match a.flags.get("channels") { - Some(v) => v.parse().map_err(|_| "bad --channels".to_string())?, - None => probe - .get("channels") - .ok_or("could not probe channel count; pass --channels")? - .parse() - .map_err(|_| "bad probed channel count".to_string())?, - }; - if channels == 0 { - return Err("channel count is zero".into()); - } - let rate = probe - .get("sample_rate") - .cloned() - .unwrap_or_else(|| "-".into()); - - let ours = read_file(ours_path)?; - let reference = ffmpeg_raw( - ref_path, - &["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le"], - )?; - let (na, nb) = (ours.len() / 4 / channels, reference.len() / 4 / channels); - let (ca, cb) = ( - deinterleave_f32(&ours, channels), - deinterleave_f32(&reference, channels), - ); - - println!("meta\tours\t{ours_path}"); - println!("meta\tref\t{ref_path}"); - println!("meta\tchannels\t{channels}"); - println!("meta\tsample_rate\t{rate}"); - println!("meta\tframes_ours\t{na}"); - println!("meta\tframes_ref\t{nb}"); - - // A length gap beyond one percent is a decoder bug (dropped/duplicated - // packets), not a comparison detail — it fails on its own. - let len_ok = na.abs_diff(nb) as f64 <= 0.01 * na.max(nb) as f64; - let mut min_c = f64::INFINITY; - let mut max_r: f64 = 0.0; - for c in 0..channels { - let k = corr(&ca[c], &cb[c]); - let (r, p) = rms_delta(&ca[c], &cb[c]); - min_c = min_c.min(k); - max_r = max_r.max(r); - println!("ch\t{c}\tcorr\t{k:.6}\trms\t{r:.8}\tpeak\t{p:.8}"); - } - let pass = len_ok && min_c >= min_corr && max_r <= max_rms; - println!( - "verdict\t{}\tmin_corr={min_c:.6}\tmax_rms={max_r:.8}\tlen_ok={len_ok}", - if pass { "PASS" } else { "FAIL" } - ); - eprintln!( - "audio-compare: {} — {channels}ch @{rate}, min corr {min_c:.6} (>= {min_corr}), \ - max RMS delta {max_r:.8} (<= {max_rms}), lengths {na}/{nb}", - if pass { "PASS" } else { "FAIL" } - ); - Ok(pass) -} - -// -------------------------------------------------------------- video ------ - -/// Raw-frame geometry for a pixel format: total samples, luma samples (0 when the -/// format is packed and has no contiguous luma plane), bytes per sample, max value. -struct PixGeom { - samples: usize, - luma: usize, - bps: usize, - max: f64, -} - -fn pix_geom(pix_fmt: &str, w: usize, h: usize) -> Result { - let wh = w * h; - let g = |samples: usize, luma: usize, bps: usize, max: f64| PixGeom { - samples, - luma, - bps, - max, - }; - // Semi-planar formats carry their depth inside the name, so match them first. - match pix_fmt { - "nv12" | "nv21" => return Ok(g(wh * 3 / 2, wh, 1, 255.0)), - "p010le" | "p010be" => return Ok(g(wh * 3 / 2, wh, 2, 1023.0)), - "p016le" | "p016be" => return Ok(g(wh * 3 / 2, wh, 2, 65535.0)), - _ => {} - } - let mut base = pix_fmt; - let mut bps = 1; - let mut max = 255.0; - for (suffix, depth) in [("9", 9u32), ("10", 10), ("12", 12), ("14", 14), ("16", 16)] { - for endian in ["le", "be"] { - let s = format!("{suffix}{endian}"); - if let Some(b) = pix_fmt.strip_suffix(&s) { - base = b; - bps = 2; - max = ((1u32 << depth) - 1) as f64; - } - } - } - let geom = match base { - "yuv420p" | "yuvj420p" => g(wh * 3 / 2, wh, bps, max), - "yuv422p" | "yuvj422p" => g(wh * 2, wh, bps, max), - "yuv444p" | "yuvj444p" | "gbrp" => g(wh * 3, wh, bps, max), - "gray" => g(wh, wh, bps, max), - // Packed: no contiguous luma plane, so luma PSNR falls back to all-plane. - "yuyv422" | "uyvy422" => g(wh * 2, 0, bps, max), - "rgb24" | "bgr24" => g(wh * 3, 0, bps, max), - "rgba" | "bgra" | "argb" | "abgr" => g(wh * 4, 0, bps, max), - _ => return Err(format!("unsupported pix_fmt for raw compare: {pix_fmt}")), - }; - Ok(geom) -} - -fn sample(buf: &[u8], i: usize, bps: usize) -> f64 { - if bps == 1 { - buf[i] as f64 - } else { - u16::from_le_bytes([buf[2 * i], buf[2 * i + 1]]) as f64 - } -} - -/// PSNR over `n` samples starting at sample index `off` in both buffers. -fn psnr(a: &[u8], b: &[u8], off: usize, n: usize, bps: usize, max: f64) -> f64 { - let mut sum = 0.0; - for i in off..off + n { - let d = sample(a, i, bps) - sample(b, i, bps); - sum += d * d; - } - let mse = sum / n as f64; - if mse == 0.0 { - f64::INFINITY - } else { - 10.0 * (max * max / mse).log10() - } -} - -fn cmd_video_compare(argv: &[String]) -> Result { - let a = Args::parse(argv)?; - if a.pos.len() != 2 { - return Err("video-compare needs ".into()); - } - let (ours_path, ref_path) = (&a.pos[0], &a.pos[1]); - let min_psnr: f64 = a.num("min-psnr", 40.0)?; - - let probe = ffprobe(ref_path, "v:0", "width,height,pix_fmt")?; - let pix = match a.flags.get("pix-fmt") { - Some(v) => v.clone(), - None => probe - .get("pix_fmt") - .cloned() - .ok_or("could not probe pix_fmt; pass --pix-fmt")?, - }; - let (w, h) = match a.flags.get("size") { - Some(s) => { - let (ws, hs) = s.split_once('x').ok_or("--size must look like 1920x1080")?; - ( - ws.parse::().map_err(|_| "bad --size width")?, - hs.parse::().map_err(|_| "bad --size height")?, - ) - } - None => ( - probe - .get("width") - .ok_or("could not probe width; pass --size")? - .parse() - .map_err(|_| "bad probed width".to_string())?, - probe - .get("height") - .ok_or("could not probe height; pass --size")? - .parse() - .map_err(|_| "bad probed height".to_string())?, - ), - }; - - let geom = pix_geom(&pix, w, h)?; - let frame_bytes = geom.samples * geom.bps; - if frame_bytes == 0 { - return Err("frame size computed as zero".into()); - } - - let ours = read_file(ours_path)?; - let reference = ffmpeg_raw( - ref_path, - &["-map", "0:v:0", "-f", "rawvideo", "-pix_fmt", &pix], - )?; - let (fa, fb) = (ours.len() / frame_bytes, reference.len() / frame_bytes); - let frames = fa.min(fb); - - println!("meta\tours\t{ours_path}"); - println!("meta\tref\t{ref_path}"); - println!("meta\tpix_fmt\t{pix}"); - println!("meta\tdims\t{w}x{h}"); - println!("meta\tframe_bytes\t{frame_bytes}"); - println!("meta\tframes_ours\t{fa}"); - println!("meta\tframes_ref\t{fb}"); - if frames == 0 { - println!("verdict\tFAIL\tno complete frame in common"); - eprintln!("video-compare: FAIL — no complete frame in common ({fa} vs {fb})"); - return Ok(false); - } - - let luma_n = if geom.luma == 0 { - geom.samples - } else { - geom.luma - }; - let mut min_y = f64::INFINITY; - let mut sum_y = 0.0; - let mut min_all = f64::INFINITY; - let mut sum_all = 0.0; - let mut finite_y = 0usize; - let mut finite_all = 0usize; - for f in 0..frames { - let off = f * geom.samples; - let py = psnr(&ours, &reference, off, luma_n, geom.bps, geom.max); - let pa = psnr(&ours, &reference, off, geom.samples, geom.bps, geom.max); - min_y = min_y.min(py); - min_all = min_all.min(pa); - if py.is_finite() { - sum_y += py; - finite_y += 1; - } - if pa.is_finite() { - sum_all += pa; - finite_all += 1; - } - println!("frame\t{f}\tpsnr_y\t{py:.4}\tpsnr_all\t{pa:.4}"); - } - // Mean over finite frames only: identical frames give +inf and would otherwise - // poison the average of a run that also contains real differences. - let mean_y = if finite_y == 0 { - f64::INFINITY - } else { - sum_y / finite_y as f64 - }; - let mean_all = if finite_all == 0 { - f64::INFINITY - } else { - sum_all / finite_all as f64 - }; - let len_ok = fa == fb; - let pass = len_ok && min_y >= min_psnr; - println!("stats\tpsnr_y\tmin\t{min_y:.4}\tmean\t{mean_y:.4}"); - println!("stats\tpsnr_all\tmin\t{min_all:.4}\tmean\t{mean_all:.4}"); - println!( - "verdict\t{}\tmin_psnr_y={min_y:.4}\tframes={frames}\tlen_ok={len_ok}", - if pass { "PASS" } else { "FAIL" } - ); - eprintln!( - "video-compare: {} — {frames} frames {w}x{h} {pix}, min luma PSNR {min_y:.4} dB \ - (>= {min_psnr}), mean {mean_y:.4} dB, frame counts {fa}/{fb}", - if pass { "PASS" } else { "FAIL" } - ); - Ok(pass) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn corr_identical_and_inverted() { - let a = [0.0, 1.0, -1.0, 0.5, -0.25]; - let inv: Vec = a.iter().map(|x| -x).collect(); - assert!((corr(&a, &a) - 1.0).abs() < 1e-12); - assert!((corr(&a, &inv) + 1.0).abs() < 1e-12); - // Silence vs silence correlates; silence vs DC offset does not. - assert_eq!(corr(&[0.0; 4], &[0.0; 4]), 1.0); - assert_eq!(corr(&[0.0; 4], &[1.0; 4]), 0.0); - } - - #[test] - fn rms_and_peak_delta() { - let (r, p) = rms_delta(&[0.0, 0.0, 0.0], &[0.0, 0.0, 0.0]); - assert_eq!((r, p), (0.0, 0.0)); - let (r, p) = rms_delta(&[1.0, -1.0], &[0.0, 0.0]); - assert!((r - 1.0).abs() < 1e-12 && (p - 1.0).abs() < 1e-12); - } - - #[test] - fn psnr_identical_is_infinite_and_differing_is_finite() { - let a = vec![10u8, 20, 30, 40]; - assert!(psnr(&a, &a, 0, 4, 1, 255.0).is_infinite()); - let b = vec![11u8, 21, 31, 41]; - let p = psnr(&a, &b, 0, 4, 1, 255.0); - // MSE 1 over 8-bit range: 10*log10(255^2) = 48.13 dB. - assert!((p - 48.1308).abs() < 1e-3, "psnr={p}"); - // 10-bit path reads little-endian u16 pairs. - let x = [0u8, 1, 0, 1]; - let y = [1u8, 1, 0, 1]; - assert!(psnr(&x, &y, 0, 2, 2, 1023.0).is_finite()); - } - - #[test] - fn pix_geom_covers_the_generated_fixture_formats() { - let (w, h) = (1920, 1080); - let g = pix_geom("yuv420p", w, h).unwrap(); - assert_eq!( - (g.samples, g.luma, g.bps, g.max), - (w * h * 3 / 2, w * h, 1, 255.0) - ); - let g = pix_geom("yuv420p10le", w, h).unwrap(); - assert_eq!( - (g.samples, g.luma, g.bps, g.max), - (w * h * 3 / 2, w * h, 2, 1023.0) - ); - let g = pix_geom("p010le", w, h).unwrap(); - assert_eq!((g.samples, g.bps, g.max), (w * h * 3 / 2, 2, 1023.0)); - assert_eq!(pix_geom("yuv444p", w, h).unwrap().samples, w * h * 3); - assert_eq!(pix_geom("yuyv422", w, h).unwrap().luma, 0); - assert!(pix_geom("no_such_fmt", w, h).is_err()); - } - - #[test] - fn deinterleave_splits_channels() { - let mut buf = Vec::new(); - for f in 0..3u32 { - for c in 0..2u32 { - buf.extend_from_slice(&((f * 10 + c) as f32).to_le_bytes()); - } - } - let ch = deinterleave_f32(&buf, 2); - assert_eq!(ch[0], vec![0.0, 10.0, 20.0]); - assert_eq!(ch[1], vec![1.0, 11.0, 21.0]); - } - - #[test] - fn args_parse_flags_and_positionals() { - let argv: Vec = ["a.raw", "b.mp4", "--min-corr", "0.5"] - .iter() - .map(|s| s.to_string()) - .collect(); - let a = Args::parse(&argv).unwrap(); - assert_eq!(a.pos, ["a.raw", "b.mp4"]); - assert_eq!(a.num::("min-corr", 0.999).unwrap(), 0.5); - assert_eq!(a.num::("max-rms", 1e-3).unwrap(), 1e-3); - assert!(Args::parse(&["--dangling".to_string()]).is_err()); - } -} diff --git a/tools/oracle/tests/cli.rs b/tools/oracle/tests/cli.rs deleted file mode 100644 index 6eb1fbc7..00000000 --- a/tools/oracle/tests/cli.rs +++ /dev/null @@ -1,129 +0,0 @@ -//! Self-test of the `oracle` CLI itself: drives the built binary the way a codec -//! crate's test will, using ffmpeg as both the "our decoder" stand-in and the -//! reference. Exercises the PASS and the FAIL path of every subcommand. -//! - -use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; - -// Per-test directory: the test binary runs its cases as threads of one process, -// so a pid-only name would let one case delete another's raw files. -fn workdir(name: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("oracle-selftest-{}-{name}", std::process::id())); - std::fs::create_dir_all(&d).unwrap(); - d -} - -/// Decode `input` to a raw file with ffmpeg — stands in for "our decoder's output". -fn decode_raw(input: &Path, out: &Path, extra: &[&str]) { - let f = std::fs::File::create(out).unwrap(); - let st = ec_testkit::ffmpeg() - .args(["-nostdin", "-y", "-v", "error", "-i"]) - .arg(input) - .args(extra) - .arg("-") - .stdout(Stdio::from(f)) - .status() - .expect("ffmpeg must be installed to run the oracle self-test"); - assert!(st.success(), "ffmpeg failed decoding {}", input.display()); -} - -fn oracle(args: &[&str]) -> i32 { - Command::new(env!("CARGO_BIN_EXE_oracle")) - .args(args) - .status() - .expect("oracle binary") - .code() - .expect("oracle exited by signal") -} - -const F32: &[&str] = &["-map", "0:a:0", "-f", "f32le", "-acodec", "pcm_f32le"]; - -#[test] -fn bit_exact_passes_on_same_decode_and_fails_on_a_different_one() { - let a = ec_testkit::fixture("audio/flac-stereo-48000.flac"); - let b = ec_testkit::fixture("audio/flac-mono-48000.flac"); - let w = workdir("bitexact"); - let (r1, r2, r3) = (w.join("a1.raw"), w.join("a2.raw"), w.join("b.raw")); - decode_raw(&a, &r1, F32); - decode_raw(&a, &r2, F32); - decode_raw(&b, &r3, F32); - - assert_eq!( - oracle(&["bit-exact", r1.to_str().unwrap(), r2.to_str().unwrap()]), - 0, - "same file decoded twice must be bit-exact" - ); - assert_eq!( - oracle(&["bit-exact", r1.to_str().unwrap(), r3.to_str().unwrap()]), - 1, - "different fixtures must not be bit-exact" - ); - let _ = std::fs::remove_dir_all(&w); -} - -#[test] -fn audio_compare_passes_against_its_own_source_and_fails_across_rates() { - let a = ec_testkit::fixture("audio/flac-stereo-48000.flac"); - let b = ec_testkit::fixture("audio/flac-stereo-44100.flac"); - let w = workdir("audio"); - let (ra, rb) = (w.join("a.raw"), w.join("b.raw")); - decode_raw(&a, &ra, F32); - decode_raw(&b, &rb, F32); - - assert_eq!( - oracle(&["audio-compare", ra.to_str().unwrap(), a.to_str().unwrap()]), - 0, - "lossless decode vs its own source must correlate at 1.0" - ); - // 44.1 kHz samples against a 48 kHz reference: wrong length and wrong phase. - assert_eq!( - oracle(&["audio-compare", rb.to_str().unwrap(), a.to_str().unwrap()]), - 1, - "a different-rate decode must be rejected" - ); - let _ = std::fs::remove_dir_all(&w); -} - -#[test] -fn video_compare_passes_against_its_own_source_and_fails_on_frame_count() { - let a = ec_testkit::fixture("video/h264-1080p-23.976-8bit.mp4"); - let b = ec_testkit::fixture("video/h264-1080p-60-8bit.mp4"); - let w = workdir("video"); - let raw = w.join("a.raw"); - decode_raw( - &a, - &raw, - &["-map", "0:v:0", "-f", "rawvideo", "-pix_fmt", "yuv420p"], - ); - - assert_eq!( - oracle(&[ - "video-compare", - raw.to_str().unwrap(), - a.to_str().unwrap(), - "--pix-fmt", - "yuv420p", - ]), - 0, - "decode vs its own source must be lossless (infinite PSNR)" - ); - assert_eq!( - oracle(&[ - "video-compare", - raw.to_str().unwrap(), - b.to_str().unwrap(), - "--pix-fmt", - "yuv420p", - ]), - 1, - "48 frames against a 120-frame reference must fail" - ); - let _ = std::fs::remove_dir_all(&w); -} - -#[test] -fn bad_usage_exits_two() { - assert_eq!(oracle(&["no-such-subcommand"]), 2); - assert_eq!(oracle(&["bit-exact", "only-one-arg"]), 2); -}