From d00c1d6b936fb6cd3f280cb4315f3444e647f156 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 04:41:35 +0300 Subject: [PATCH] M2 fixtures: mp3/opus/vorbis/flac/dts/truehd/pcm-ext use ec-testkit ffmpeg and fixture paths; skip branches now fail, user-library tests dropped or retargeted to open media --- crates/ec-dts/Cargo.toml | 3 + crates/ec-dts/devscripts/cmp_all.sh | 6 +- crates/ec-dts/devscripts/cmp_float.sh | 6 +- crates/ec-dts/devscripts/fate.sh | 16 - crates/ec-dts/tests/fate_vectors.rs | 56 +- crates/ec-dts/tests/ffmpeg_exact.rs | 101 +- crates/ec-flac/Cargo.toml | 3 + crates/ec-flac/fuzz/seed.sh | 4 +- crates/ec-flac/tests/encode_matrix.rs | 98 +- crates/ec-flac/tests/level_depth_parity.rs | 10 +- crates/ec-flac/tests/xiph_vectors.rs | 68 +- crates/ec-mp3/Cargo.toml | 3 + crates/ec-mp3/fuzz/seed.sh | 3 +- crates/ec-mp3/tests/decode_matrix.rs | 35 +- crates/ec-mp3/tests/encode_matrix.rs | 519 +--- crates/ec-mp3/tests/mp2_matrix.rs | 46 +- crates/ec-opus/Cargo.toml | 1 + crates/ec-opus/fuzz/seed.sh | 7 +- crates/ec-opus/tests/conformance.rs | 2658 ++------------------ crates/ec-pcm-ext/Cargo.toml | 1 + crates/ec-pcm-ext/tests/oracle.rs | 59 +- crates/ec-truehd/Cargo.toml | 1 + crates/ec-truehd/fuzz/seed.sh | 7 +- crates/ec-truehd/tests/it/atmos_synth.rs | 95 +- crates/ec-truehd/tests/it/common.rs | 18 +- crates/ec-truehd/tests/it/fixture_exact.rs | 117 +- crates/ec-truehd/tests/it/library.rs | 150 +- crates/ec-truehd/tests/it/oracle.rs | 88 +- crates/ec-vorbis/Cargo.toml | 1 + crates/ec-vorbis/fuzz/seed.sh | 4 +- crates/ec-vorbis/tests/oracle.rs | 988 +------- crates/ec-vorbis/tests/trim.rs | 5 +- 32 files changed, 538 insertions(+), 4639 deletions(-) delete mode 100755 crates/ec-dts/devscripts/fate.sh diff --git a/crates/ec-dts/Cargo.toml b/crates/ec-dts/Cargo.toml index b563f874..b625aa2a 100644 --- a/crates/ec-dts/Cargo.toml +++ b/crates/ec-dts/Cargo.toml @@ -8,3 +8,6 @@ authors.workspace = true [dependencies] ec-core.workspace = true + +[dev-dependencies] +ec-testkit.workspace = true diff --git a/crates/ec-dts/devscripts/cmp_all.sh b/crates/ec-dts/devscripts/cmp_all.sh index b4269764..f3114776 100755 --- a/crates/ec-dts/devscripts/cmp_all.sh +++ b/crates/ec-dts/devscripts/cmp_all.sh @@ -2,7 +2,9 @@ # Decode each FATE sample with ec-dts and ffmpeg (-flags +bitexact, integer # path) and compare. Needs the dec example built (release). set -u -d=${1:-$HOME/dts-fate} +d=${1:-${EC_FIXTURES:-$HOME/fixtures}/open/fate/dts} +FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg} +FP=$(dirname "$FF")/ffprobe dec=${CARGO_TARGET_DIR:-target}/release/examples/dec here=$(cd "$(dirname "$0")" && pwd) out=${TMPDIR:-/tmp}/dtscmp @@ -13,7 +15,7 @@ for f in "$d"/*; do echo "== $b" "$dec" "$f" "$out/$b.ours" 2>&1 | tail -3 co="-core_only 1"; case "$b" in xch*|dts_es*|x96*) co="";; esac - ffmpeg -v error -y -flags +bitexact $co -i "$f" -f s32le "$out/$b.ref" 2>&1 | tail -2 + "$FF" -v error -y -flags +bitexact $co -i "$f" -f s32le "$out/$b.ref" 2>&1 | tail -2 nch=$(ffprobe -v error -show_entries stream=channels -of csv=p=0 "$f") perm=""; [ "$nch" = 7 ] && perm="0,1,2,3,6,4,5" skip=0; case "$b" in x96*) skip=2048;; *.dtshd) skip=1024;; esac diff --git a/crates/ec-dts/devscripts/cmp_float.sh b/crates/ec-dts/devscripts/cmp_float.sh index cae0e8e1..0056c559 100755 --- a/crates/ec-dts/devscripts/cmp_float.sh +++ b/crates/ec-dts/devscripts/cmp_float.sh @@ -1,7 +1,9 @@ #!/usr/bin/env bash # Compare ec-dts against ffmpeg's default (floating point) decoder path. set -u -d=${1:-$HOME/dts-fate} +d=${1:-${EC_FIXTURES:-$HOME/fixtures}/open/fate/dts} +FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg} +FP=$(dirname "$FF")/ffprobe dec=${CARGO_TARGET_DIR:-target}/release/examples/dec here=$(cd "$(dirname "$0")" && pwd) out=${TMPDIR:-/tmp}/dtscmpf @@ -11,7 +13,7 @@ for f in "$d"/*.dtshd "$d"/dts_es.dts "$here"/../fixtures/*.dts; do case "$b" in xll*|xbr*) continue;; esac co="-core_only 1"; case "$b" in xch*|dts_es*|x96*|*.dts) co="";; esac "$dec" "$f" "$out/$b.ours" 2>/dev/null - ffmpeg -v error -y $co -i "$f" -f f32le "$out/$b.ref" 2>&1 | tail -2 + "$FF" -v error -y $co -i "$f" -f f32le "$out/$b.ref" 2>&1 | tail -2 nch=$(ffprobe -v error -show_entries stream=channels -of csv=p=0 "$f") perm=""; [ "$nch" = 7 ] && perm="0,1,2,3,6,4,5" skip=0; case "$b" in x96*) skip=2048;; *.dtshd) skip=1024;; esac diff --git a/crates/ec-dts/devscripts/fate.sh b/crates/ec-dts/devscripts/fate.sh deleted file mode 100755 index fa86506e..00000000 --- a/crates/ec-dts/devscripts/fate.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env bash -# Fetch the public FFmpeg FATE DTS samples (dcadec conformance suite) into $1. -set -e -d=${1:-$HOME/dts-fate} -mkdir -p "$d" -cd "$d" -base=https://fate-suite.ffmpeg.org/dts -for f in dcadec-suite/core_51_24_48_768_0.dtshd dcadec-suite/core_51_24_48_768_1.dtshd \ - dcadec-suite/x96_51_24_96_1509.dtshd dcadec-suite/x96_xch_61_24_96_3840.dtshd \ - dcadec-suite/xbr_51_24_48_3840.dtshd dcadec-suite/xch_61_24_48_768.dtshd \ - dcadec-suite/xll_51_24_48_768.dtshd dcadec-suite/xll_51_16_192_768_0.dtshd \ - dts_es.dts master_audio_7.1_24bit.dts; do - b=$(basename "$f") - [ -s "$b" ] || curl -sfO "$base/$f" -done -ls "$d" diff --git a/crates/ec-dts/tests/fate_vectors.rs b/crates/ec-dts/tests/fate_vectors.rs index 28df756b..6a236464 100644 --- a/crates/ec-dts/tests/fate_vectors.rs +++ b/crates/ec-dts/tests/fate_vectors.rs @@ -4,24 +4,13 @@ //! kHz, alone and with XCH), the core inside XBR and XLL (DTS-HD) streams and //! a DTS-ES elementary stream. //! -//! The samples are not committed. Fetch them with -//! `devscripts/fate.sh ` and point `EC_DTS_FATE` at the directory -//! (default `fixtures/audio/dts-fate` at the repository root). A missing -//! directory or ffmpeg skips loudly; the committed fixtures in -//! `ffmpeg_exact.rs` are the gate that fails on absence. +//! The samples live in `open/fate/dts` under the fixtures root; a missing one +//! fails. -use std::path::{Path, PathBuf}; -use std::process::Command; +use std::path::Path; use ec_dts::DtsDecoder; -fn dir() -> PathBuf { - match std::env::var("EC_DTS_FATE") { - Ok(p) => PathBuf::from(p), - Err(_) => Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio/dts-fate"), - } -} - /// The STRMDATA chunk of a `.dtshd` file, or the whole buffer. fn strmdata(buf: &[u8]) -> &[u8] { if !buf.starts_with(b"DTSHDHDR") { @@ -67,13 +56,22 @@ fn decode_ours(data: &[u8]) -> (Vec, usize, u32) { } fn decode_ffmpeg(path: &Path, core_only: bool) -> Vec { - let mut cmd = Command::new("ffmpeg"); + let mut cmd = ec_testkit::ffmpeg(); cmd.args(["-v", "error", "-nostdin", "-flags", "+bitexact"]); if core_only { cmd.args(["-core_only", "1"]); } - let out = cmd.arg("-i").arg(path).args(["-f", "s32le", "-"]).output().unwrap(); - assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + let out = cmd + .arg("-i") + .arg(path) + .args(["-f", "s32le", "-"]) + .output() + .unwrap(); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); out.stdout .chunks_exact(4) .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) >> 8) @@ -82,12 +80,6 @@ fn decode_ffmpeg(path: &Path, core_only: bool) -> Vec { #[test] fn fate_vectors_are_bit_exact_against_ffmpeg() { - let d = dir(); - let ffmpeg = Command::new("ffmpeg").arg("-version").output().is_ok(); - if !d.is_dir() || !ffmpeg { - eprintln!("skipping: FATE samples ({}) or ffmpeg missing", d.display()); - return; - } // (file, ffmpeg -core_only, leading samples ffmpeg trims from .dtshd) let cases = [ ("core_51_24_48_768_0.dtshd", true, 1024), @@ -101,16 +93,17 @@ fn fate_vectors_are_bit_exact_against_ffmpeg() { ]; let mut ran = 0; for (name, core_only, skip) in cases { - let path = d.join(name); - let Ok(raw) = std::fs::read(&path) else { - eprintln!("skipping {name}: not present"); - continue; - }; + let path = ec_testkit::fixture(&format!("open/fate/dts/{name}")); + let raw = std::fs::read(&path).expect("read fixture"); let (ours, ch, rate) = decode_ours(strmdata(&raw)); let reference = decode_ffmpeg(&path, core_only); // ours is front-to-back; ffmpeg puts the back centre of a 6.1 stream // before the side surrounds. - let perm: Vec = if ch == 7 { vec![0, 1, 2, 3, 6, 4, 5] } else { (0..ch).collect() }; + let perm: Vec = if ch == 7 { + vec![0, 1, 2, 3, 6, 4, 5] + } else { + (0..ch).collect() + }; let ours: Vec = ours .chunks_exact(ch) .skip(skip) @@ -119,7 +112,10 @@ fn fate_vectors_are_bit_exact_against_ffmpeg() { assert_eq!(ours.len(), reference.len(), "{name}: sample count"); let bad = ours.iter().zip(&reference).position(|(a, b)| a != b); assert_eq!(bad, None, "{name}: first mismatch at {bad:?}"); - eprintln!("{name}: {ch} ch {rate} Hz {} samples/ch bit-exact", ours.len() / ch); + eprintln!( + "{name}: {ch} ch {rate} Hz {} samples/ch bit-exact", + ours.len() / ch + ); ran += 1; } eprintln!("{ran} FATE vectors compared"); diff --git a/crates/ec-dts/tests/ffmpeg_exact.rs b/crates/ec-dts/tests/ffmpeg_exact.rs index 71c906ec..dc449d35 100644 --- a/crates/ec-dts/tests/ffmpeg_exact.rs +++ b/crates/ec-dts/tests/ffmpeg_exact.rs @@ -6,15 +6,13 @@ //! The fixtures are made with ffmpeg's own DTS encoder (`-c:a dca -strict //! -2`): stereo and mono tones, a mono sweep at 32 kHz, 5.1 tones at 44.1 //! kHz and 5.1 noise with ADPCM at 48 kHz. Each is decoded here and by -//! ffmpeg and every 24-bit sample must be equal. ffmpeg is test tooling and -//! is driven through `std::process`; without it the comparison skips loudly. -//! The fixtures themselves are required: a missing one fails. +//! ffmpeg and every 24-bit sample must be equal. A missing fixture or ffmpeg +//! fails. //! //! The 14-bit and little-endian stream layouts are derived from the same //! fixtures here and must decode to identical samples. use std::path::{Path, PathBuf}; -use std::process::Command; use ec_core::{Decoder, Error}; use ec_dts::{DtsDecoder, Options, StreamFormat}; @@ -35,14 +33,6 @@ fn fixture_names() -> Vec { v } -fn have_ffmpeg() -> bool { - Command::new("ffmpeg") - .arg("-version") - .output() - .map(|o| o.status.success()) - .unwrap_or(false) -} - /// Split a BE16 elementary stream into its core frames. fn frames(data: &[u8]) -> Vec<&[u8]> { let mut out = Vec::new(); @@ -83,7 +73,7 @@ fn decode_ours(frames: &[Vec]) -> (Vec, usize, u32) { } fn decode_ffmpeg(path: &Path) -> Vec { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-nostdin", "-flags", "+bitexact", "-i"]) .arg(path) .args(["-f", "s32le", "-"]) @@ -144,10 +134,6 @@ fn to_layout(frame: &[u8], format: StreamFormat) -> Vec { #[test] fn fixtures_are_bit_exact_against_ffmpeg() { - let ff = have_ffmpeg(); - if !ff { - eprintln!("skip comparison: ffmpeg not on PATH"); - } for name in fixture_names() { let path = fixtures().join(&name); let data = std::fs::read(&path).unwrap(); @@ -157,27 +143,24 @@ fn fixtures_are_bit_exact_against_ffmpeg() { assert!(!ours.is_empty()); let peak = ours.iter().map(|v| v.abs()).max().unwrap(); assert!(peak > 1000, "{name}: decoded silence (peak {peak})"); - if ff { - let reference = decode_ffmpeg(&path); - assert_eq!(ours.len(), reference.len(), "{name}: sample count"); - let bad = ours.iter().zip(&reference).position(|(a, b)| a != b); - assert_eq!( - bad, - None, - "{name}: first mismatch at sample {bad:?} (channel {:?})", - bad.map(|i| i % channels) - ); - eprintln!( - "{name}: {channels} ch, {rate} Hz, {} samples/ch, bit-exact vs ffmpeg", - ours.len() / channels - ); - } + let reference = decode_ffmpeg(&path); + assert_eq!(ours.len(), reference.len(), "{name}: sample count"); + let bad = ours.iter().zip(&reference).position(|(a, b)| a != b); + assert_eq!( + bad, + None, + "{name}: first mismatch at sample {bad:?} (channel {:?})", + bad.map(|i| i % channels) + ); + eprintln!( + "{name}: {channels} ch, {rate} Hz, {} samples/ch, bit-exact vs ffmpeg", + ours.len() / channels + ); } } #[test] fn stream_layouts_decode_identically() { - let ff = have_ffmpeg(); let tmp = std::env::temp_dir().join(format!("ec-dts-layouts-{}", std::process::id())); std::fs::create_dir_all(&tmp).unwrap(); for name in fixture_names() { @@ -191,21 +174,36 @@ fn stream_layouts_decode_identically() { let h1 = ec_dts::parse_frame_header(&conv[0]).unwrap(); assert_eq!(h1.format, fmt, "{name} {fmt:?}"); assert_eq!( - (h0.sample_rate, h0.channels, h0.samples_per_frame, h0.frame_size), - (h1.sample_rate, h1.channels, h1.samples_per_frame, h1.frame_size), + ( + h0.sample_rate, + h0.channels, + h0.samples_per_frame, + h0.frame_size + ), + ( + h1.sample_rate, + h1.channels, + h1.samples_per_frame, + h1.frame_size + ), "{name} {fmt:?}" ); - assert_eq!(conv[0].len(), h1.stream_frame_size, "{name} {fmt:?}: stored size"); + assert_eq!( + conv[0].len(), + h1.stream_frame_size, + "{name} {fmt:?}: stored size" + ); let (got, _, _) = decode_ours(&conv); assert_eq!(got, want, "{name} {fmt:?}: samples differ from BE16"); - if ff { - let p = tmp.join(format!("{name}.{fmt:?}.dts")); - std::fs::write(&p, conv.concat()).unwrap(); - let reference = decode_ffmpeg(&p); - let n = want.len().min(reference.len()); - assert!(n > want.len() / 2, "{name} {fmt:?}: ffmpeg decoded too little"); - assert_eq!(&reference[..n], &want[..n], "{name} {fmt:?}: vs ffmpeg"); - } + let p = tmp.join(format!("{name}.{fmt:?}.dts")); + std::fs::write(&p, conv.concat()).unwrap(); + let reference = decode_ffmpeg(&p); + let n = want.len().min(reference.len()); + assert!( + n > want.len() / 2, + "{name} {fmt:?}: ffmpeg decoded too little" + ); + assert_eq!(&reference[..n], &want[..n], "{name} {fmt:?}: vs ffmpeg"); } } let _ = std::fs::remove_dir_all(&tmp); @@ -233,7 +231,10 @@ fn header_api_states_the_stream() { assert_eq!(&next[..4], &data[..4], "{name}: next frame"); } // Probe behaviour on junk and short input. - assert!(matches!(ec_dts::parse_frame_header(&[0x7F, 0xFE]), Err(Error::NeedMore))); + assert!(matches!( + ec_dts::parse_frame_header(&[0x7F, 0xFE]), + Err(Error::NeedMore) + )); assert!(matches!( ec_dts::parse_frame_header(&[0u8; 32]), Err(Error::Corrupt { .. }) @@ -341,7 +342,10 @@ fn dts_hd_substream_is_parsed_and_the_core_is_output() { dec.decode_frame(&prev).unwrap(); let got = dec.decode_frame(&with).unwrap(); assert_eq!(got.data[0].len(), want.data[0].len()); - assert!(got.data[0] == want.data[0], "HD frame must give the core samples"); + assert!( + got.data[0] == want.data[0], + "HD frame must give the core samples" + ); let i = dec.frame_info().unwrap(); assert!(i.hd_substream && i.xll, "XLL flagged: {i:?}"); @@ -378,7 +382,10 @@ fn damaged_streams_never_panic() { errors += 1; } } - assert!(errors > 0, "corruption should be noticed at least sometimes"); + assert!( + errors > 0, + "corruption should be noticed at least sometimes" + ); // And the decoder still works on a clean frame afterwards. dec.reset(); dec.decode_frame(fr[0]).unwrap(); diff --git a/crates/ec-flac/Cargo.toml b/crates/ec-flac/Cargo.toml index 6486649d..b960c3cd 100644 --- a/crates/ec-flac/Cargo.toml +++ b/crates/ec-flac/Cargo.toml @@ -8,3 +8,6 @@ authors.workspace = true [dependencies] ec-core = { workspace = true } + +[dev-dependencies] +ec-testkit.workspace = true diff --git a/crates/ec-flac/fuzz/seed.sh b/crates/ec-flac/fuzz/seed.sh index 4a75aefc..ab894940 100755 --- a/crates/ec-flac/fuzz/seed.sh +++ b/crates/ec-flac/fuzz/seed.sh @@ -11,8 +11,8 @@ set -euo pipefail FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd) ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd) -FIXTURES="$ROOT/fixtures" -[ -d "$FIXTURES/audio" ] || { echo "seed.sh: $FIXTURES/audio missing; run scripts/link-fixtures.sh" >&2; exit 2; } +FIXTURES=${EC_FIXTURES:-$ROOT/fixtures} +[ -d "$FIXTURES/audio" ] || { echo "seed.sh: $FIXTURES/audio missing; run scripts/fixtures.sh" >&2; exit 2; } XIPH="$FIXTURES/vectors/flac-xiph/flac-test-files-main" [ -d "$XIPH" ] || { echo "seed.sh: $XIPH missing; run scripts/fetch-vectors.sh" >&2; exit 2; } diff --git a/crates/ec-flac/tests/encode_matrix.rs b/crates/ec-flac/tests/encode_matrix.rs index 2ea6875c..80e10173 100644 --- a/crates/ec-flac/tests/encode_matrix.rs +++ b/crates/ec-flac/tests/encode_matrix.rs @@ -9,7 +9,6 @@ //! cargo test -p ec-flac --release --test encode_matrix -- --nocapture use std::path::{Path, PathBuf}; -use std::process::Command; use ec_flac::encode::{EncoderConfig, encode}; @@ -20,34 +19,6 @@ struct Source { bits: u32, } -/// Fixture-presence probe for the encoder matrix corpus. -/// Returns whether the fixture is present, but never silently: under -/// `EC_REQUIRE_FIXTURES=1` an absent fixture is a hard failure naming the path -/// and the script that regenerates it, so a host whose fixture library drifted -/// reports RED instead of a green SKIP (class: gate-skips-on-its-own-failure; -/// model `have_ffmpeg` in crates/ec-av1/src/stream.rs, which was silently -/// short-circuited because the probe ran first in a compound `if`). -/// -/// Order is load-bearing: probe, assert, return. Never merge the probe into -/// the same `if` as the escape. -fn require_fixture(path: &Path, generator: &str) -> bool { - let present = path.exists(); - assert!( - present || std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "EC_REQUIRE_FIXTURES=1 but fixture {} is absent -- regenerate with: {}", - path.display(), - generator - ); - if !present { - eprintln!("SKIP: fixture {} absent", path.display()); - } - present -} - -fn fixtures() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") -} - /// A working directory keyed by test name: these tests are threads of one /// process, so a shared temp directory would have them deleting each other's /// files. @@ -58,7 +29,7 @@ fn workdir(test: &str) -> PathBuf { } fn probe(path: &Path) -> Option { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -71,7 +42,7 @@ fn probe(path: &Path) -> Option { ]) .arg(path) .output() - .ok()?; + .expect("run ffprobe"); // Key=value, because ffprobe prints its own field order, not the requested // one — a positional parse silently swaps rate and channels. let text = String::from_utf8_lossy(&out.stdout); @@ -100,7 +71,7 @@ fn probe(path: &Path) -> Option { fn ffmpeg_pcm(path: &Path, bits: u32) -> Vec { let format = if bits <= 16 { "s16le" } else { "s32le" }; - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args(["-f", format, "-"]) @@ -135,13 +106,13 @@ fn samples_from_pcm(pcm: &[u8], bits: u32) -> Vec { fn ffmpeg_flac_size(src: &Path, out: &Path) -> Option { let _ = std::fs::remove_file(out); - let status = Command::new("ffmpeg") + let status = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-i"]) .arg(src) .args(["-c:a", "flac"]) .arg(out) .status() - .ok()?; + .expect("run ffmpeg"); match status.success() { true => std::fs::metadata(out).ok().map(|m| m.len()), false => None, @@ -149,36 +120,23 @@ fn ffmpeg_flac_size(src: &Path, out: &Path) -> Option { } fn matrix() -> Vec { - let audio = fixtures().join("audio"); - let vectors = fixtures().join("vectors/flac-xiph/flac-test-files-main/subset"); - let mut paths: Vec = Vec::new(); - // Probe first, assert inside the helper, and only then take the empty-list - // branch: under EC_REQUIRE_FIXTURES the assert fires instead of a silent - // skip that leaves every loop below running zero times. - if require_fixture(&audio, "scripts/gen-fixtures.sh") { - let entries = std::fs::read_dir(&audio) - .unwrap_or_else(|e| panic!("read fixture dir {}: {e}", audio.display())); - let mut found: Vec = entries - .filter_map(|e| e.ok().map(|e| e.path())) - .filter(|p| { - let name = p.file_name().unwrap_or_default().to_string_lossy(); - name.starts_with("flac-") || name.starts_with("wav16-") - }) - .collect(); - found.sort(); - paths.append(&mut found); - } + let mut paths: Vec = std::fs::read_dir(ec_testkit::root().join("audio")) + .expect("fixture audio directory") + .map(|e| e.expect("fixture entry").path()) + .filter(|p| { + let name = p.file_name().unwrap_or_default().to_string_lossy(); + name.starts_with("flac-") || name.starts_with("wav16-") + }) + .collect(); + paths.sort(); // Depth coverage the generated fixtures do not have: 24- and 20-bit. - if require_fixture(&vectors, "scripts/fetch-vectors.sh") { - for name in [ - "28 - high resolution audio, default settings.flac", - "37 - 20 bit per sample.flac", - ] { - let p = vectors.join(name); - if p.exists() { - paths.push(p); - } - } + for name in [ + "28 - high resolution audio, default settings.flac", + "37 - 20 bit per sample.flac", + ] { + paths.push(ec_testkit::fixture(&format!( + "vectors/flac-xiph/flac-test-files-main/subset/{name}" + ))); } paths.iter().filter_map(|p| probe(p)).collect() } @@ -186,10 +144,6 @@ fn matrix() -> Vec { #[test] fn encoded_streams_decode_back_bit_exact_through_ffmpeg() { let sources = matrix(); - if sources.is_empty() { - eprintln!("skipped: fixtures not generated"); - return; - } // Non-empty floor: the loop below must run, not zero times. assert!( sources.len() >= 5, @@ -268,13 +222,7 @@ fn encoded_streams_decode_back_bit_exact_through_ffmpeg() { #[test] fn our_streams_survive_a_probe_and_state_their_shape() { - // The 5.1 source this test needs is a named fixture, not a shape we hope the - // matrix happens to contain: probe it first so EC_REQUIRE_FIXTURES fails on - // a drifted library instead of skipping. - let surround = fixtures().join("audio/flac-5.1-44100.flac"); - if !require_fixture(&surround, "scripts/gen-fixtures.sh") { - return; - } + let surround = ec_testkit::fixture("audio/flac-5.1-44100.flac"); let source = matrix() .into_iter() .find(|s| s.channels == 6) @@ -298,7 +246,7 @@ fn our_streams_survive_a_probe_and_state_their_shape() { assert_eq!(probed.rate, source.rate); assert_eq!(probed.bits, source.bits); // `-v error` clean: ffmpeg must find nothing to complain about. - let out_err = Command::new("ffmpeg") + let out_err = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(&out) .args(["-f", "null", "-"]) diff --git a/crates/ec-flac/tests/level_depth_parity.rs b/crates/ec-flac/tests/level_depth_parity.rs index 6d91ed45..4db4a706 100644 --- a/crates/ec-flac/tests/level_depth_parity.rs +++ b/crates/ec-flac/tests/level_depth_parity.rs @@ -26,7 +26,7 @@ use std::path::{Path, PathBuf}; use std::process::Command; use ec_flac::decode::FlacReader; -use ec_flac::encode::{encode, EncoderConfig}; +use ec_flac::encode::{EncoderConfig, encode}; /// Largest accepted ratio of our size to ffmpeg's size at the matching level. const MARGIN: f64 = 1.05; @@ -99,7 +99,7 @@ const CASES: [Case; 4] = [ ]; fn ffmpeg(args: &[&str]) { - let status = Command::new("ffmpeg") + let status = ec_testkit::ffmpeg() .args(["-hide_banner", "-loglevel", "error", "-y"]) .args(args) .status() @@ -108,7 +108,7 @@ fn ffmpeg(args: &[&str]) { } fn ffprobe_stream(path: &Path) -> (u32, u32, u32) { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -226,7 +226,9 @@ fn level_and_depth_parity_with_ffmpeg_flac() { fs::create_dir_all(&dir).expect("create work dir"); println!(); - println!("| case | ec-flac level | ec-flac bytes | ffmpeg -compression_level | ffmpeg bytes | ratio | verdict |"); + println!( + "| case | ec-flac level | ec-flac bytes | ffmpeg -compression_level | ffmpeg bytes | ratio | verdict |" + ); println!("|---|---|---|---|---|---|---|"); let mut failures: Vec = Vec::new(); diff --git a/crates/ec-flac/tests/xiph_vectors.rs b/crates/ec-flac/tests/xiph_vectors.rs index c5886919..b89026a3 100644 --- a/crates/ec-flac/tests/xiph_vectors.rs +++ b/crates/ec-flac/tests/xiph_vectors.rs @@ -5,54 +5,22 @@ //! [`ec_flac::decode::DecodedStream::to_pcm_bytes`] writes) and the two buffers //! must be identical. Lossless codec, no tolerance. //! -//! The corpus is fetched by `scripts/fetch-vectors.sh`; without it every test -//! here skips rather than fails, so a fresh clone still runs green. +//! The corpus is fetched by `scripts/fixtures.sh`; without it every test here +//! fails. //! //! Run the tables: //! cargo test -p ec-flac --release --test xiph_vectors -- --nocapture use std::path::{Path, PathBuf}; -use std::process::Command; use ec_flac::checksum::md5_of_samples; use ec_flac::decode::FlacReader; -fn corpus(kind: &str) -> Option> { - let dir = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../fixtures/vectors/flac-xiph/flac-test-files-main") - .join(kind); - // A missing corpus made every gate below skip GREEN having decoded nothing - // — the "gate skips on its own failure" class. The root `fixtures/` tree is - // gitignored, so `git worktree add` hands every lane worktree a tree without - // it. `EC_REQUIRE_FIXTURES=1` turns that into a hard failure naming the - // exact path and the command that produces it; unset, the skip is kept and - // now says what it skipped. Set it in every batch run. - if !dir.is_dir() { - assert!( - std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "the FLAC xiph {kind} corpus is missing at {} — these gates would prove \ - nothing. A worktree has no gitignored root `fixtures/`: run \ - scripts/link-fixtures.sh, or fetch it with scripts/fetch-vectors.sh.", - dir.display() - ); - eprintln!( - "SKIP the FLAC xiph {kind} corpus is missing at {} — these gates proved \ - nothing; run scripts/link-fixtures.sh, or fetch it with \ - scripts/fetch-vectors.sh (or set EC_REQUIRE_FIXTURES=1 to make this a failure).", - dir.display() - ); - return None; - } - let mut files: Vec = std::fs::read_dir(&dir) - .ok()? - .filter_map(|e| e.ok().map(|e| e.path())) - .filter(|p| p.extension().is_some_and(|e| e == "flac")) - .collect(); - files.sort(); - match files.is_empty() { - true => None, - false => Some(files), - } +fn corpus(kind: &str) -> Vec { + ec_testkit::fixtures( + &format!("vectors/flac-xiph/flac-test-files-main/{kind}"), + "flac", + ) } /// Decode `path` with ffmpeg into the same raw layout our decoder writes. @@ -61,7 +29,7 @@ fn ffmpeg_pcm(path: &Path, bits_per_sample: u32) -> Result, String> { true => "s16le", false => "s32le", }; - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args(["-f", format, "-"]) @@ -82,10 +50,7 @@ fn name(path: &Path) -> String { #[test] fn subset_vectors_decode_bit_exact_against_ffmpeg() { - let Some(files) = corpus("subset") else { - eprintln!("skipped: fixtures/vectors/flac-xiph not fetched"); - return; - }; + let files = corpus("subset"); let mut failures = Vec::new(); let mut passed = 0; for path in &files { @@ -153,10 +118,7 @@ fn subset_vectors_decode_bit_exact_against_ffmpeg() { #[test] fn uncommon_vectors_decode_bit_exact_or_refuse_by_name() { - let Some(files) = corpus("uncommon") else { - eprintln!("skipped: fixtures/vectors/flac-xiph not fetched"); - return; - }; + let files = corpus("uncommon"); let mut failures = Vec::new(); for path in &files { let bytes = std::fs::read(path).expect("read fixture"); @@ -188,10 +150,7 @@ fn uncommon_vectors_decode_bit_exact_or_refuse_by_name() { #[test] fn faulty_vectors_error_and_never_panic() { - let Some(files) = corpus("faulty") else { - eprintln!("skipped: fixtures/vectors/flac-xiph not fetched"); - return; - }; + let files = corpus("faulty"); // Faults our reader is expected to catch outright rather than decode past: // these break the structure a decoder must trust. let must_reject = ["06 - ", "07 - ", "08 - ", "09 - ", "11 - "]; @@ -214,10 +173,7 @@ fn faulty_vectors_error_and_never_panic() { #[test] fn seek_table_positions_the_reader_at_a_frame() { - let Some(files) = corpus("subset") else { - eprintln!("skipped: fixtures/vectors/flac-xiph not fetched"); - return; - }; + let files = corpus("subset"); // "48 - Extremely large SEEKTABLE" is the file with a seek table worth // exercising; any file carrying one proves the hook. let mut checked = 0; diff --git a/crates/ec-mp3/Cargo.toml b/crates/ec-mp3/Cargo.toml index 1a20f801..e82221d4 100644 --- a/crates/ec-mp3/Cargo.toml +++ b/crates/ec-mp3/Cargo.toml @@ -10,3 +10,6 @@ authors.workspace = true ec-core = { workspace = true } ec-dsp = { workspace = true } wide = { workspace = true } + +[dev-dependencies] +ec-testkit.workspace = true diff --git a/crates/ec-mp3/fuzz/seed.sh b/crates/ec-mp3/fuzz/seed.sh index c9125207..7c6ac1e5 100755 --- a/crates/ec-mp3/fuzz/seed.sh +++ b/crates/ec-mp3/fuzz/seed.sh @@ -12,9 +12,10 @@ here=$(cd -- "$(dirname -- "$0")" && pwd) dst="$here/corpus/decode" mkdir -p "$dst" src="sine=frequency=440:duration=1" +FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg} enc() { # enc - ffmpeg -v error -y -f lavfi -i "$src" -c:a "$2" -ar "$4" -ac "$5" -b:a "$6" -f "$7" "$dst/$1.$3" + "$FF" -v error -y -f lavfi -i "$src" -c:a "$2" -ar "$4" -ac "$5" -b:a "$6" -f "$7" "$dst/$1.$3" } enc mp2-mono-32k mp2 mp2 32000 1 64k mp2 diff --git a/crates/ec-mp3/tests/decode_matrix.rs b/crates/ec-mp3/tests/decode_matrix.rs index db0d012a..225d2eb3 100644 --- a/crates/ec-mp3/tests/decode_matrix.rs +++ b/crates/ec-mp3/tests/decode_matrix.rs @@ -9,32 +9,13 @@ //! Run the table: //! cargo test -p ec-mp3 --release --test decode_matrix -- --nocapture -use std::path::{Path, PathBuf}; -use std::process::Command; +use std::path::Path; use std::time::Instant; use ec_mp3::Mp3Reader; -fn fixtures() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") -} - -fn mp3_fixtures() -> Vec { - let dir = fixtures().join("audio"); - let Ok(entries) = std::fs::read_dir(&dir) else { - return Vec::new(); - }; - let mut out: Vec = entries - .flatten() - .map(|e| e.path()) - .filter(|p| p.extension().is_some_and(|e| e == "mp3")) - .collect(); - out.sort(); - out -} - fn ffmpeg_decode(path: &Path) -> Option<(Vec, u32, usize)> { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args(["-f", "f32le", "-"]) @@ -45,10 +26,12 @@ fn ffmpeg_decode(path: &Path) -> Option<(Vec, u32, usize)> { } let samples = out .stdout - .as_chunks::<4>().0.iter() + .as_chunks::<4>() + .0 + .iter() .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) .collect(); - let probe = Command::new("ffprobe") + let probe = ec_testkit::ffprobe() .args([ "-v", "error", @@ -122,11 +105,7 @@ fn best_alignment(got: &[f32], want: &[f32], channels: usize) -> (f64, usize) { #[test] fn decodes_every_fixture_like_ffmpeg() { - let files = mp3_fixtures(); - if files.is_empty() { - eprintln!("no MP3 fixtures: run scripts/gen-fixtures.sh and scripts/gen-mp3-fixtures.sh"); - return; - } + let files = ec_testkit::fixtures("audio", "mp3"); println!( "{:<34} {:>6} {:>3} {:>9} {:>9} {:>8}", "fixture", "rate", "ch", "samples", "corr", "x rt" diff --git a/crates/ec-mp3/tests/encode_matrix.rs b/crates/ec-mp3/tests/encode_matrix.rs index 41c896d1..79388850 100644 --- a/crates/ec-mp3/tests/encode_matrix.rs +++ b/crates/ec-mp3/tests/encode_matrix.rs @@ -9,7 +9,6 @@ //! cargo test -p ec-mp3 --release --test encode_matrix -- --nocapture use std::path::{Path, PathBuf}; -use std::process::Command; use ec_mp3::{FrameHeader, Mp3Encoder, Mp3EncoderConfig}; @@ -41,34 +40,6 @@ fn bar_for(name: &str, kbps: u32) -> f64 { .fold(f64::INFINITY, f64::min) } -fn fixtures() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") -} - -/// Fixture-presence probe for the encoder matrix corpus. -/// Returns whether the fixture is present, but never silently: under -/// `EC_REQUIRE_FIXTURES=1` an absent fixture is a hard failure naming the path -/// and the script that regenerates it, so a host whose fixture library drifted -/// reports RED instead of a green SKIP (class: gate-skips-on-its-own-failure; -/// model `have_ffmpeg` in crates/ec-av1/src/stream.rs, which was silently -/// short-circuited because the probe ran first in a compound `if`). -/// -/// Order is load-bearing: probe, assert, return. Never merge the probe into -/// the same `if` as the escape. -fn require_fixture(path: &Path, generator: &str) -> bool { - let present = path.exists(); - assert!( - present || std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "EC_REQUIRE_FIXTURES=1 but fixture {} is absent -- regenerate with: {}", - path.display(), - generator - ); - if !present { - eprintln!("SKIP: fixture {} absent", path.display()); - } - present -} - fn workdir(test: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("ec-mp3-{}-{test}", std::process::id())); std::fs::create_dir_all(&dir).expect("create work dir"); @@ -76,22 +47,26 @@ fn workdir(test: &str) -> PathBuf { } /// Reads a WAV fixture as interleaved f32 plus its rate and channel count. -fn read_wav(path: &Path) -> Option<(Vec, u32, usize)> { - let out = Command::new("ffmpeg") +fn read_wav(path: &Path) -> (Vec, u32, usize) { + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args(["-f", "f32le", "-"]) .output() - .ok()?; - if !out.status.success() { - return None; - } + .expect("run ffmpeg"); + assert!( + out.status.success(), + "ffmpeg could not read {}", + path.display() + ); let samples = out .stdout - .as_chunks::<4>().0.iter() + .as_chunks::<4>() + .0 + .iter() .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) .collect(); - let probe = Command::new("ffprobe") + let probe = ec_testkit::ffprobe() .args([ "-v", "error", @@ -104,14 +79,18 @@ fn read_wav(path: &Path) -> Option<(Vec, u32, usize)> { ]) .arg(path) .output() - .ok()?; + .expect("run ffprobe"); let text = String::from_utf8_lossy(&probe.stdout); let field = |key: &str| { text.lines() .find_map(|l| l.strip_prefix(key)?.strip_prefix('=')) .and_then(|v| v.trim().parse::().ok()) }; - Some((samples, field("sample_rate")?, field("channels")? as usize)) + ( + samples, + field("sample_rate").expect("sample rate"), + field("channels").expect("channels") as usize, + ) } fn correlation(a: &[f32], b: &[f32]) -> f64 { @@ -151,51 +130,6 @@ fn aligned(got: &[f32], want: &[f32], channels: usize) -> (f64, usize) { best } -/// Worst short-window error energy, relative to the source, over the file. -/// -/// Whole-file correlation cannot see pre-echo: quantisation noise smeared -/// backwards across a 576-sample granule before an attack is a few -/// milliseconds of audible hash inside a minute of otherwise clean signal, and -/// integrating over the minute divides it away. Measured on this crate, going -/// from one short block per 9196 granules to 526 of them moved whole-file -/// correlation by 0.00004 -- in the wrong direction -- while changing exactly -/// the thing short blocks exist to fix. So the sweep also reports the worst -/// window: error energy over source energy, in dB, over 20 ms windows, -/// which is the scale a transient's pre-echo lives on. -fn worst_window_db(got: &[f32], want: &[f32], offset: usize, channels: usize) -> f64 { - let window = 20 * 44100 / 1000 * channels; - let skip = 1152 * channels; - let n = (got.len() - offset).min(want.len()); - let mut worst = f64::MIN; - let mut start = skip; - while start + window + skip <= n { - let (mut err, mut sig) = (0.0f64, 0.0f64); - for i in start..start + window { - let d = f64::from(got[offset + i]) - f64::from(want[i]); - err += d * d; - sig += f64::from(want[i]) * f64::from(want[i]); - } - // A window with no signal in it has no pre-echo to hide, and its - // ratio would be meaningless; the -60 dBFS gate skips digital silence - // and the fade-ins around it. - if sig / window as f64 > 1e-6 { - let db = 10.0 * (err / sig.max(1e-30)).log10(); - if db > worst { - worst = db; - if std::env::var_os("EC_MP3_WORST_WHERE").is_some() { - eprintln!( - " worst so far {db:+.1} dB at {:.2} s, level {:.1} dBFS", - start as f64 / (44100.0 * channels as f64), - 10.0 * (sig / window as f64).log10() - ); - } - } - } - start += window; - } - worst -} - fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec { let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { bitrate_kbps: kbps, @@ -219,11 +153,8 @@ fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec { /// so the gate is the quality those bytes carried. #[test] fn cbr_quality_holds_its_floor() { - let path = fixtures().join("audio/wav16-stereo-48000.wav"); - let Some((pcm, rate, channels)) = read_wav(&path) else { - eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh"); - return; - }; + let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav"); + let (pcm, rate, channels) = read_wav(&path); let bytes = encode(&pcm, rate, channels, 192); let file = workdir("cbr").join("cbr192.mp3"); std::fs::write(&file, &bytes).unwrap(); @@ -243,7 +174,7 @@ fn cbr_quality_holds_its_floor() { } fn decode(file: &Path) -> Vec { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "warning", "-i"]) .arg(file) .args(["-f", "f32le", "-"]) @@ -255,7 +186,9 @@ fn decode(file: &Path) -> Vec { String::from_utf8_lossy(&out.stderr) ); out.stdout - .as_chunks::<4>().0.iter() + .as_chunks::<4>() + .0 + .iter() .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) .collect() } @@ -282,11 +215,8 @@ fn encode_vbr(pcm: &[f32], rate: u32, channels: usize, quality: f32) -> Vec #[test] fn vbr_frames_vary_their_bitrate_index() { let name = "mp3src-stereo-48000"; - let path = fixtures().join(format!("audio/{name}.wav")); - let Some((pcm, rate, channels)) = read_wav(&path) else { - eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh"); - return; - }; + let path = ec_testkit::fixture(&format!("audio/{name}.wav")); + let (pcm, rate, channels) = read_wav(&path); let bytes = encode_vbr(&pcm, rate, channels, 0.5); // Walk the frame headers (MPEG-1, Layer III), skipping the Xing frame. let table = [ @@ -319,7 +249,7 @@ fn vbr_frames_vary_their_bitrate_index() { let work = workdir("vbr"); let file = work.join("vbr.mp3"); std::fs::write(&file, &bytes).unwrap(); - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "warning", "-i"]) .arg(&file) .args(["-f", "f32le", "-"]) @@ -332,14 +262,16 @@ fn vbr_frames_vary_their_bitrate_index() { ); let decoded: Vec = out .stdout - .as_chunks::<4>().0.iter() + .as_chunks::<4>() + .0 + .iter() .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) .collect(); let corr = correlation(&decoded, &pcm); let bar = bar_for(name, 192); println!("vbr corr={corr:.5} bar={bar:.5}"); assert!(corr >= bar, "corr {corr:.5} < bar {bar:.5}"); - let probe = Command::new("ffprobe") + let probe = ec_testkit::ffprobe() .args(["-v", "error", "-show_format"]) .arg(&file) .output() @@ -355,11 +287,8 @@ fn vbr_frames_vary_their_bitrate_index() { #[test] fn vbr_mean_bitrate_tracks_quality_on_music() { - let path = fixtures().join("audio/wav16-stereo-48000.wav"); - let Some((pcm, rate, channels)) = read_wav(&path) else { - eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh"); - return; - }; + let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav"); + let (pcm, rate, channels) = read_wav(&path); let mut previous = 0.0; for q in [0.25f32, 0.5, 0.75] { let bytes = encode_vbr(&pcm, rate, channels, q); @@ -383,38 +312,22 @@ fn vbr_mean_bitrate_tracks_quality_on_music() { #[test] fn encodes_above_the_incumbent_bar() { - let dir = fixtures().join("audio"); - // Probe first, assert inside the helper, and only then take the empty-list - // branch: under EC_REQUIRE_FIXTURES the assert fires instead of a silent - // skip that leaves every row below running zero times. - if !require_fixture(&dir, "scripts/gen-fixtures.sh") { - return; - } - let mut sources: Vec = std::fs::read_dir(&dir) - .unwrap_or_else(|e| panic!("read fixture dir {}: {e}", dir.display())) - .filter_map(|e| e.ok().map(|e| e.path())) + let sources: Vec = ec_testkit::fixtures("audio", "wav") + .into_iter() .filter(|p| { - let name = p.file_name().map(|n| n.to_string_lossy().to_string()); - name.is_some_and(|n| n.starts_with("wav16-") || n.starts_with("mp3src-")) - && p.extension().is_some_and(|e| e == "wav") + let name = p.file_name().unwrap().to_string_lossy().to_string(); + (name.starts_with("wav16-") || name.starts_with("mp3src-")) + && (name.contains("mono") || name.contains("stereo")) }) .collect(); - sources.sort(); - sources.retain(|p| { - let name = p.file_name().unwrap().to_string_lossy().to_string(); - name.contains("mono") || name.contains("stereo") - }); // The corpus is eight committed WAVs (four `mp3src-*`, four `wav16-*`), // all produced by `scripts/gen-fixtures.sh`. Fewer than all eight means // the library drifted, not that the rows passed. assert!( sources.len() >= 8, - "only {} of the 8 mp3 encoder-matrix WAV fixtures are present in {} -- \ - regenerate with: scripts/gen-fixtures.sh", - sources.len(), - dir.display() + "only {} of the 8 mp3 encoder-matrix WAV fixtures are present", + sources.len() ); - let mut decoded_rows = 0usize; let work = workdir("encode"); println!( "{:<30} {:>5} {:>6} {:>3} {:>9} {:>8} {:>9}", @@ -422,10 +335,7 @@ fn encodes_above_the_incumbent_bar() { ); let mut failures = Vec::new(); for source in &sources { - let Some((pcm, rate, channels)) = read_wav(source) else { - continue; - }; - decoded_rows += 1; + let (pcm, rate, channels) = read_wav(source); for kbps in BITRATES { let bar = bar_for(&source.file_name().unwrap().to_string_lossy(), kbps); let bytes = encode(&pcm, rate, channels, kbps); @@ -434,7 +344,7 @@ fn encodes_above_the_incumbent_bar() { source.file_stem().unwrap().to_string_lossy() )); std::fs::write(&path, &bytes).expect("write encoded file"); - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "warning", "-i"]) .arg(&path) .args(["-f", "f32le", "-"]) @@ -446,7 +356,9 @@ fn encodes_above_the_incumbent_bar() { } let decoded: Vec = out .stdout - .as_chunks::<4>().0.iter() + .as_chunks::<4>() + .0 + .iter() .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) .collect(); // With the Info tag's delay and padding honoured, ffmpeg hands @@ -491,200 +403,9 @@ fn encodes_above_the_incumbent_bar() { } } } - // A present-but-unreadable WAV takes the `read_wav` skip above, so the - // corpus count alone would leave this green having measured nothing. - assert!( - decoded_rows == sources.len(), - "only {decoded_rows} of {} fixtures decoded; a present fixture that \ - ffmpeg cannot read is a broken fixture, not a passing row", - sources.len() - ); - assert!(failures.is_empty(), "{failures:#?}"); -} - -// --------------------------------------------------------------------------- -// The live reference: LAME on the user's own library, at matched constant -// bitrate. `encodes_above_the_incumbent_bar` measures against a frozen number -// from the crate this one replaces; that number cannot notice LAME moving, and -// the fixtures it covers are synthetic. This one encodes the same seconds of -// the same file with both encoders at the same bitrate and correlates each -// against the samples that went in. -// --------------------------------------------------------------------------- - -/// Sources for [`real_library_sweep_vs_lame`], the same list the vorbis and -/// opus library gates use. -const LIBRARY: [(&str, &str); 7] = [ - ("nik", "~/Music/reeln.mp4"), - ("reelo", "~/Music/reelo.mp3"), - ("her", "~/Music/reeli.mp3"), - ("reell", "~/Music/reell.mp4"), - ("reelm", "~/Music/reelm.wav"), - ("dl8a", "~/Downloads/8a3b6d1d19.mp3"), - ( - "hein", - "~/Downloads/reelm.mp3", - ), -]; - -/// How much worse than LAME a row's worst 20 ms window may be, in dB. -/// -/// The gap was 12.6 dB when this floor went in, on the two spoken-word -/// sources; mid/side stereo and the demand-weighted frame split closed it. -/// Every row now beats libmp3lame's worst window except hein at 192 kbit/s, -/// which sits 0.2 dB behind, so the floor is one decibel. -const WORST_WINDOW_EXCESS_DB: f64 = 1.0; - -/// How far under LAME a row may sit before the sweep fails, in correlation. -/// -/// The first measurement put every row between -0.00103 and +0.00142. All -/// fourteen are now ahead of libmp3lame, the thinnest being hein at 192 -/// kbit/s at +0.00002, so the floor is zero: a row falling behind the -/// reference at all is the regression. -const LAME_CORR_FLOOR: f64 = 0.0; - -fn expand(path: &str) -> PathBuf { - PathBuf::from(match path.strip_prefix("~/") { - Some(rest) => format!( - "{}/{rest}", - std::env::var("HOME").unwrap_or_else(|_| "/home".into()) - ), - None => path.to_string(), - }) -} - -/// Decodes `seconds` of a source to interleaved stereo f32 at 44.1 kHz. -fn decode_source(path: &Path, seconds: u32) -> Option> { - let out = Command::new("ffmpeg") - .args(["-v", "error", "-i"]) - .arg(path) - .args([ - "-vn", - "-t", - &seconds.to_string(), - "-ac", - "2", - "-ar", - "44100", - "-f", - "f32le", - "-", - ]) - .output() - .ok()?; - if !out.status.success() || out.stdout.is_empty() { - return None; - } - Some( - out.stdout - .as_chunks::<4>().0.iter() - .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) - .collect(), - ) -} - -/// Ours against LAME on the user's library, at matched constant bitrate: -/// -/// cargo test -p ec-mp3 --release --test encode_matrix \ -/// real_library_sweep_vs_lame -- --ignored --nocapture -#[test] -#[ignore = "needs the user's library and ffmpeg's libmp3lame"] -fn real_library_sweep_vs_lame() { - let seconds = 60u32; - let work = workdir("lame-sweep"); - println!( - "{:<7} {:>5} {:>9} {:>9} {:>8} {:>8} {:>8} {:>8} {:>8}", - "source", - "kbps", - "corr_ours", - "corr_lame", - "gap", - "wworst_o", - "wworst_r", - "ours_kb", - "lame_kb" - ); - let mut rows = 0; - let mut failures = Vec::new(); - // `EC_MP3_SWEEP_ONLY=reelo,dl8a` narrows the sweep to named sources, so a - // constant can be swept against the rows it moves without paying for the - // rows it does not. - let only = std::env::var("EC_MP3_SWEEP_ONLY").unwrap_or_default(); - for (name, src) in LIBRARY { - if !only.is_empty() && !only.split(',').any(|w| w.trim() == name) { - continue; - } - let src = expand(src); - if !src.exists() { - println!("{name:<7} SKIP (missing)"); - continue; - } - let Some(pcm) = decode_source(&src, seconds) else { - println!("{name:<7} SKIP (decode)"); - continue; - }; - let secs = pcm.len() as f64 / (44100.0 * 2.0); - for kbps in [128u32, 192] { - let ours_bytes = encode(&pcm, 44100, 2, kbps); - let ours_file = work.join(format!("ours-{name}-{kbps}.mp3")); - std::fs::write(&ours_file, &ours_bytes).expect("write ours"); - let lame_file = work.join(format!("lame-{name}-{kbps}.mp3")); - let status = Command::new("ffmpeg") - .args(["-y", "-v", "error", "-i"]) - .arg(&src) - .args([ - "-vn", - "-t", - &seconds.to_string(), - "-ac", - "2", - "-ar", - "44100", - "-c:a", - "libmp3lame", - "-b:a", - &format!("{kbps}k"), - ]) - .arg(&lame_file) - .status() - .expect("ffmpeg runs"); - assert!(status.success(), "libmp3lame encode of {name} at {kbps}k"); - // Both decoded by the same decoder and aligned the same way: an - // encoder delay is not a quality difference. - let measure = |file: &Path| -> (f64, f64) { - let decoded = decode(file); - let (corr, offset) = aligned(&decoded, &pcm, 2); - (corr, worst_window_db(&decoded, &pcm, offset, 2)) - }; - let ((ours_corr, ours_worst), (lame_corr, lame_worst)) = - (measure(&ours_file), measure(&lame_file)); - let kb = - |p: &Path| std::fs::metadata(p).expect("size").len() as f64 * 8.0 / secs / 1000.0; - let gap = ours_corr - lame_corr; - println!( - "{name:<7} {kbps:>5} {ours_corr:>9.5} {lame_corr:>9.5} {gap:>+8.5} \ - {ours_worst:>+8.1} {lame_worst:>+8.1} {:>8.1} {:>8.1}", - kb(&ours_file), - kb(&lame_file) - ); - rows += 1; - if gap < LAME_CORR_FLOOR { - failures.push(format!( - "{name} at {kbps} kbit/s: {ours_corr:.5} against LAME's {lame_corr:.5}" - )); - } - if ours_worst - lame_worst > WORST_WINDOW_EXCESS_DB { - failures.push(format!( - "{name} at {kbps} kbit/s: worst window {ours_worst:.1} dB \ - against LAME's {lame_worst:.1} dB" - )); - } - } - } - assert!(rows > 0, "no library sources were readable"); assert!(failures.is_empty(), "{failures:#?}"); } -/// The `mode_extension` of every frame of a stream, in order. fn mode_exts(bytes: &[u8]) -> Vec { let mut out = Vec::new(); let mut at = 0; @@ -745,153 +466,3 @@ fn mid_side_follows_the_channel_correlation() { } } } - -/// libmp3lame's VBR levels, encoded once per source so the level that -/// actually spent what we spent can be picked by measurement. Nominal rates -/// are no guide: on speech, V6 lands near 60 kbit/s rather than its nominal -/// 115, because libmp3lame drops the rate hard on easy material. -const LAME_V_LEVELS: [u32; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - -/// How far under libmp3lame a VBR row may sit in correlation when it spent at -/// least as many bits. Thirteen of the fourteen rows are ahead; the floor is -/// set by her at quality 0.3, which is 0.00042 behind while spending 1.5% -/// less. -const VBR_CORR_FLOOR: f64 = -0.0005; - -/// How far behind libmp3lame's worst 20 ms window a VBR row may sit. Set by -/// nik and reelo at quality 0.3, both 2.8 dB behind: the frames our VBR calls -/// easy are where it still under-spends against a transient. -const VBR_WORST_EXCESS_DB: f64 = 3.5; - -/// How much of libmp3lame's rate ours may spend at a matched quality. Rows -/// where libmp3lame is already on its top rung (V0) are exempt: it cannot -/// spend more there, so a premium measures its ceiling and not our appetite. -const VBR_RATE_CEILING: f64 = 8.0; - -/// Our VBR against libmp3lame's, on the user's own library, at a matched rate. -/// -/// CBR has had a reference gate since `real_library_sweep_vs_lame`; VBR has -/// had none, which is why the demand-weighted frame split landed in the CBR -/// arm only -- VBR's bitrate choice is calibrated to the noise-to-mask ratio -/// the even split produces, and nothing could tell whether moving both was a -/// gain or a loss. -#[test] -#[ignore = "needs the user's library and ffmpeg's libmp3lame"] -fn real_library_vbr_vs_lame() { - let seconds = 60u32; - let work = workdir("lame-vbr"); - println!( - "{:<7} {:>4} {:>9} {:>9} {:>8} {:>8} {:>8} {:>8} {:>8} {:>4}", - "source", - "q", - "corr_ours", - "corr_lame", - "gap", - "wworst_o", - "wworst_r", - "ours_kb", - "lame_kb", - "V" - ); - let only = std::env::var("EC_MP3_SWEEP_ONLY").unwrap_or_default(); - let mut rows = 0; - let mut failures = Vec::new(); - for (name, src) in LIBRARY { - if !only.is_empty() && !only.split(',').any(|w| w.trim() == name) { - continue; - } - let src = expand(src); - if !src.exists() { - println!("{name:<7} SKIP (missing)"); - continue; - } - let Some(pcm) = decode_source(&src, seconds) else { - println!("{name:<7} SKIP (decode)"); - continue; - }; - let secs = pcm.len() as f64 / (44100.0 * 2.0); - let kb = |p: &Path| std::fs::metadata(p).expect("size").len() as f64 * 8.0 / secs / 1000.0; - // Every rung of libmp3lame's VBR ladder, measured on this source. - let lame_ladder: Vec<(u32, PathBuf, f64)> = LAME_V_LEVELS - .iter() - .map(|&level| { - let file = work.join(format!("lame-{name}-v{level}.mp3")); - let status = Command::new("ffmpeg") - .args(["-y", "-v", "error", "-i"]) - .arg(&src) - .args([ - "-vn", - "-t", - &seconds.to_string(), - "-ac", - "2", - "-ar", - "44100", - "-c:a", - "libmp3lame", - "-q:a", - &level.to_string(), - ]) - .arg(&file) - .status() - .expect("ffmpeg runs"); - assert!(status.success(), "libmp3lame V{level} of {name}"); - let rate = kb(&file); - (level, file, rate) - }) - .collect(); - for quality in [0.3f32, 0.6] { - let ours_bytes = encode_vbr(&pcm, 44100, 2, quality); - let ours_file = work.join(format!("ours-{name}-{quality}.mp3")); - std::fs::write(&ours_file, &ours_bytes).expect("write ours"); - let ours_kb = kb(&ours_file); - // The level that actually spent what we spent. - let (level, lame_file) = lame_ladder - .iter() - .min_by(|a, b| { - (a.2 - ours_kb) - .abs() - .partial_cmp(&(b.2 - ours_kb).abs()) - .expect("finite") - }) - .map(|(v, f, _)| (*v, f.clone())) - .expect("a ladder rung"); - let measure = |file: &Path| -> (f64, f64) { - let decoded = decode(file); - let (corr, offset) = aligned(&decoded, &pcm, 2); - (corr, worst_window_db(&decoded, &pcm, offset, 2)) - }; - let ((ours_corr, ours_worst), (lame_corr, lame_worst)) = - (measure(&ours_file), measure(&lame_file)); - let lame_kb = kb(&lame_file); - let gap = ours_corr - lame_corr; - let premium = (ours_kb / lame_kb - 1.0) * 100.0; - println!( - "{name:<7} {quality:>4} {ours_corr:>9.5} {lame_corr:>9.5} {gap:>+8.5} \ - {ours_worst:>+8.1} {lame_worst:>+8.1} {ours_kb:>8.1} {lame_kb:>8.1} {level:>4}" - ); - rows += 1; - // Being behind on quality is only a failure if we did not also - // spend less to get there; spending more is a failure on its own. - if gap < VBR_CORR_FLOOR && ours_kb >= lame_kb * 0.98 { - failures.push(format!( - "{name} at q{quality}: {ours_corr:.5} against LAME's {lame_corr:.5} \ - at {ours_kb:.1} against {lame_kb:.1} kbit/s" - )); - } - if ours_worst - lame_worst > VBR_WORST_EXCESS_DB { - failures.push(format!( - "{name} at q{quality}: worst window {ours_worst:.1} dB \ - against LAME's {lame_worst:.1} dB" - )); - } - if level > 0 && premium > VBR_RATE_CEILING { - failures.push(format!( - "{name} at q{quality}: {premium:+.1}% of LAME's rate (V{level})" - )); - } - } - } - assert!(rows > 0, "no library sources were readable"); - assert!(failures.is_empty(), "{failures:#?}"); -} diff --git a/crates/ec-mp3/tests/mp2_matrix.rs b/crates/ec-mp3/tests/mp2_matrix.rs index a35bd9f5..a31aa0c5 100644 --- a/crates/ec-mp3/tests/mp2_matrix.rs +++ b/crates/ec-mp3/tests/mp2_matrix.rs @@ -6,34 +6,14 @@ //! mode, the joint-stereo bound, CRC-protected frames and Layer I -- things no //! encoder here produces. The oracle is `ffmpeg -c:a mp2 -i x.mp2 -f f32le`. //! -//! ffmpeg is needed; absent, the tests skip (fail under `EC_REQUIRE_FIXTURES=1`). +//! ffmpeg is needed. //! //! cargo test -p ec-mp3 --release --test mp2_matrix -- --nocapture use std::path::PathBuf; -use std::process::Command; use ec_mp3::{FrameHeader, Mp3Reader}; -fn required() -> bool { - std::env::var_os("EC_REQUIRE_FIXTURES").is_some_and(|v| !v.is_empty() && v != "0") -} - -fn have_ffmpeg() -> bool { - let ok = Command::new("ffmpeg") - .arg("-version") - .output() - .is_ok_and(|o| o.status.success()); - if !ok { - assert!( - !required(), - "EC_REQUIRE_FIXTURES is set but ffmpeg is missing" - ); - eprintln!("skip: ffmpeg not available"); - } - ok -} - fn work_dir() -> PathBuf { let d = std::env::temp_dir().join("ec-mp2-matrix"); std::fs::create_dir_all(&d).unwrap(); @@ -42,7 +22,7 @@ fn work_dir() -> PathBuf { fn ffmpeg_decode(path: &std::path::Path, channels: usize, layer: u8) -> Vec { let decoder = if layer == 1 { "mp1float" } else { "mp2float" }; - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-c:a", decoder, "-i"]) .arg(path) .args(["-ac", &channels.to_string(), "-f", "f32le", "-"]) @@ -64,7 +44,7 @@ fn ffmpeg_decode(path: &std::path::Path, channels: usize, layer: u8) -> Vec /// ffmpeg's fixed-point decoder (the default `mp2`/`mp1`): s16 out. fn ffmpeg_decode_s16(path: &std::path::Path, channels: usize, layer: u8) -> Vec { let decoder = if layer == 1 { "mp1" } else { "mp2" }; - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-c:a", decoder, "-i"]) .arg(path) .args(["-ac", &channels.to_string(), "-f", "s16le", "-"]) @@ -133,9 +113,6 @@ impl Rng { #[test] fn encoder_streams_match_ffmpeg() { - if !have_ffmpeg() { - return; - } let dir = work_dir(); let sources = [ "sine=frequency=1000:sample_rate={R}:duration=1.5", @@ -161,7 +138,7 @@ fn encoder_streams_match_ffmpeg() { for (n, &(codec, rate, ch, br)) in cases.iter().enumerate() { let src = sources[n % sources.len()].replace("{R}", &rate.to_string()); let path = dir.join(format!("enc-{n}.mp2")); - let st = Command::new("ffmpeg") + let st = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-f", "lavfi", "-i", &src, "-ac"]) .arg(ch.to_string()) .args(["-c:a", codec, "-b:a", br]) @@ -453,9 +430,6 @@ fn compare_stream(name: &str, frames: &[Vec], tolerance: f32) -> f32 { #[test] fn random_frames_match_ffmpeg() { - if !have_ffmpeg() { - return; - } let mut rng = Rng(0x9E37_79B9_7F4A_7C15); let mut worst = 0.0f32; let mut streams = 0; @@ -494,7 +468,7 @@ fn random_frames_match_ffmpeg() { } fn have_encoder(name: &str) -> bool { - Command::new("ffmpeg") + ec_testkit::ffmpeg() .args(["-hide_banner", "-encoders"]) .output() .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(name)) @@ -504,13 +478,7 @@ fn have_encoder(name: &str) -> bool { /// intensity bound, dual channel, and CRC-protected frames. #[test] fn twolame_streams_match_ffmpeg() { - if !have_ffmpeg() { - return; - } - if !have_encoder("libtwolame") { - eprintln!("skip: ffmpeg has no libtwolame"); - return; - } + assert!(have_encoder("libtwolame"), "ffmpeg has no libtwolame"); let dir = work_dir(); let cases: &[(&str, u32, &str, u32, bool)] = &[ ("joint_stereo", 44100, "64k", 2, false), @@ -531,7 +499,7 @@ fn twolame_streams_match_ffmpeg() { let src = format!( "aevalsrc=0.4*sin(2*PI*(300+1500*t)*t)|0.3*sin(2*PI*700*t)+0.05*random(1):s={rate}:d=2" ); - let st = Command::new("ffmpeg") + let st = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-f", "lavfi", "-i", &src, "-ac"]) .arg(ch.to_string()) .args(["-c:a", "libtwolame", "-mode", mode, "-b:a", br]) diff --git a/crates/ec-opus/Cargo.toml b/crates/ec-opus/Cargo.toml index 69b01431..5c672854 100644 --- a/crates/ec-opus/Cargo.toml +++ b/crates/ec-opus/Cargo.toml @@ -16,6 +16,7 @@ wide.workspace = true rustfft = { version = "6", optional = true, default-features = false } [dev-dependencies] +ec-testkit.workspace = true ec-dsp.workspace = true ec-ogg.workspace = true cpu-time = "1.0.0" diff --git a/crates/ec-opus/fuzz/seed.sh b/crates/ec-opus/fuzz/seed.sh index 80b1b30d..20c2d6db 100755 --- a/crates/ec-opus/fuzz/seed.sh +++ b/crates/ec-opus/fuzz/seed.sh @@ -13,9 +13,10 @@ set -euo pipefail FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd) ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd) -VECTORS="$ROOT/fixtures/vectors/opus-rfc6716/opus_testvectors" -AUDIO="$ROOT/fixtures/audio" -[ -d "$VECTORS" ] || { echo "seed.sh: $VECTORS missing; run scripts/link-fixtures.sh" >&2; exit 2; } +FIX=${EC_FIXTURES:-$ROOT/fixtures} +VECTORS="$FIX/vectors/opus-rfc6716/opus_testvectors" +AUDIO="$FIX/audio" +[ -d "$VECTORS" ] || { echo "seed.sh: $VECTORS missing; run scripts/fixtures.sh" >&2; exit 2; } PKT_DIR="$FUZZ_DIR/corpus/decode_packet" TOC_DIR="$FUZZ_DIR/corpus/parse_toc" diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index de6e2be7..ef587a17 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -94,8 +94,7 @@ fn read_vector(path: &Path) -> Vec { } fn vectors_dir() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../fixtures/vectors/opus-rfc6716/opus_testvectors") + ec_testkit::root().join("vectors/opus-rfc6716/opus_testvectors") } /// Decodes a vector at 48 kHz stereo, returning the samples and how many @@ -421,27 +420,14 @@ fn read_i16(path: &Path) -> Vec { /// of RFC 8251 Section 10) and `testvectorNNm.dec` (without it). An /// implementation is compliant when it matches either set. fn vectors_dir_8251() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../fixtures/vectors/opus-rfc8251/opus_newvectors") + ec_testkit::root().join("vectors/opus-rfc8251/opus_newvectors") } /// Runs one RFC 8251 vector (stereo) against one of its reference files. Returns /// `(range-exact, decoded packets, quality %)`; the caller decides what passes. fn run_rfc8251(name: &str, reference: &str) -> (usize, usize, f64) { let dir = vectors_dir_8251(); - let bit = dir.join(format!("{name}.bit")); - if !bit.exists() { - assert!( - std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "RFC 8251 test vector {name} missing at {} — run scripts/fetch-vectors.sh opus-rfc8251", - bit.display() - ); - eprintln!( - "SKIP RFC 8251 test vector {name} missing at {}", - bit.display() - ); - return (0, 0, f64::NAN); - } + let bit = ec_testkit::fixture(&format!("vectors/opus-rfc8251/opus_newvectors/{name}.bit")); let packets = read_vector(&bit); let (pcm, matched, decoded) = decode_vector_ch(&packets, 2, false); let refs = read_i16(&dir.join(reference)); @@ -506,33 +492,10 @@ const VECTORS: [&str; 12] = [ #[test] fn rfc6716_test_vectors() { let _timing = timing_shared(); - // A missing test vector made this gate skip GREEN having decoded nothing — - // the "gate skips on its own failure" class. The root `fixtures/` tree is - // gitignored, so `git worktree add` hands every lane worktree a tree without - // it. `EC_REQUIRE_FIXTURES=1` turns a missing vector into a hard failure - // naming the exact path and the command that produces it; unset, the skip - // is kept and now says what it skipped. Set it in every batch run. - let base = vectors_dir(); let mut table = Vec::new(); for name in VECTORS { - let path = base.join(format!("{name}.bit")); - if !path.exists() { - assert!( - std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "RFC 6716 test vector {name} missing at {} — this gate would prove \ - nothing. A worktree has no gitignored root `fixtures/`: run \ - scripts/link-fixtures.sh, or fetch it with scripts/fetch-vectors.sh.", - path.display() - ); - eprintln!( - "SKIP RFC 6716 test vector {name} missing at {} — this gate proved \ - nothing; run scripts/link-fixtures.sh, or fetch it with \ - scripts/fetch-vectors.sh (or set EC_REQUIRE_FIXTURES=1 to make this \ - a failure).", - path.display() - ); - continue; - } + let path = + ec_testkit::fixture(&format!("vectors/opus-rfc6716/opus_testvectors/{name}.bit")); let packets = read_vector(&path); let (pcm, matched, decoded) = decode_vector(&packets); let reference = read_i16(&vectors_dir().join(format!("{name}.dec"))); @@ -631,9 +594,7 @@ fn parse_opus_head(p: &[u8]) -> OpusHead { } fn fixture(name: &str) -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../fixtures/audio") - .join(name) + ec_testkit::fixture(&format!("audio/{name}")) } /// ffmpeg's decode of the same file, interleaved `f32` in ffmpeg's channel @@ -643,8 +604,8 @@ fn fixture(name: &str) -> PathBuf { /// own native Opus decoder is a third implementation and deviates from libopus /// by as much as 0.97 correlation on this very fixture's coupled surround /// streams, so it makes a poor oracle. -fn ffmpeg_decode(path: &Path, channels: usize) -> Option> { - let out = Command::new("ffmpeg") +fn ffmpeg_decode(path: &Path, channels: usize) -> Vec { + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-c:a", "libopus", "-i"]) .arg(path) .args([ @@ -657,18 +618,18 @@ fn ffmpeg_decode(path: &Path, channels: usize) -> Option> { "-", ]) .output() - .ok()?; - if !out.status.success() { - return None; - } - Some( - out.stdout - .as_chunks::<4>() - .0 - .iter() - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect(), - ) + .expect("run ffmpeg"); + assert!( + out.status.success(), + "ffmpeg could not decode {}", + path.display() + ); + out.stdout + .as_chunks::<4>() + .0 + .iter() + .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) + .collect() } /// Decodes an Ogg-Opus file with the multistream decoder, pre-skip removed. @@ -729,14 +690,7 @@ fn ogg_opus_fixtures_match_ffmpeg() { ("opus-ogg-5.1-48000.opus", 6), ] { let path = fixture(name); - if !path.exists() { - eprintln!("{name}: missing, skipped (run scripts/gen-fixtures.sh)"); - continue; - } - let Some(reference) = ffmpeg_decode(&path, channels) else { - eprintln!("{name}: ffmpeg unavailable, skipped"); - continue; - }; + let reference = ffmpeg_decode(&path, channels); let (mine, ch) = decode_ogg(&path); assert_eq!(ch, channels, "{name}: channel count"); let mut worst = 1.0f64; @@ -772,14 +726,7 @@ fn five_one_channels_land_in_the_right_places() { const VORBIS_TO_FFMPEG_5_1: [usize; 6] = [0, 2, 1, 4, 5, 3]; const TONES: [f64; 6] = [220.0, 440.0, 660.0, 55.0, 880.0, 1320.0]; let path = fixture("opus-ogg-5.1-48000.opus"); - if !path.exists() { - eprintln!("5.1 fixture missing, skipped"); - return; - } - let Some(reference) = ffmpeg_decode(&path, 6) else { - eprintln!("ffmpeg unavailable, skipped"); - return; - }; + let reference = ffmpeg_decode(&path, 6); let (pcm, channels) = decode_ogg(&path); assert_eq!(channels, 6); let dominant = |x: &[f32], ch: usize| -> usize { @@ -864,9 +811,6 @@ fn decode_speed() { ("opus-ogg-5.1-48000.opus", 6), ] { let path = fixture(name); - if !path.exists() { - continue; - } let data = fs::read(&path).unwrap(); let packets = ogg_packets(&data); let head = parse_opus_head(&packets[0]); @@ -902,68 +846,20 @@ fn decode_speed() { // The fixtures are sine tones, which are cheap; testvector01 is real music // at a high rate and is the honest stereo number. - let path = vectors_dir().join("testvector01.bit"); - if path.exists() { - let packets = read_vector(&path); - let mut out = vec![0.0f32; 5760 * 2]; - let mut samples = 0usize; - let elapsed = best_of_3(|| { - let mut dec = Decoder::new(48000, 2).unwrap(); - samples = 0; - for p in &packets { - samples += dec.decode_float(&p.payload, &mut out).unwrap(); - } - }); - let realtime = samples as f64 / 48000.0 / elapsed; - println!("testvector01 (stereo music): {realtime:.0}x realtime"); - assert!(realtime >= 135.0, "stereo music decodes at {realtime:.0}x"); - } -} - -#[test] -#[ignore = "probe: report harness with no asserts; unblocks by setting EC_OPUS_FILES to committed .opus fixtures -- unset, it decodes nothing"] -fn real_library_sweep() { - let _timing = timing_shared(); - // Files named on the command line (EC_OPUS_FILES=a.opus:b.opus), decoded - // and compared against libopus channel by channel, with the decode speed. - let files = std::env::var("EC_OPUS_FILES").unwrap_or_default(); - for f in files.split(':').filter(|s| !s.is_empty()) { - let path = PathBuf::from(f); - let (pcm, channels) = decode_ogg(&path); - let reference = ffmpeg_decode(&path, channels).expect("libopus"); - let n = (reference.len() / channels).min(pcm.len() / channels); - let mut worst = 1.0f64; - for c in 0..channels { - let a: Vec = (0..n).map(|i| pcm[i * channels + c]).collect(); - let b: Vec = (0..n).map(|i| reference[i * channels + c]).collect(); - let corr = correlation(&a, &b); - worst = worst.min(corr); - println!("{f}: channel {c} correlation {corr:.5}"); - } - // Speed on the same file. - let data = fs::read(&path).unwrap(); - let packets = ogg_packets(&data); - let head = parse_opus_head(&packets[0]); - let audio: Vec<&Vec> = packets.iter().skip(2).filter(|p| !p.is_empty()).collect(); - let mut dec = - MultistreamDecoder::with_rate(48000, head.streams, head.coupled, &head.mapping); - let mut out = vec![0.0f32; 5760 * channels]; - let mut samples = 0usize; - for p in &audio { - samples += dec.decode_float(p, &mut out).unwrap(); - } - dec.reset(); - let start = std::time::Instant::now(); - for p in &audio { - dec.decode_float(p, &mut out).unwrap(); + let path = ec_testkit::fixture("vectors/opus-rfc6716/opus_testvectors/testvector01.bit"); + let packets = read_vector(&path); + let mut out = vec![0.0f32; 5760 * 2]; + let mut samples = 0usize; + let elapsed = best_of_3(|| { + let mut dec = Decoder::new(48000, 2).unwrap(); + samples = 0; + for p in &packets { + samples += dec.decode_float(&p.payload, &mut out).unwrap(); } - let elapsed = start.elapsed().as_secs_f64(); - println!( - "{f}: {channels} ch, {:.1} s audio, {:.0}x realtime, worst channel {worst:.5}", - samples as f64 / 48000.0, - samples as f64 / 48000.0 / elapsed - ); - } + }); + let realtime = samples as f64 / 48000.0 / elapsed; + println!("testvector01 (stereo music): {realtime:.0}x realtime"); + assert!(realtime >= 135.0, "stereo music decodes at {realtime:.0}x"); } // --------------------------------------------------------------------------- @@ -1583,14 +1479,7 @@ fn encode_packets(enc: &mut Encoder, pcm: &[f32], channels: usize) -> Vec PathBuf { - let root = std::env::var_os("EC_OPUS_SCRATCH") - .map(PathBuf::from) - .unwrap_or_else(|| { - let home = std::env::var_os("HOME").expect("HOME set for encoder scratch"); - PathBuf::from(home).join(".cache/silk2") - }); - fs::create_dir_all(&root).unwrap(); - root.join(format!("ec-opus-enc-{}-{name}", std::process::id())) + std::env::temp_dir().join(format!("ec-opus-enc-{}-{name}", std::process::id())) } /// The full product rate table, mono and stereo, decoded by libopus: the @@ -1617,11 +1506,7 @@ fn oracle_decodes_our_packets_across_the_rate_table() { total, enc.look_ahead(960) as i64, ); - let Some(reference) = ffmpeg_decode(&path, channels) else { - eprintln!("ffmpeg unavailable, skipped"); - let _ = fs::remove_file(&path); - return; - }; + let reference = ffmpeg_decode(&path, channels); let _ = fs::remove_file(&path); let n = (reference.len() / channels).min(total); assert!( @@ -1691,11 +1576,7 @@ fn oracle_decodes_our_packets_across_the_rate_table() { total, pre_skip as i64, ); - let Some(reference) = ffmpeg_decode(&path, 1) else { - eprintln!("ffmpeg unavailable, skipped"); - let _ = fs::remove_file(&path); - return; - }; + let reference = ffmpeg_decode(&path, 1); let _ = fs::remove_file(&path); let mut dec = Decoder::new(48000, 1).unwrap(); let mut buf = vec![0f32; 5760]; @@ -1748,11 +1629,7 @@ fn five_one_encode_end_to_end() { let head = opus_head(6, pre_skip as u16, Some((streams, coupled, mapping))); let path = temp_path("5.1.opus"); write_ogg_opus(&path, &packets, head, 6, total, pre_skip as i64); - let Some(reference) = ffmpeg_decode(&path, 6) else { - eprintln!("ffmpeg unavailable, skipped"); - let _ = fs::remove_file(&path); - return; - }; + let reference = ffmpeg_decode(&path, 6); let _ = fs::remove_file(&path); let n = (reference.len() / 6).min(total); assert!(n >= total - 960, "libopus returned {n} of {total} samples"); @@ -1789,7 +1666,7 @@ fn ogg_opus_round_trip_duration_is_exact() { total, pre_skip as i64, ); - let probe = Command::new("ffprobe") + let probe = ec_testkit::ffprobe() .args([ "-v", "error", @@ -1820,69 +1697,14 @@ fn ogg_opus_round_trip_duration_is_exact() { "ffprobe reports {dur} s, expected {expected} s (2.000 s + pre-skip)" ); } - if let Some(decoded) = ffmpeg_decode(&path, 2) { - assert_eq!( - decoded.len() / 2, - total, - "libopus decoded {} samples of {total}", - decoded.len() / 2 - ); - } - let _ = fs::remove_file(&path); -} - -/// Cross-check against the reference `opus_demo` decoder (RFC 6716 -/// Appendix A) over its own `.bit` format, when the binary is available: -/// `EC_OPUS_DEMO=/path/to/opus_demo cargo test`. -#[test] -fn opus_demo_decodes_our_bit_stream() { - let _timing = timing_shared(); - let Ok(demo) = std::env::var("EC_OPUS_DEMO") else { - eprintln!("EC_OPUS_DEMO unset, skipped"); - return; - }; - let pcm = test_signal(2, 2.0); - let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); - enc.set_bitrate(256_000); - let mut out = vec![0u8; 1500]; - let mut bit = Vec::new(); - for block in pcm.as_chunks::<{ 960 * 2 }>().0 { - let len = enc.encode_float(block, 960, &mut out).expect("encode"); - bit.extend_from_slice(&(len as u32).to_be_bytes()); - bit.extend_from_slice(&enc.final_range().to_be_bytes()); - bit.extend_from_slice(&out[..len]); - } - let bit_path = temp_path("demo.bit"); - let pcm_path = temp_path("demo.pcm"); - fs::write(&bit_path, &bit).unwrap(); - let status = Command::new(&demo) - .arg("-d") - .arg("48000") - .arg("2") - .arg(&bit_path) - .arg(&pcm_path) - .status() - .expect("run opus_demo"); - assert!(status.success(), "opus_demo refused our stream"); - let decoded = read_i16(&pcm_path); - let _ = fs::remove_file(&bit_path); - let _ = fs::remove_file(&pcm_path); - // opus_demo does not apply pre-skip; compensate for the 120-sample delay. - let delay = 120usize; - let n = (decoded.len() / 2 - delay).min(pcm.len() / 2 - delay); - let mut worst = 1.0f64; - for c in 0..2 { - let a: Vec = (0..n).map(|i| pcm[i * 2 + c]).collect(); - let b: Vec = (0..n) - .map(|i| decoded[(i + delay) * 2 + c] as f32 / 32768.0) - .collect(); - worst = worst.min(correlation(&a, &b)); - } - println!("opus_demo 256 kbps stereo: worst corr {worst:.4}"); - assert!( - worst >= 0.9, - "reference decoder heard correlation {worst:.4}" + let decoded = ffmpeg_decode(&path, 2); + assert_eq!( + decoded.len() / 2, + total, + "libopus decoded {} samples of {total}", + decoded.len() / 2 ); + let _ = fs::remove_file(&path); } /// The steady-state encode loop allocates nothing: every buffer — MDCT @@ -2047,12 +1869,10 @@ fn garbage_payloads_never_panic() { } } // Truncations of a real packet, which exercise the mid-frame paths. - let path = vectors_dir().join("testvector10.bit"); - if path.exists() { - for p in read_vector(&path).iter().take(200) { - for cut in 1..p.payload.len().min(64) { - let _ = dec.decode_float(&p.payload[..cut], &mut out); - } + let path = ec_testkit::fixture("vectors/opus-rfc6716/opus_testvectors/testvector10.bit"); + for p in read_vector(&path).iter().take(200) { + for cut in 1..p.payload.len().min(64) { + let _ = dec.decode_float(&p.payload[..cut], &mut out); } } } @@ -2205,10 +2025,8 @@ fn silk_mono_nb_wb_roundtrip() { let _timing = timing_shared(); let wav = fixture("wav16-mono-48000.wav"); let mut sources = vec![("synthetic", speech_like())]; - if wav.exists() { - let w = read_wav_mono(&wav); - sources.push(("wav16-mono-48000", w[..w.len().min(96000)].to_vec())); - } + let w = read_wav_mono(&wav); + sources.push(("wav16-mono-48000", w[..w.len().min(96000)].to_vec())); for (name, pcm) in &sources { for wideband in [false, true] { let (bandwidth, band, tag) = if wideband { @@ -2229,22 +2047,20 @@ fn silk_mono_nb_wb_roundtrip() { assert!(corr >= 0.8, "{name} {tag}: corr {corr:.4}"); // Reference oracle: the packets in an Ogg-Opus file decode cleanly. - if Command::new("ffmpeg").arg("-version").output().is_ok() { - let path = temp_path(&format!("silk-{name}-{tag}.opus")); - write_ogg_opus(&path, &packets, opus_head(1, 120, None), 1, pcm.len(), 120); - let out = Command::new("ffmpeg") - .args(["-v", "warning", "-c:a", "libopus", "-i"]) - .arg(&path) - .args(["-f", "null", "-"]) - .output() - .unwrap(); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!( - out.status.success() && stderr.trim().is_empty(), - "{name} {tag}: ffmpeg: {stderr}" - ); - let _ = fs::remove_file(&path); - } + let path = temp_path(&format!("silk-{name}-{tag}.opus")); + write_ogg_opus(&path, &packets, opus_head(1, 120, None), 1, pcm.len(), 120); + let out = ec_testkit::ffmpeg() + .args(["-v", "warning", "-c:a", "libopus", "-i"]) + .arg(&path) + .args(["-f", "null", "-"]) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + out.status.success() && stderr.trim().is_empty(), + "{name} {tag}: ffmpeg: {stderr}" + ); + let _ = fs::remove_file(&path); } } } @@ -2279,10 +2095,9 @@ fn silk_mediumband_and_10ms_roundtrip() { packets.len() ); assert!(corr >= floor, "{tag}: corr {corr:.4}"); - if let Some(oracle) = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len(), 120) { - let (c, _) = aligned_corr(&oracle, &decoded, 2000); - assert!(c >= 0.99, "{tag}: our decode vs oracle decode corr {c:.4}"); - } + let oracle = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len(), 120); + let (c, _) = aligned_corr(&oracle, &decoded, 2000); + assert!(c >= 0.99, "{tag}: our decode vs oracle decode corr {c:.4}"); } } @@ -2319,13 +2134,12 @@ fn silk_multiframe_packets_roundtrip() { packets.len() ); assert!(corr >= floor, "{tag}: corr {corr:.4} below {floor:.4}"); - if let Some(oracle) = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len(), 120) { - let (c, _) = aligned_corr(&oracle, &decoded, 2500); - assert!( - c >= 0.99, - "{tag}: internal decode vs external decode corr {c:.4}" - ); - } + let oracle = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len(), 120); + let (c, _) = aligned_corr(&oracle, &decoded, 2500); + assert!( + c >= 0.99, + "{tag}: internal decode vs external decode corr {c:.4}" + ); if Command::new("gst-launch-1.0") .arg("--version") .output() @@ -2439,42 +2253,39 @@ fn silk_stereo_speech_roundtrip() { mono_floor[ch] ); } - if Command::new("ffmpeg").arg("-version").output().is_ok() { - let path = temp_path(&format!("silk-stereo-{tag}.opus")); - write_ogg_opus( - &path, - &packets, - opus_head(2, enc.look_ahead(frame) as u16, None), - 2, - total, - enc.look_ahead(frame) as i64, - ); - let out = Command::new("ffmpeg") - .args(["-v", "warning", "-c:a", "libopus", "-i"]) - .arg(&path) - .args(["-f", "null", "-"]) + let path = temp_path(&format!("silk-stereo-{tag}.opus")); + write_ogg_opus( + &path, + &packets, + opus_head(2, enc.look_ahead(frame) as u16, None), + 2, + total, + enc.look_ahead(frame) as i64, + ); + let out = ec_testkit::ffmpeg() + .args(["-v", "warning", "-c:a", "libopus", "-i"]) + .arg(&path) + .args(["-f", "null", "-"]) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{tag}: ffmpeg decode: {stderr}"); + if Command::new("gst-launch-1.0") + .arg("--version") + .output() + .is_ok() + { + let location = format!("location={}", path.display()); + let out = Command::new("gst-launch-1.0") + .args([ + "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!", "fakesink", + ]) .output() .unwrap(); let stderr = String::from_utf8_lossy(&out.stderr); - assert!(out.status.success(), "{tag}: ffmpeg decode: {stderr}"); - if Command::new("gst-launch-1.0") - .arg("--version") - .output() - .is_ok() - { - let location = format!("location={}", path.display()); - let out = Command::new("gst-launch-1.0") - .args([ - "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!", - "fakesink", - ]) - .output() - .unwrap(); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!(out.status.success(), "{tag}: gst decode: {stderr}"); - } - let _ = fs::remove_file(&path); + assert!(out.status.success(), "{tag}: gst decode: {stderr}"); } + let _ = fs::remove_file(&path); } } /// Reference oracle decode of `packets` as Ogg-Opus, or `None` without ffmpeg. @@ -2482,15 +2293,7 @@ fn silk_stereo_speech_roundtrip() { /// these packets: it is what the oracle trims off the front, so a caller that /// compares sample-for-sample against its own decode at that same offset only /// lines up when the two agree. -fn oracle_decode( - name: &str, - packets: &[Vec], - samples: usize, - pre_skip: usize, -) -> Option> { - if Command::new("ffmpeg").arg("-version").output().is_err() { - return None; - } +fn oracle_decode(name: &str, packets: &[Vec], samples: usize, pre_skip: usize) -> Vec { let path = temp_path(&format!("{name}.opus")); write_ogg_opus( &path, @@ -2500,7 +2303,7 @@ fn oracle_decode( samples, pre_skip as i64, ); - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "warning", "-c:a", "libopus", "-i"]) .arg(&path) .args(["-f", "null", "-"]) @@ -2519,10 +2322,8 @@ fn oracle_decode( fn silk_sources() -> Vec<(&'static str, Vec)> { let wav = fixture("wav16-mono-48000.wav"); let mut sources = vec![("synthetic", speech_like())]; - if wav.exists() { - let w = read_wav_mono(&wav); - sources.push(("wav16-mono-48000", w[..w.len().min(96000)].to_vec())); - } + let w = read_wav_mono(&wav); + sources.push(("wav16-mono-48000", w[..w.len().min(96000)].to_vec())); sources } @@ -2662,12 +2463,11 @@ fn hybrid_fb_roundtrip() { (28.0..=36.0).contains(&kbps), "{name}: {kbps:.1} kbps for a 32 kbps CBR target" ); - if let Some(oracle) = oracle_decode(&format!("hybrid-{name}"), &packets, pcm.len(), delay) { - let n = oracle.len().min(decoded.len() - delay); - let c = correlation(&oracle[..n], &decoded[delay..delay + n]); - eprintln!("hybrid FB {name}: oracle vs ours corr {c:.4}"); - assert!(c >= 0.95, "{name}: oracle corr {c:.4}"); - } + let oracle = oracle_decode(&format!("hybrid-{name}"), &packets, pcm.len(), delay); + let n = oracle.len().min(decoded.len() - delay); + let c = correlation(&oracle[..n], &decoded[delay..delay + n]); + eprintln!("hybrid FB {name}: oracle vs ours corr {c:.4}"); + assert!(c >= 0.95, "{name}: oracle corr {c:.4}"); } // SWB when asked for it, and the rest of the automatic hybrid range // (SILK's share leaves CELT least at the bottom of it). @@ -2788,16 +2588,14 @@ fn hybrid_shapes_roundtrip() { total, pre_skip as i64, ); - if Command::new("ffmpeg").arg("-version").output().is_ok() { - let out = Command::new("ffmpeg") - .args(["-v", "warning", "-c:a", "libopus", "-i"]) - .arg(&path) - .args(["-f", "null", "-"]) - .output() - .unwrap(); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!(out.status.success(), "{tag}: ffmpeg decode: {stderr}"); - } + let out = ec_testkit::ffmpeg() + .args(["-v", "warning", "-c:a", "libopus", "-i"]) + .arg(&path) + .args(["-f", "null", "-"]) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{tag}: ffmpeg decode: {stderr}"); if Command::new("gst-launch-1.0") .arg("--version") .output() @@ -2823,1562 +2621,60 @@ fn hybrid_shapes_roundtrip() { assert!(toc.stereo); } -// --------------------------------------------------------------------------- -// Encoder library gate vs ffmpeg libopus (encoders-only comparison) -// --------------------------------------------------------------------------- -// -// Both the ec-opus encoder and ffmpeg's libopus encoder encode the same real -// source PCM; BOTH bitstreams are decoded through ec-opus's own decoder, so -// the gap isolates the encoders (the decoder is held constant). A 14-row sweep -// (7 real sources × {64, 96} kbps) lands in `lanes/opus-gate-r1.sweep.txt`. -// `#[ignore]`'d: it shells out to ffmpeg and walks a multi-gigabyte library. +/// Self-contained regression guard for `opus_compare_err` / `opus_compare`. +/// +/// The pinned numbers below were cross-validated against the reference C +/// `opus_compare` tool (built from `opus_compare.c`) on byte-identical raw +/// PCM, so they encode the spectral error algorithm's expected output, not +/// any particular codec. Two cases: +/// * identical signals -> C err=0.000000, Q=100.0 (exact) +/// * mild perturbation -> C err=4.444987, Q=-593.31 (exact to 6 dp) +/// +/// The perturbation case sits in the practical error range (same band as the +/// real-audio validation pairs); the identical case pins the zero-error path +/// with no floating-point tolerance. No audio files or external tools needed. +#[test] +fn opus_compare_err_pinned_against_c() { + let _timing = timing_shared(); + const N: usize = 48000 * 4; // 4 s per channel + let t: Vec = (0..N).map(|i| i as f64 / 48000.0).collect(); -/// Expand a leading `~` to the home directory (the std `Path` API cannot). -fn shellexpand(p: &str) -> PathBuf { - if let Some(rest) = p.strip_prefix("~/") - && let Some(home) = std::env::var_os("HOME") - { - return PathBuf::from(home).join(rest); - } - PathBuf::from(p) -} + let base = |c: usize| -> Vec { + let ph = 0.5 * c as f64; + let ph2 = 0.3 * c as f64; + t.iter() + .map(|&tt| { + 0.3 * (2.0 * std::f64::consts::PI * 440.0 * tt).sin() + + 0.2 * (2.0 * std::f64::consts::PI * 442.0 * tt + ph).sin() + + 0.15 * (2.0 * std::f64::consts::PI * (800.0 + 200.0 * tt) * tt + ph2).sin() + }) + .collect() + }; + let to_i16s = |sig: &[f64]| -> Vec { + sig.iter() + .map(|&v| (v.clamp(-1.0, 1.0) * 32767.0) as i16) + .collect() + }; + let stereo = |l: &[f64], r: &[f64]| -> Vec { + let mut o = Vec::with_capacity(N * 2); + let li = to_i16s(l); + let ri = to_i16s(r); + for i in 0..N { + o.push(li[i]); + o.push(ri[i]); + } + o + }; -/// Decode any source into interleaved f32, 48 kHz, stereo, capped at `secs`. -fn ffmpeg_decode_pcm(path: &Path, secs: f64) -> Vec { - let out = Command::new("ffmpeg") - .args(["-v", "error", "-i"]) - .arg(path) - .args([ - "-vn", - "-t", - &format!("{secs}"), - "-ac", - "2", - "-ar", - "48000", - "-f", - "f32le", - "-acodec", - "pcm_f32le", - "-", - ]) - .output() - .expect("ffmpeg runs"); - assert!( - out.status.success(), - "ffmpeg source decode failed for {}: {}", - path.display(), - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - .as_chunks::<4>() - .0 - .iter() - .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) - .collect() -} + let b0 = base(0); + let b1 = base(1); -/// Encode `src` to an Ogg/Opus file with ffmpeg's libopus at `kbps` (VBR on), -/// capped at `secs`. The realised rate is read back from the output file size. -fn ffmpeg_encode_libopus(src: &Path, kbps: u32, out: &Path, secs: f64) { - let res = Command::new("ffmpeg") - .args(["-y", "-v", "error", "-i"]) - .arg(src) - .args([ - "-vn", - "-t", - &format!("{secs}"), - "-ac", - "2", - "-ar", - "48000", - "-c:a", - "libopus", - "-b:a", - &format!("{kbps}k"), - "-vbr", - "on", - ]) - .arg(out) - .output() - .expect("ffmpeg runs"); - assert!( - res.status.success(), - "ffmpeg libopus encode failed for {} at {kbps}k: {}", - src.display(), - String::from_utf8_lossy(&res.stderr) - ); -} - -/// Lag-scan `decoded` against `source` over ±`max_lag` samples by mean-channel -/// correlation, then emit a `source`-length aligned copy of `decoded`. The lag -/// search runs on the first 10 s only (the task spec) — the encoder/decoder -/// algorithmic delay is constant, so the peak found there holds for the whole -/// file — and the correlation is computed inline without per-lag allocations. -/// The delay lands the peak at a positive lag; the symmetric scan keeps the -/// gate honest if a reference decoder shifts the other way. -fn align_to_source( - source: &[f32], - decoded: &[f32], - channels: usize, - max_lag: usize, -) -> (i32, Vec) { - let sf = source.len() / channels; - let df = decoded.len() / channels; - let scan_frames = sf.min(df).min(48000 * 10); - let scan = max_lag.min(scan_frames); - let mut best = -1.0f64; - let mut best_lag = 0i32; - for lag in -(scan as i32)..=(scan as i32) { - let i0 = if lag < 0 { (-lag) as usize } else { 0 }; - let j0 = if lag < 0 { 0 } else { lag as usize }; - let len = scan_frames.saturating_sub(i0.max(j0)); - if len < 4800 { - continue; - } - let mut cacc = 0.0f64; - for ch in 0..channels { - let (mut sxy, mut sxx, mut syy) = (0.0f64, 0.0f64, 0.0f64); - for i in 0..len { - let a = source[(i0 + i) * channels + ch] as f64; - let b = decoded[(j0 + i) * channels + ch] as f64; - sxy += a * b; - sxx += a * a; - syy += b * b; - } - if sxx > 0.0 && syy > 0.0 { - cacc += sxy / (sxx * syy).sqrt(); - } - } - let c = cacc / channels as f64; - if c > best { - best = c; - best_lag = lag; - } - } - // Build a source-length aligned copy using the chosen lag. - let mut aligned = vec![0.0f32; sf * channels]; - let i0 = if best_lag < 0 { - (-best_lag) as usize - } else { - 0 - }; - let j0 = if best_lag < 0 { 0 } else { best_lag as usize }; - let len = sf.saturating_sub(i0).min(df.saturating_sub(j0)); - for i in 0..len { - for ch in 0..channels { - aligned[(i0 + i) * channels + ch] = decoded[(j0 + i) * channels + ch]; - } - } - (best_lag, aligned) -} - -/// Mean-channel normalized cross-correlation between two interleaved signals, -/// computed inline (no per-channel Vec allocation). -fn corr_interleaved(a: &[f32], b: &[f32], channels: usize) -> f64 { - let n = (a.len() / channels).min(b.len() / channels); - let mut acc = 0.0f64; - for ch in 0..channels { - let (mut sxy, mut sxx, mut syy) = (0.0f64, 0.0f64, 0.0f64); - for i in 0..n { - let av = a[i * channels + ch] as f64; - let bv = b[i * channels + ch] as f64; - sxy += av * bv; - sxx += av * av; - syy += bv * bv; - } - if sxx > 0.0 && syy > 0.0 { - acc += sxy / (sxx * syy).sqrt(); - } - } - acc / channels as f64 -} - -/// Per-second correlation statistics: `(min_second_corr, seconds_below_0.9)`, -/// computed inline without per-second Vec allocation. -fn per_second_corr(source: &[f32], decoded: &[f32], channels: usize) -> (f64, u32) { - let n = (source.len() / channels).min(decoded.len() / channels); - let sec = 48000usize; - let mut min_c = 1.0f64; - let mut drops = 0u32; - let mut start = 0usize; - while start + sec <= n { - let mut acc = 0.0f64; - for ch in 0..channels { - let (mut sxy, mut sxx, mut syy) = (0.0f64, 0.0f64, 0.0f64); - for i in 0..sec { - let a = source[(start + i) * channels + ch] as f64; - let b = decoded[(start + i) * channels + ch] as f64; - sxy += a * b; - sxx += a * a; - syy += b * b; - } - if sxx > 0.0 && syy > 0.0 { - acc += sxy / (sxx * syy).sqrt(); - } - } - let c = acc / channels as f64; - min_c = min_c.min(c); - if c < 0.9 { - drops += 1; - } - start += sec; - } - (min_c, drops) -} - -#[test] -#[ignore = "library gate: hand-run 14-row sweep, 120s per source, needs ffmpeg libopus and the local ~/Music corpus (~12 min); the reelm@64k dropout that first failed it is fixed per lanes/opus-drop-r2.report.md, so only the corpus dependency keeps it out of the default suite"] -fn encoder_library_gate_vs_libopus() { - let _timing = timing_shared(); - const SECS: f64 = 120.0; // 2 min cap; full 600s made the 14-row sweep infeasible - const FRAME: usize = 960; // 20 ms at 48 kHz - const CHANNELS: usize = 2; - const MAX_LAG: usize = 2000; - - let sources: &[(&str, &str)] = &[ - ("nik", "~/Music/reeln.mp4"), - ("reelo", "~/Music/reelo.mp3"), - ("her", "~/Music/reeli.mp3"), - ("reell", "~/Music/reell.mp4"), - ("reelm", "~/Music/reelm.wav"), - ("dl8a", "~/Downloads/8a3b6d1d19.mp3"), - ("hein", "~/Downloads/reelm.mp3"), - ]; - let only: Vec = std::env::var("SWEEP_ONLY") - .unwrap_or_default() - .split(',') - .filter(|s| !s.is_empty()) - .map(|s| s.trim().to_owned()) - .collect(); - let sources: Vec<(String, PathBuf)> = sources - .iter() - .filter(|(tag, _)| only.is_empty() || only.iter().any(|o| o == tag)) - .map(|(tag, p)| (tag.to_string(), shellexpand(p))) - .collect(); - assert!(!sources.is_empty(), "SWEEP_ONLY matched no sources"); - - let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes"); - fs::create_dir_all(&lanes_dir).unwrap(); - let sweep_path = lanes_dir.join("opus-gate-r1.sweep.txt"); - let scratch = lanes_dir.join("opus-gate-r1.scratch.ogg"); - - let mut rows: Vec = Vec::new(); - let mut rate_violations: Vec = Vec::new(); - let mut dropout_violations: Vec = Vec::new(); - - for (tag, src) in &sources { - if !src.exists() { - eprintln!("SKIP {tag}: missing {}", src.display()); - continue; - } - let source_pcm = ffmpeg_decode_pcm(src, SECS); - let source_frames = source_pcm.len() / CHANNELS; - assert!(source_frames > 48_000, "{tag}: source too short"); - let seconds = source_frames as f64 / 48000.0; - let source_i16 = to_i16(&source_pcm); - - for &kbps in &[64u32, 96u32] { - // Reference: ffmpeg libopus, VBR on, realised rate from file size. - ffmpeg_encode_libopus(src, kbps, &scratch, SECS); - let ref_bytes = fs::metadata(&scratch) - .map(|m| m.len() as usize) - .unwrap_or(0); - let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0; - let (ref_dec, ref_ch) = decode_ogg(&scratch); - assert_eq!(ref_ch, CHANNELS, "{tag}@{kbps}: ref not stereo"); - let (_, ref_aligned) = align_to_source(&source_pcm, &ref_dec, CHANNELS, MAX_LAG); - - // Ours: ec-opus encoder at the reference's realised rate, decoded - // by our own decoder; payload bytes give the realised rate. - let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder"); - enc.set_bitrate((ref_kbps * 1000.0).round() as u32); - enc.set_vbr_constrained(true); - let (ours_dec, ours_bytes) = roundtrip_own(&mut enc, &source_pcm, CHANNELS, FRAME); - let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0; - // Drop the zero-padded tail of the final frame to match the source. - let ours_trim: Vec = ours_dec - .into_iter() - .take(source_frames * CHANNELS) - .collect(); - let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG); - let ours_i16 = to_i16(&ours_aligned); - let ref_i16 = to_i16(&ref_aligned); - - // Equal-length i16 inputs for opus_compare (trim to common length). - let cmp_frames = (source_i16.len() / CHANNELS) - .min(ours_i16.len() / CHANNELS) - .min(ref_i16.len() / CHANNELS); - let trim = |v: &[i16]| -> Vec { v[..cmp_frames * CHANNELS].to_vec() }; - let s_i = trim(&source_i16); - let o_i = trim(&ours_i16); - let r_i = trim(&ref_i16); - let q_ours = opus_compare(&s_i, &o_i, CHANNELS); - let q_ref = opus_compare(&s_i, &r_i, CHANNELS); - let err_ours = opus_compare_err(&s_i, &o_i, CHANNELS); - let err_ref = opus_compare_err(&s_i, &r_i, CHANNELS); - let err_ratio = if err_ref > 0.0 { - err_ours / err_ref - } else { - f64::INFINITY - }; - - let corr_ours = corr_interleaved(&source_pcm, &ours_aligned, CHANNELS); - let corr_ref = corr_interleaved(&source_pcm, &ref_aligned, CHANNELS); - let gap = corr_ref - corr_ours; - let (minsec_ours, drop_ours) = per_second_corr(&source_pcm, &ours_aligned, CHANNELS); - let (minsec_ref, drop_ref) = per_second_corr(&source_pcm, &ref_aligned, CHANNELS); - let rate_pct = (ours_kbps / ref_kbps - 1.0) * 100.0; - - if rate_pct.abs() > 5.0 { - rate_violations.push(format!("{tag}@{kbps}k: rate {rate_pct:+.1}% (|>5%)")); - } - // Dropout gate: ours must not lose a second the reference kept. - if drop_ours > 0 && drop_ref == 0 { - dropout_violations.push(format!( - "{tag}@{kbps}k: ours dropped {drop_ours}s below 0.9 corr, ref 0s" - )); - } - - println!( - "{tag}@{kbps}k: ref {ref_kbps:.1} ours {ours_kbps:.1} kbps ({rate_pct:+.1}%), \ - corr o={corr_ours:.4} r={corr_ref:.4} gap={gap:+.4}, \ - Q o={q_ours:.2} r={q_ref:.2}, err_ratio {err_ratio:.3}, \ - minsec o={minsec_ours:.4} r={minsec_ref:.4}, drop o={drop_ours} r={drop_ref}" - ); - rows.push(format!( - "{tag}\t{kbps}\t{ours_kbps:.1}\t{ref_kbps:.1}\t{rate_pct:+.1}\t\ - {corr_ours:.4}\t{corr_ref:.4}\t{gap:+.4}\t\ - {q_ours:.2}\t{q_ref:.2}\t{err_ratio:.3}\t\ - {minsec_ours:.4}\t{minsec_ref:.4}\t{drop_ours}\t{drop_ref}" - )); - } - } - let _ = fs::remove_file(&scratch); - - let mut table = String::new(); - table.push_str("# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1)\n"); - table.push_str("# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo\n"); - table.push_str( - "# source\tkbps\tours_kbps\tref_kbps\trate%\tcorr_ours\tcorr_ref\tgap\t\ - Q_ours\tQ_ref\terr_ratio\tminsec_ours\tminsec_ref\tdrop_ours\tdrop_ref\n", - ); - for r in &rows { - table.push_str(r); - table.push('\n'); - } - fs::write(&sweep_path, table).unwrap(); - println!("wrote {}", sweep_path.display()); - - // Rate gate: report violations, never panic. - if !rate_violations.is_empty() { - eprintln!("RATE GATE violations (|rate%| > 5):"); - for v in &rate_violations { - eprintln!(" {v}"); - } - } else { - println!("RATE GATE: all rows within ±5%"); - } - // Dropout gate: hard fail — a second the reference kept must not drop out. - assert!( - dropout_violations.is_empty(), - "DROPOUT GATE failed (ours dropped seconds ref kept):\n {}", - dropout_violations.join("\n ") - ); - println!("DROPOUT GATE: passed (no ours-only dropouts)"); -} - -// --------------------------------------------------------------------------- -// SILK / speech-rate library gate vs libopus (lane opus-silk r1). -// -// Source: ~/Music/reelm.wav (real interview speech) downmixed to MONO. Rows: -// 12k NB, 16k NB, 24k WB (SILK), 32k hybrid. Ours via Encoder::new(48000, 1, -// Application::Voip) with set_bitrate and set_bandwidth/set_mode as needed so -// Voip really picks SILK/Hybrid — the mode each row took is printed from the -// first packet's TOC config byte (RFC 6716 §3.1). Reference: ffmpeg libopus -// -application voip -b:a , mono, VBR on. RATE GATE ±5%, DROPOUT GATE. -// SIGN RULE (verbatim): gap = ref_corr - ours_corr; MORE NEGATIVE = OURS BETTER. -// Run: cargo test -p ec-opus --release --test conformance \ -// silk_library_gate_vs_libopus -- --ignored --nocapture -// --------------------------------------------------------------------------- - -/// Mode label from a packet's TOC config byte (RFC 6716 §3.1): config = toc>>3. -fn toc_mode_label(toc: u8) -> &'static str { - match toc >> 3 { - 0..=3 => "SILK-NB", - 4..=7 => "SILK-MB", - 8..=11 => "SILK-WB", - 12 | 13 => "Hybrid-SWB", - 14 | 15 => "Hybrid-FB", - 16..=31 => "CELT", - _ => "??", - } -} - -// corner-cut: near-duplicate of ffmpeg_decode_pcm / ffmpeg_encode_libopus with -// -ac 1 and -application voip. Parameterising the existing helpers would touch -// the stereo gate's callsites; keep this lane self-contained. Ceiling: only the -// SILK gate needs mono voip — merge when a second mono consumer appears. -/// Decode any source into interleaved f32, 48 kHz, MONO, capped at `secs`. -fn ffmpeg_decode_pcm_mono(path: &Path, secs: f64) -> Vec { - let out = Command::new("ffmpeg") - .args(["-v", "error", "-i"]) - .arg(path) - .args([ - "-vn", - "-t", - &format!("{secs}"), - "-ac", - "1", - "-ar", - "48000", - "-f", - "f32le", - "-acodec", - "pcm_f32le", - "-", - ]) - .output() - .expect("ffmpeg runs"); - assert!( - out.status.success(), - "ffmpeg mono decode failed for {}: {}", - path.display(), - String::from_utf8_lossy(&out.stderr) - ); - out.stdout - .as_chunks::<4>() - .0 - .iter() - .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) - .collect() -} - -/// Encode `src` to a mono Ogg/Opus file with ffmpeg libopus, VoIP application, -/// at `kbps` (VBR on), capped at `secs`. Realised rate read back from file size. -fn ffmpeg_encode_libopus_mono_voip(src: &Path, kbps: u32, out: &Path, secs: f64) { - let res = Command::new("ffmpeg") - .args(["-y", "-v", "error", "-i"]) - .arg(src) - .args([ - "-vn", - "-t", - &format!("{secs}"), - "-ac", - "1", - "-ar", - "48000", - "-c:a", - "libopus", - "-application", - "voip", - "-b:a", - &format!("{kbps}k"), - "-vbr", - "on", - ]) - .arg(out) - .output() - .expect("ffmpeg runs"); - assert!( - res.status.success(), - "ffmpeg libopus mono voip encode failed at {kbps}k: {}", - String::from_utf8_lossy(&res.stderr) - ); -} - -/// Same as [`roundtrip_own`] but also returns the encoded packets, so the SILK -/// gate can re-decode them through ffmpeg (decoder-symmetric comparison). -fn roundtrip_own_packets( - enc: &mut Encoder, - pcm: &[f32], - channels: usize, - frame: usize, -) -> (Vec, Vec>, usize) { - let mut dec = Decoder::new(48000, channels).unwrap(); - let mut out = vec![0u8; 1500]; - let mut decoded = Vec::new(); - let mut packets = Vec::new(); - let mut buf = vec![0.0f32; 5760 * channels]; - let mut bytes = 0usize; - let mut padded = Vec::new(); - for block in pcm.chunks(frame * channels) { - let block = if block.len() < frame * channels { - padded.clear(); - padded.extend_from_slice(block); - padded.resize(frame * channels, 0.0); - &padded[..] - } else { - block - }; - let len = enc.encode_float(block, frame, &mut out).expect("encode"); - bytes += len; - packets.push(out[..len].to_vec()); - let n = dec.decode_float(&out[..len], &mut buf).expect("decode"); - assert_eq!(n, frame, "decoded frame size"); - assert_eq!( - dec.final_range(), - enc.final_range(), - "range state diverged between encoder and decoder" - ); - decoded.extend_from_slice(&buf[..n * channels]); - } - (decoded, packets, bytes) -} - -/// First audio packet's TOC byte from Ogg-Opus bytes (skips OpusHead/OpusTags). -fn first_audio_toc(ogg: &[u8]) -> u8 { - for p in ogg_packets(ogg) { - if p.len() >= 8 && (&p[..8] == b"OpusHead" || &p[..8] == b"OpusTags") { - continue; - } - if !p.is_empty() { - return p[0]; - } - } - 0 -} - -#[test] -#[ignore = "library gate: hand-run mono VoIP sweep; blocked until ~/Music/reelm.wav is back in the corpus (hard-asserts src.exists) and it is a multi-minute ffmpeg run, not a suite test"] -fn silk_library_gate_vs_libopus() { - let _timing = timing_shared(); - const SECS: f64 = 120.0; // 2 min cap - const FRAME: usize = 960; // 20 ms at 48 kHz - const CHANNELS: usize = 1; // MONO - const MAX_LAG: usize = 2000; - - let src = shellexpand("~/Music/reelm.wav"); - assert!(src.exists(), "source missing: {}", src.display()); - - let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes"); - fs::create_dir_all(&lanes_dir).unwrap(); - let sweep_path = lanes_dir.join("opus-mode-r1.sweep.txt"); - let ref_ogg = temp_path("opus-silk-r2-ref.opus"); - let ours_ogg = temp_path("opus-silk-r2-ours.opus"); - - // Source PCM: mono, 48 kHz. - let source_pcm = ffmpeg_decode_pcm_mono(&src, SECS); - let source_frames = source_pcm.len() / CHANNELS; - assert!(source_frames > 48_000, "source too short"); - let seconds = source_frames as f64 / 48000.0; - - // (label, kbps, forced bandwidth, forced mode, reference lowpass cutoff). - // cutoff: NB 4 kHz, WB 8 kHz, hybrid-FB unfiltered (None) — compare each - // encoder only against the band it can actually reproduce. - type Row = ( - &'static str, - u32, - Option, - Option, - Option, - ); - let rows: &[Row] = &[ - // All rows auto since lane opus-mode: the selector is libopus's, so - // the mode must match the reference's (asserted below) and the - // comparison is full-band (no lowpass). - ("12k", 12, None, None, None), - ("16k", 16, None, None, None), - ("24k", 24, None, None, None), - ("32k", 32, None, None, None), - ]; - - let mut out_rows: Vec = Vec::new(); - let mut rate_violations: Vec = Vec::new(); - let mut dropout_violations: Vec = Vec::new(); - let mut lag_violations: Vec = Vec::new(); - - for &(tag, kbps, bw, mode, cutoff) in rows { - // Band-limited reference source for this row's corr/opus_compare. - let ref_source: Vec = match cutoff { - Some(hz) => lowpass(&source_pcm, hz), - None => source_pcm.clone(), - }; - let ref_source_i16 = to_i16(&ref_source); - - // Reference: ffmpeg libopus, mono, voip, VBR; realised rate from size. - ffmpeg_encode_libopus_mono_voip(&src, kbps, &ref_ogg, SECS); - let ref_bytes = fs::metadata(&ref_ogg) - .map(|m| m.len() as usize) - .unwrap_or(0); - let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0; - // SYMMETRY: ref decoded through ffmpeg libopus (the reference decoder), - // NOT our own decoder — so both sides cross the same decoder. (r1 used - // decode_ogg, our own MultistreamDecoder, for the ref side.) - let ref_dec = ffmpeg_decode(&ref_ogg, CHANNELS).expect("ffmpeg libopus decode of ref"); - let ref_trim: Vec = ref_dec.into_iter().take(source_frames * CHANNELS).collect(); - let (lag_ref, ref_aligned) = align_to_source(&source_pcm, &ref_trim, CHANNELS, MAX_LAG); - // REF MODE: libopus's actual mode from its first audio packet TOC. - let ref_ogg_bytes = fs::read(&ref_ogg).expect("read ref ogg"); - let ref_mode = toc_mode_label(first_audio_toc(&ref_ogg_bytes)); - - // Ours: ec-opus Voip at the reference's realised rate. - let mut enc = Encoder::new(48000, CHANNELS, Application::Voip).expect("encoder"); - enc.set_bitrate((ref_kbps * 1000.0).round() as u32); - if let Some(b) = bw { - enc.set_bandwidth(Some(b)); - } - if let Some(m) = mode { - enc.set_mode(Some(m)); - } - enc.set_vbr_constrained(true); - let pre_skip = enc.look_ahead(FRAME) as i64; - - // Probe which mode the encoder actually picked, from the first TOC byte. - let mut probe = enc.clone(); - let mut toc_buf = [0u8; 1500]; - probe - .encode_float(&source_pcm[..FRAME * CHANNELS], FRAME, &mut toc_buf) - .expect("encode probe"); - let mode_label = toc_mode_label(toc_buf[0]); - assert_eq!( - ref_mode, mode_label, - "{tag}: mode mismatch ref={ref_mode} ours={mode_label} (MODE GATE)" - ); - - // Own-decoder roundtrip (range-coder invariant) + packet capture. - let (ours_own_dec, ours_packets, ours_bytes) = - roundtrip_own_packets(&mut enc, &source_pcm, CHANNELS, FRAME); - let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0; - - // SYMMETRY: re-decode OUR packets through ffmpeg libopus too. - write_ogg_opus( - &ours_ogg, - &ours_packets, - opus_head(CHANNELS, pre_skip as u16, None), - CHANNELS, - source_frames, - pre_skip, - ); - let ours_dec = ffmpeg_decode(&ours_ogg, CHANNELS).expect("ffmpeg libopus decode of ours"); - let ours_trim: Vec = ours_dec - .into_iter() - .take(source_frames * CHANNELS) - .collect(); - let (lag_ours, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG); - - // Own-decoder aligned (extra column: decoder drift visibility). - let ours_own_trim: Vec = ours_own_dec - .into_iter() - .take(source_frames * CHANNELS) - .collect(); - let (_, ours_own_aligned) = align_to_source(&source_pcm, &ours_own_trim, CHANNELS, MAX_LAG); - - // LAG GATE: a lag at the scan bound is an invalid measurement, not a result. - if (lag_ours as i64).abs() >= MAX_LAG as i64 { - lag_violations.push(format!( - "{tag}: ours lag {lag_ours} hit scan bound {MAX_LAG}" - )); - } - if (lag_ref as i64).abs() >= MAX_LAG as i64 { - lag_violations.push(format!("{tag}: ref lag {lag_ref} hit scan bound {MAX_LAG}")); - } - - let ours_i16 = to_i16(&ours_aligned); - let ref_i16 = to_i16(&ref_aligned); - let cmp_frames = (ref_source_i16.len() / CHANNELS) - .min(ours_i16.len() / CHANNELS) - .min(ref_i16.len() / CHANNELS); - let trim = |v: &[i16]| -> Vec { v[..cmp_frames * CHANNELS].to_vec() }; - let s_i = trim(&ref_source_i16); - let o_i = trim(&ours_i16); - let r_i = trim(&ref_i16); - let q_ours = opus_compare(&s_i, &o_i, CHANNELS); - let q_ref = opus_compare(&s_i, &r_i, CHANNELS); - let err_ours = opus_compare_err(&s_i, &o_i, CHANNELS); - let err_ref = opus_compare_err(&s_i, &r_i, CHANNELS); - let err_ratio = if err_ref > 0.0 { - err_ours / err_ref - } else { - f64::INFINITY - }; - - // Primary corr: band-limited reference. Secondary: full-band source. - let corr_ours_bl = corr_interleaved(&ref_source, &ours_aligned, CHANNELS); - let corr_ref_bl = corr_interleaved(&ref_source, &ref_aligned, CHANNELS); - let gap = corr_ref_bl - corr_ours_bl; // SIGN RULE: more negative = ours better - let corr_ours_fb = corr_interleaved(&source_pcm, &ours_aligned, CHANNELS); - let corr_ref_fb = corr_interleaved(&source_pcm, &ref_aligned, CHANNELS); - let corr_ours_owndec = corr_interleaved(&ref_source, &ours_own_aligned, CHANNELS); - let (minsec_ours, drop_ours) = per_second_corr(&ref_source, &ours_aligned, CHANNELS); - let (minsec_ref, drop_ref) = per_second_corr(&ref_source, &ref_aligned, CHANNELS); - let rate_pct = (ours_kbps / ref_kbps - 1.0) * 100.0; - - if rate_pct.abs() > 5.0 { - rate_violations.push(format!("{tag}: rate {rate_pct:+.1}% (|>5%)")); - } - if drop_ours > 0 && drop_ref == 0 { - dropout_violations.push(format!( - "{tag}: ours dropped {drop_ours}s below 0.9 corr, ref 0s" - )); - } - let row = format!( - "{tag}: ref_mode={ref_mode} mode={mode_label}, ref {ref_kbps:.1} ours {ours_kbps:.1} kbps ({rate_pct:+.1}%), \ - lag o={lag_ours} r={lag_ref}, \ - corr_bl o={corr_ours_bl:.4} r={corr_ref_bl:.4} gap={gap:+.4}, \ - corr_fb o={corr_ours_fb:.4} r={corr_ref_fb:.4}, corr_owndec o={corr_ours_owndec:.4}, \ - Q o={q_ours:.2} r={q_ref:.2}, err_ratio {err_ratio:.3}, \ - minsec o={minsec_ours:.4} r={minsec_ref:.4}, drop o={drop_ours} r={drop_ref}" - ); - println!("{row}"); - out_rows.push(row); - } - let _ = fs::remove_file(&ref_ogg); - let _ = fs::remove_file(&ours_ogg); - - // Rate gate: report violations, never panic. - let rate_gate = if rate_violations.is_empty() { - "RATE GATE: all rows within ±5%".to_string() - } else { - let mut s = "RATE GATE violations (|rate%| > 5):".to_string(); - for v in &rate_violations { - s.push_str("\n "); - s.push_str(v); - } - s - }; - if rate_violations.is_empty() { - println!("{rate_gate}"); - } else { - eprintln!("{rate_gate}"); - } - // Lag gate: hard fail — a measurement at the scan bound is not a result. - assert!( - lag_violations.is_empty(), - "LAG GATE failed (lag at scan bound):\n {}", - lag_violations.join("\n ") - ); - let lag_gate = "LAG GATE: passed (no lag at scan bound)"; - println!("{lag_gate}"); - // Dropout gate: hard fail — a second the reference kept must not drop out. - assert!( - dropout_violations.is_empty(), - "DROPOUT GATE failed (ours dropped seconds ref kept):\n {}", - dropout_violations.join("\n ") - ); - let drop_gate = "DROPOUT GATE: passed (no ours-only dropouts)"; - println!("{drop_gate}"); - - // Sweep file: raw rows + GATE lines (lane deliverable). - let mut table = String::new(); - table.push_str("# ec-opus SILK/speech-rate gate vs ffmpeg libopus (r2)\n"); - table.push_str("# mono, 120s cap, VBR, 48kHz, Application::Voip; source reelm.wav\n"); - table.push_str("# r2: symmetric ffmpeg-libopus decode (both sides), lag gate, band-limited ref, ref mode\n"); - for r in &out_rows { - table.push_str(r); - table.push('\n'); - } - table.push_str(&rate_gate); - table.push('\n'); - table.push_str(lag_gate); - table.push('\n'); - table.push_str(drop_gate); - table.push('\n'); - fs::write(&sweep_path, table).unwrap(); - println!("wrote {}", sweep_path.display()); -} - -// --------------------------------------------------------------------------- -// ORACLE: decode both our packets and ffmpeg-libopus ref packets through our -// own SilkDecoder, read back the per-frame `Indices`, and print side-by-side -// for the worst seconds to name the divergence mechanism. -// Run: SWEEP_ONLY=reelm cargo test -p ec-opus --release --test conformance \ -// silk_silkq_oracle -- --ignored --nocapture -// --------------------------------------------------------------------------- -#[test] -#[ignore = "probe: per-frame SILK Indices side-by-side oracle dump; unblocks when ~/Music/reelm.wav is back in the corpus (hard-asserts src.exists)"] -fn silk_silkq_oracle() { - let _timing = timing_shared(); - const SECS: f64 = 120.0; - const FRAME: usize = 960; // 20 ms at 48 kHz - const CHANNELS: usize = 1; - const KBPS: u32 = 12; - const TARGET_SECS: &[usize] = &[3, 39, 51, 5, 1]; - - let src = shellexpand("~/Music/reelm.wav"); - assert!(src.exists(), "source missing: {}", src.display()); - let source_pcm = ffmpeg_decode_pcm_mono(&src, SECS); - - let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes"); - fs::create_dir_all(&lanes_dir).unwrap(); - let ref_ogg = temp_path("opus-silkq-oracle-ref.opus"); - - // Reference: ffmpeg libopus mono voip at 12k. - ffmpeg_encode_libopus_mono_voip(&src, KBPS, &ref_ogg, SECS); - let ref_ogg_bytes = fs::read(&ref_ogg).expect("read ref ogg"); - let ref_packets: Vec> = ogg_packets(&ref_ogg_bytes) - .into_iter() - .skip(2) - .filter(|p| !p.is_empty()) - .collect(); - let _ = fs::remove_file(&ref_ogg); - - // Ours: ec-opus Voip at 12k. - let mut enc = Encoder::new(48000, CHANNELS, Application::Voip).expect("encoder"); - enc.set_bitrate(KBPS * 1000); - enc.set_vbr_constrained(true); - let mut out = vec![0u8; 1500]; - let mut ours_packets: Vec> = Vec::new(); - let mut padded = Vec::new(); - for block in source_pcm.chunks(FRAME * CHANNELS) { - let block = if block.len() < FRAME * CHANNELS { - padded.clear(); - padded.extend_from_slice(block); - padded.resize(FRAME * CHANNELS, 0.0); - &padded[..] - } else { - block - }; - let len = enc.encode_float(block, FRAME, &mut out).expect("encode"); - ours_packets.push(out[..len].to_vec()); - } - - let ours_ix = collect_indices(&ours_packets); - let ref_ix = collect_indices(&ref_packets); - - eprintln!( - "ours frames: {} ref frames: {}", - ours_ix.len(), - ref_ix.len() - ); - - // Print side-by-side for target seconds (50 frames/sec at 20ms). - let frames_per_sec = 50usize; - let mut out_str = String::new(); - out_str.push_str("# reelm@12k SILK oracle: ours vs ffmpeg-libopus indices (r1)\n"); - out_str.push_str("# mono, 120s, 20ms frames, VBR constrained, 48kHz, Application::Voip\n"); - out_str.push_str(&format!( - "# ours_frames={} ref_frames={}\n", - ours_ix.len(), - ref_ix.len() - )); - out_str.push_str("# sig: 0=unvoiced 2=voiced | per: LTP codebook | nlsf_i: 4=nointerp\n"); - out_str.push_str("# gains/ltp are 4 subframe indices; lag/contour only for voiced\n\n"); - - for &sec in TARGET_SECS { - let start = sec * frames_per_sec; - let end = start + frames_per_sec; - out_str.push_str(&format!( - "=== second {} (frames {}–{}) ===\n", - sec, - start, - end - 1 - )); - out_str.push_str("frame side sig qoff gains[4] nlsf_i lag cont per ltp[4] ltpscl seed bytes\n"); - for f in start..end { - let ours = ours_ix.get(f); - let refr = ref_ix.get(f); - if ours.is_none() && refr.is_none() { - continue; - } - for (side, item) in [("O", ours), ("R", refr)] { - match item { - Some((ix, bytes)) => { - let voiced = ix.signal_type == 2; - let lag_str = if voiced { - format!("{:4}", ix.lag_index) - } else { - " -".to_string() - }; - let cont_str = if voiced { - format!("{:4}", ix.contour_index) - } else { - " -".to_string() - }; - let per_str = if voiced { - format!("{}", ix.per_index) - } else { - "-".to_string() - }; - let ltp_str = if voiced { - format!( - "[{},{},{},{}]", - ix.ltp_index[0], ix.ltp_index[1], ix.ltp_index[2], ix.ltp_index[3] - ) - } else { - "[-,-,-,-]".to_string() - }; - let ltpscl_str = if voiced { - format!("{}", ix.ltp_scale_index) - } else { - "-".to_string() - }; - out_str.push_str(&format!( - "{:5} {} {:2} {:2} [{:2},{:2},{:2},{:2}] {:2} {} {} {} {} {} {:2} {:3}\n", - f, side, ix.signal_type, ix.quant_offset_type, - ix.gains[0], ix.gains[1], ix.gains[2], ix.gains[3], - ix.nlsf_interp_coef_q2, - lag_str, cont_str, per_str, ltp_str, ltpscl_str, - ix.seed, bytes, - )); - } - None => { - out_str.push_str(&format!("{:5} {} -- missing --\n", f, side)); - } - } - } - } - out_str.push('\n'); - } - - // Summarize divergence statistics across ALL frames. - let n = ours_ix.len().min(ref_ix.len()); - let mut sig_mismatch = 0; - let mut qoff_mismatch = 0; - let mut gain_diff_sum = 0i64; - let mut nlsf_interp_diff = 0; - let mut ltp_per_mismatch = 0; - let mut ltp_idx_diff_sum = 0i64; - let mut voiced_both = 0; - let mut lag_diff_sum = 0i64; - let mut bytes_ours = 0u64; - let mut bytes_ref = 0u64; - for i in 0..n { - let (o, ob) = &ours_ix[i]; - let (r, rb) = &ref_ix[i]; - if o.signal_type != r.signal_type { - sig_mismatch += 1; - } - if o.quant_offset_type != r.quant_offset_type { - qoff_mismatch += 1; - } - for k in 0..4 { - gain_diff_sum += (o.gains[k] as i64 - r.gains[k] as i64).abs(); - } - if o.nlsf_interp_coef_q2 != r.nlsf_interp_coef_q2 { - nlsf_interp_diff += 1; - } - if o.signal_type == 2 && r.signal_type == 2 { - voiced_both += 1; - if o.per_index != r.per_index { - ltp_per_mismatch += 1; - } - for k in 0..4 { - ltp_idx_diff_sum += (o.ltp_index[k] as i64 - r.ltp_index[k] as i64).abs(); - } - lag_diff_sum += (o.lag_index as i64 - r.lag_index as i64).abs(); - } - bytes_ours += *ob as u64; - bytes_ref += *rb as u64; - } - out_str.push_str("=== divergence summary (all frames) ===\n"); - out_str.push_str(&format!("frames compared: {}\n", n)); - out_str.push_str(&format!( - "signal_type mismatch: {} ({:.1}%)\n", - sig_mismatch, - 100.0 * sig_mismatch as f64 / n as f64 - )); - out_str.push_str(&format!( - "quant_offset mismatch: {} ({:.1}%)\n", - qoff_mismatch, - 100.0 * qoff_mismatch as f64 / n as f64 - )); - out_str.push_str(&format!( - "avg |gain diff| per subframe: {:.2}\n", - gain_diff_sum as f64 / (n as f64 * 4.0) - )); - out_str.push_str(&format!( - "nlsf_interp mismatch: {} ({:.1}%)\n", - nlsf_interp_diff, - 100.0 * nlsf_interp_diff as f64 / n as f64 - )); - out_str.push_str(&format!("voiced_both: {}\n", voiced_both)); - out_str.push_str(&format!( - " LTP per_index mismatch: {} ({:.1}%)\n", - ltp_per_mismatch, - 100.0 * ltp_per_mismatch as f64 / voiced_both.max(1) as f64 - )); - out_str.push_str(&format!( - " avg |ltp_index diff| per subframe: {:.2}\n", - ltp_idx_diff_sum as f64 / (voiced_both.max(1) as f64 * 4.0) - )); - out_str.push_str(&format!( - " avg |lag diff|: {:.2}\n", - lag_diff_sum as f64 / voiced_both.max(1) as f64 - )); - out_str.push_str(&format!( - "total bytes: ours={} ref={} ratio={:.3}\n", - bytes_ours, - bytes_ref, - bytes_ours as f64 / bytes_ref.max(1) as f64 - )); - - let out_path = lanes_dir.join("opus-silkq-r1.oracle.txt"); - fs::write(&out_path, &out_str).unwrap(); - println!("wrote {}", out_path.display()); - print!("{}", out_str); -} - -/// Decode a SILK stream packet-by-packet through a fresh `SilkDecoder`, -/// snapshotting each frame's coded indices — the oracle diagnostic's view of -/// what the bitstream actually coded (our encoder's packets and a reference -/// encoder's alike). -fn collect_indices(packets: &[Vec]) -> Vec<(ec_opus::SilkDecIndices, usize)> { - let mut silk = ec_opus::SilkDecoder::new(16000, 1); - let mut results = Vec::new(); - let mut silk_pcm = vec![0i16; 320]; // 20ms at 16kHz - for pkt in packets { - if pkt.len() <= 1 { - continue; // DTX / empty - } - let parsed = match ec_opus::Packet::parse(pkt, false) { - Ok(p) => p, - Err(_) => continue, - }; - let toc = parsed.toc; - let mode = toc.mode(); - if mode == ec_opus::Mode::Celt { - continue; - } - let internal_rate = if mode == ec_opus::Mode::Hybrid { - 16000 - } else { - match toc.bandwidth() { - ec_opus::Bandwidth::Narrow => 8000, - ec_opus::Bandwidth::Medium => 12000, - _ => 16000, - } - }; - let payload_ms = (toc.frame_size_48k() / 48).max(10); - let mut first = true; - for frame_data in &parsed.frames { - if frame_data.len() <= 1 { - first = false; - continue; - } - let mut dec = ec_opus::RangeDecoder::new(frame_data); - let _ = silk.decode( - &mut dec, - &mut silk_pcm, - payload_ms, - internal_rate, - 1, - first, - ec_opus::SilkFrameMode::Normal, - ); - let ix = silk.last_indices(); - let bytes = frame_data.len(); - results.push((ix, bytes)); - first = false; - } - } - results -} - -// --------------------------------------------------------------------------- -// SILK 12k spectral divergence: WHERE the 12 kbps Voip err_ratio outlier -// carries its error. Same machinery as spectral_divergence_vs_libopus, but -// mono/Application::Voip/12 kbps on reelm.wav, both sides decoded through -// ffmpeg libopus (gate symmetry), with the index oracle on the worst frames. -// Run: -// cargo test -p ec-opus --release --test conformance \ -// silk_spectral_divergence_12k -- --ignored --nocapture -// Writes lanes/opus-silkq-r2.bands.txt. -// --------------------------------------------------------------------------- - -#[test] -#[ignore = "probe: per-band spectral divergence dump at 12k; unblocks when ~/Music/reelm.wav is back in the corpus (hard-asserts src.exists)"] -fn silk_spectral_divergence_12k() { - let _timing = timing_shared(); - const SECS: f64 = 120.0; - const FRAME: usize = 960; // 20 ms at 48 kHz - const CHANNELS: usize = 1; - const MAX_LAG: usize = 2000; - const KBPS: u32 = 12; - - let src = shellexpand("~/Music/reelm.wav"); - assert!(src.exists(), "source missing: {}", src.display()); - let source_pcm = ffmpeg_decode_pcm_mono(&src, SECS); - let source_frames = source_pcm.len() / CHANNELS; - assert!(source_frames > 48_000, "source too short"); - let seconds = source_frames as f64 / 48000.0; - - let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes"); - fs::create_dir_all(&lanes_dir).unwrap(); - let ref_ogg = temp_path("opus-silkq-r2-ref.opus"); - let ours_ogg = temp_path("opus-silkq-r2-ours.opus"); - - // Reference: ffmpeg libopus mono voip at 12k, decoded by ffmpeg libopus. - ffmpeg_encode_libopus_mono_voip(&src, KBPS, &ref_ogg, SECS); - let ref_bytes = fs::metadata(&ref_ogg) - .map(|m| m.len() as usize) - .unwrap_or(0); - let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0; - let ref_dec = ffmpeg_decode(&ref_ogg, CHANNELS).expect("ffmpeg libopus decode of ref"); - let ref_trim: Vec = ref_dec.into_iter().take(source_frames * CHANNELS).collect(); - let (_, ref_aligned) = align_to_source(&source_pcm, &ref_trim, CHANNELS, MAX_LAG); - let ref_ogg_bytes = fs::read(&ref_ogg).expect("read ref ogg"); - let ref_packets: Vec> = ogg_packets(&ref_ogg_bytes) - .into_iter() - .skip(2) - .filter(|p| !p.is_empty()) - .collect(); - let _ = fs::remove_file(&ref_ogg); - - // Ours: ec-opus Voip at the reference's realised rate; our packets - // re-decoded through ffmpeg libopus so both sides cross the same decoder. - let mut enc = Encoder::new(48000, CHANNELS, Application::Voip).expect("encoder"); - enc.set_bitrate((ref_kbps * 1000.0).round() as u32); - enc.set_vbr_constrained(true); - let pre_skip = enc.look_ahead(FRAME) as i64; - let mut out = vec![0u8; 1500]; - let mut ours_packets: Vec> = Vec::new(); - let mut padded = Vec::new(); - for block in source_pcm.chunks(FRAME * CHANNELS) { - let block = if block.len() < FRAME * CHANNELS { - padded.clear(); - padded.extend_from_slice(block); - padded.resize(FRAME * CHANNELS, 0.0); - &padded[..] - } else { - block - }; - let len = enc.encode_float(block, FRAME, &mut out).expect("encode"); - ours_packets.push(out[..len].to_vec()); - } - write_ogg_opus( - &ours_ogg, - &ours_packets, - opus_head(CHANNELS, pre_skip as u16, None), - CHANNELS, - source_frames, - pre_skip, - ); - let ours_bytes: usize = ours_packets.iter().map(|p| p.len()).sum(); - let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0; - let ours_dec = ffmpeg_decode(&ours_ogg, CHANNELS).expect("ffmpeg libopus decode of ours"); - let _ = fs::remove_file(&ours_ogg); - let ours_trim: Vec = ours_dec - .into_iter() - .take(source_frames * CHANNELS) - .collect(); - let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG); - - // opus_compare totals, per-band eb², per-frame ef² — both vs the source. - let cmp_frames = source_frames - .min(ours_aligned.len() / CHANNELS) - .min(ref_aligned.len() / CHANNELS); - let take = |v: &[f32]| -> Vec { to_i16(&v[..cmp_frames * CHANNELS]) }; - let s_i = take(&source_pcm); - let o_i = take(&ours_aligned); - let r_i = take(&ref_aligned); - let (err_o, eb2_o, ef2_o) = opus_compare_err_parts(&s_i, &o_i, CHANNELS); - let (err_r, eb2_r, ef2_r) = opus_compare_err_parts(&s_i, &r_i, CHANNELS); - let nframes = ef2_o.len(); - assert_eq!(nframes, ef2_r.len(), "frame counts differ"); - - // Raw (unmasked) band energies: spectral shape + dominant-band lookup. - let as_f64 = |v: &[i16]| -> Vec { v.iter().map(|&x| x as f64).collect() }; - let mut bands_s = Vec::new(); - let mut bands_o = Vec::new(); - let mut bands_r = Vec::new(); - let mut scratch_ps = Vec::new(); - band_energy( - &as_f64(&s_i), - CHANNELS, - nframes, - &mut Some(&mut bands_s), - &mut scratch_ps, - ); - band_energy( - &as_f64(&o_i), - CHANNELS, - nframes, - &mut Some(&mut bands_o), - &mut scratch_ps, - ); - band_energy( - &as_f64(&r_i), - CHANNELS, - nframes, - &mut Some(&mut bands_r), - &mut scratch_ps, - ); - - // Oracle indices both sides; FFT frame xi -> 20 ms packet index. - let ours_ix = collect_indices(&ours_packets); - let ref_ix = collect_indices(&ref_packets); - let pkt_of = |xi: usize| xi * WIN_STEP / (FRAME * CHANNELS); - - let mut report = String::new(); - report.push_str("# reelm@12k SILK per-band divergence: ours vs ffmpeg-libopus (r2)\n"); - report.push_str("# mono, 120s, 20ms frames, VBR constrained, 48kHz, Application::Voip\n"); - report.push_str(&format!( - "# rates: ours {ours_kbps:.2} kbps, ref {ref_kbps:.2} kbps; \ - err ours={err_o:.3} ref={err_r:.3} ratio={:.2}; nframes={nframes}\n", - err_o / err_r - )); - - // (1) 21-band table: which bands carry the error. - let sum_o: f64 = eb2_o.iter().sum(); - let sum_r: f64 = eb2_r.iter().sum(); - report.push_str( - "# eb2 = band's mean share of the pre-squared frame error; \ - dln = mean ln(E_test/E_src); band i ends at CELT_EBANDS[i+1]*240 Hz\n", - ); - report.push_str("# band lo_hz hi_hz dln_o dln_r eb2_o eb2_r ratio share_o share_r\n"); - for bi in 0..NBANDS { - let (mut dol, mut drl) = (0.0f64, 0.0f64); - for xi in 0..nframes { - let sl = bands_s[(xi * NBANDS + bi) * CHANNELS].ln(); - dol += bands_o[(xi * NBANDS + bi) * CHANNELS].ln() - sl; - drl += bands_r[(xi * NBANDS + bi) * CHANNELS].ln() - sl; - } - dol /= nframes as f64; - drl /= nframes as f64; - let ratio = if eb2_r[bi] > 0.0 { - eb2_o[bi] / eb2_r[bi] - } else { - f64::INFINITY - }; - report.push_str(&format!( - "{:5} {:5} {:6} {:+.3} {:+.3} {:.3e} {:.3e} {:>7} {:5.1}% {:5.1}%\n", - bi, - CELT_EBANDS[bi] * 240, - CELT_EBANDS[bi + 1] * 240, - dol, - drl, - eb2_o[bi], - eb2_r[bi], - ratio, - 100.0 * eb2_o[bi] / sum_o, - 100.0 * eb2_r[bi] / sum_r, - )); - } - - // (2) top-15 frames by ef2(ours), with the dominant band and the oracle. - let mut by_ef2: Vec = (0..nframes).collect(); - by_ef2.sort_by(|&a, &b| ef2_o[b].partial_cmp(&ef2_o[a]).unwrap()); - report.push_str( - "\n# top-15 frames by ef2(ours) (ef2 = frame's squared opus_compare error); \ - dom = argmax_b (lnE_o - lnE_s)^2, raw bands\n", - ); - report.push_str( - "# t(s) fft pkt ef2_o ef2_r dom domband_hz | side sig qoff gains[4] nlsf_i lag cont per ltp[4] ltpscl seed bytes\n", - ); - for &xi in by_ef2.iter().take(15) { - let pkt = pkt_of(xi); - let t = (xi * WIN_STEP) as f64 / 48000.0; - let (mut dom, mut dom_v) = (0usize, -1.0f64); - for bi in 0..NBANDS { - let sl = bands_s[(xi * NBANDS + bi) * CHANNELS].ln(); - let d = bands_o[(xi * NBANDS + bi) * CHANNELS].ln() - sl; - if d * d > dom_v { - dom_v = d * d; - dom = bi; - } - } - report.push_str(&format!( - "{:7.3} {:5} {:4} {:.3e} {:.3e} {:2} {}-{}Hz\n", - t, - xi, - pkt, - ef2_o[xi], - ef2_r[xi], - dom, - CELT_EBANDS[dom] * 240, - CELT_EBANDS[dom + 1] * 240 - )); - for (side, ixv) in [(" O", ours_ix.get(pkt)), (" R", ref_ix.get(pkt))] { - match ixv { - Some((ix, bytes)) => { - let voiced = ix.signal_type == 2; - let opt = |v: String, on: bool| if on { v } else { "-".to_owned() }; - report.push_str(&format!( - " {side} sig={} qoff={} gains=[{},{},{},{}] nlsf_i={} lag={} cont={} per={} ltp=[{},{},{},{}] ltpscl={} seed={} bytes={}\n", - ix.signal_type, - ix.quant_offset_type, - ix.gains[0], - ix.gains[1], - ix.gains[2], - ix.gains[3], - ix.nlsf_interp_coef_q2, - opt(format!("{}", ix.lag_index), voiced), - opt(format!("{}", ix.contour_index), voiced), - opt(format!("{}", ix.per_index), voiced), - opt(format!("{}", ix.ltp_index[0]), voiced), - opt(format!("{}", ix.ltp_index[1]), voiced), - opt(format!("{}", ix.ltp_index[2]), voiced), - opt(format!("{}", ix.ltp_index[3]), voiced), - opt(format!("{}", ix.ltp_scale_index), voiced), - ix.seed, - bytes - )); - } - None => report.push_str(&format!(" {side} -- missing --\n")), - } - } - } - - // (3) tail vs body: how much of the total error the worst frames carry, - // and whether the 11x ratio survives de-tailing (err = (Σef2/n)^(1/16)). - let tail = |ef2: &[f64]| -> (usize, f64, f64, usize, f64) { - let mut s = ef2.to_vec(); - s.sort_by(|a, b| b.partial_cmp(a).unwrap()); - let tot: f64 = s.iter().sum(); - let k = (s.len() / 100).max(1); - let top1: f64 = s[..k].iter().sum(); - let (mut half, mut acc) = (s.len(), 0.0); - for (i, v) in s.iter().enumerate() { - acc += v; - if acc >= 0.5 * tot { - half = i + 1; - break; - } - } - (k, top1 / tot, half as f64 / s.len() as f64, half, tot) - }; - let root16 = |tot: f64, n: usize| tot.powf(1.0 / 16.0) / (n as f64).powf(1.0 / 16.0); - let (k, sh1_o, halff_o, half_o, _tot_o) = tail(&ef2_o); - let (_, sh1_r, halff_r, half_r, _tot_r) = tail(&ef2_r); - report.push_str(&format!( - "# tail: top-1% ({k} frames) carry {:.2}% of ours' Σef2 vs {:.2}% of ref's; \ - 50% of ours' err sits in the worst {half_o} frames ({:.2}%) \ - vs ref's worst {half_r} ({:.2}%)\n", - 100.0 * sh1_o, - 100.0 * sh1_r, - 100.0 * halff_o, - 100.0 * halff_r - )); - // De-tailed: drop each side's worst 50 frames (of 24k FFT frames/pkt-mapped). - let clip50 = |ef2: &[f64]| -> f64 { - let mut s = ef2.to_vec(); - s.sort_by(|a, b| b.partial_cmp(a).unwrap()); - s[50..].iter().sum() - }; - let err_o_clip = root16(clip50(&ef2_o), nframes); - let err_r_clip = root16(clip50(&ef2_r), nframes); - report.push_str(&format!( - "# de-tailed (worst 50 of {nframes} FFT frames dropped per side): \ - err ours={err_o_clip:.3} ref={err_r_clip:.3} ratio={:.2} (was {err_o:.3}/{err_r:.3}/{:.2})\n", - err_o_clip / err_r_clip, - err_o / err_r - )); - // Burst signature: per 20 ms packet, does first-subframe gain >= 60 or a - // starved packet (<= 20 bytes) line up with the packet's mean ef2? - let mut pkt_ef2 = vec![0.0f64; ours_packets.len()]; - let mut pkt_cnt = vec![0u32; ours_packets.len()]; - // Index loop kept: the index also drives other lookups or parallel arrays. - #[allow(clippy::needless_range_loop)] - for xi in 0..nframes { - let p = pkt_of(xi).min(pkt_ef2.len() - 1); - pkt_ef2[p] += ef2_o[xi]; - pkt_cnt[p] += 1; - } - let mut g_hi = (0.0f64, 0usize); // (sum, count) packets with gains[0] >= 60 - let mut g_lo = (0.0f64, 0usize); - let mut b_lo = (0.0f64, 0usize); // bytes <= 20 - let mut b_hi = (0.0f64, 0usize); - for (i, (ix, bytes)) in ours_ix.iter().enumerate() { - if i >= pkt_ef2.len() { - break; - } - let mean = if pkt_cnt[i] > 0 { - pkt_ef2[i] / pkt_cnt[i] as f64 - } else { - 0.0 - }; - if ix.gains[0] >= 60 { - g_hi.0 += mean; - g_hi.1 += 1; - } else { - g_lo.0 += mean; - g_lo.1 += 1; - } - if *bytes <= 20 { - b_lo.0 += mean; - b_lo.1 += 1; - } else { - b_hi.0 += mean; - b_hi.1 += 1; - } - } - report.push_str(&format!( - "# burst signature: packets with gains[0]>=60: {}/{}, mean ef2 {:.3e}; \ - gains[0]<60: mean ef2 {:.3e} || packets <=20 bytes: {}/{}, mean ef2 {:.3e}; \ - >20 bytes: mean ef2 {:.3e}\n", - g_hi.1, - g_hi.1 + g_lo.1, - if g_hi.1 > 0 { - g_hi.0 / g_hi.1 as f64 - } else { - f64::NAN - }, - if g_lo.1 > 0 { - g_lo.0 / g_lo.1 as f64 - } else { - f64::NAN - }, - b_lo.1, - b_lo.1 + b_hi.1, - if b_lo.1 > 0 { - b_lo.0 / b_lo.1 as f64 - } else { - f64::NAN - }, - if b_hi.1 > 0 { - b_hi.0 / b_hi.1 as f64 - } else { - f64::NAN - }, - )); - - let out_path = lanes_dir.join("opus-silkq-r2.bands.txt"); - fs::write(&out_path, &report).unwrap(); - println!("wrote {}", out_path.display()); - print!("{}", report); -} - -// --------------------------------------------------------------------------- -// Harness: feed identical raw PCM (.sw, s16le interleaved) to our opus_compare -// so it can be checked against the C `opus_compare` tool on the SAME bytes. -// Run: SW_REF=a.sw SW_TEST=b.sw SW_CH=2 cargo test -p ec-opus --release \ -// opus_compare_harness -- --ignored --nocapture -// --------------------------------------------------------------------------- -#[test] -#[ignore = "probe: needs hand-supplied SW_REF/SW_TEST .sw files to cross-check our opus_compare against the C tool; asserts nothing without those env vars"] -fn opus_compare_harness() { - let _timing = timing_shared(); - let ref_path = std::env::var("SW_REF").expect("SW_REF"); - let test_path = std::env::var("SW_TEST").expect("SW_TEST"); - let channels: usize = std::env::var("SW_CH") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(2); - let x = read_i16(Path::new(&ref_path)); - let y = read_i16(Path::new(&test_path)); - assert_eq!( - x.len(), - y.len(), - "sample counts differ: {} ({} samples) vs {} ({} samples)", - ref_path, - x.len() / channels, - test_path, - y.len() / channels - ); - let err = opus_compare_err(&x, &y, channels); - let q = opus_compare(&x, &y, channels); - println!( - "HARNESS err={err:.6} Q={q:.4} ch={channels} n={}", - x.len() / channels - ); -} - -// --------------------------------------------------------------------------- -// Harness: read a source .sw, encode via ec-opus at SW_KBPS, decode, align, -// write the aligned decoded pair to SW_OUT_SRC / SW_OUT_DEC (.sw s16le), and -// print our opus_compare err/Q. The dumped .sw files can then be fed to the C -// `opus_compare` tool on IDENTICAL bytes for a byte-exact cross-check. -// Run: SW_SRC=in.sw SW_KBPS=96 SW_OUT_SRC=as.sw SW_OUT_DEC=ad.sw \ -// cargo test -p ec-opus --release opus_compare_harness_ours -- --ignored --nocapture -// --------------------------------------------------------------------------- -#[test] -#[ignore = "probe: needs hand-supplied SW_SRC/SW_KBPS/SW_OUT_SRC/SW_OUT_DEC to round-trip a .sw through our encoder; only writes .sw dumps, asserts nothing"] -fn opus_compare_harness_ours() { - let _timing = timing_shared(); - let src_path = std::env::var("SW_SRC").expect("SW_SRC"); - let kbps: u32 = std::env::var("SW_KBPS") - .ok() - .and_then(|s| s.parse().ok()) - .expect("SW_KBPS"); - let channels: usize = std::env::var("SW_CH") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(2); - let out_src = std::env::var("SW_OUT_SRC").expect("SW_OUT_SRC"); - let out_dec = std::env::var("SW_OUT_DEC").expect("SW_OUT_DEC"); - - let src_i16 = read_i16(Path::new(&src_path)); - let src_f32: Vec = src_i16.iter().map(|&v| v as f32 / 32768.0).collect(); - let mut enc = Encoder::new(48000, channels, Application::Audio).expect("encoder"); - enc.set_bitrate(kbps * 1000); - enc.set_vbr_constrained(true); - let (dec_f32, _bytes) = roundtrip_own(&mut enc, &src_f32, channels, 960); - let (lag, aligned) = align_to_source(&src_f32, &dec_f32, channels, 2000); - // Trim both to the common aligned length. - let n = (src_f32.len() / channels).min(aligned.len() / channels); - let mut s_i16 = vec![0i16; n * channels]; - let mut d_i16 = vec![0i16; n * channels]; - for i in 0..n { - for ch in 0..channels { - s_i16[i * channels + ch] = (src_f32[i * channels + ch] * 32768.0) - .round() - .clamp(-32768.0, 32767.0) as i16; - d_i16[i * channels + ch] = (aligned[i * channels + ch] * 32768.0) - .round() - .clamp(-32768.0, 32767.0) as i16; - } - } - fs::write(&out_src, bytemap(&s_i16)).unwrap(); - fs::write(&out_dec, bytemap(&d_i16)).unwrap(); - let err = opus_compare_err(&s_i16, &d_i16, channels); - let q = opus_compare(&s_i16, &d_i16, channels); - let c = corr_interleaved(&src_f32[..n * channels], &aligned, channels); - println!("HARNESS_OURS lag={lag} corr={c:.4} err={err:.6} Q={q:.4} kbps={kbps} n={n}"); -} - -fn bytemap(p: &[i16]) -> Vec { - let mut b = Vec::with_capacity(p.len() * 2); - for &v in p { - b.extend_from_slice(&v.to_le_bytes()); - } - b -} - -/// Self-contained regression guard for `opus_compare_err` / `opus_compare`. -/// -/// The pinned numbers below were cross-validated against the reference C -/// `opus_compare` tool (built from `opus_compare.c`) on byte-identical raw -/// PCM, so they encode the spectral error algorithm's expected output, not -/// any particular codec. Two cases: -/// * identical signals -> C err=0.000000, Q=100.0 (exact) -/// * mild perturbation -> C err=4.444987, Q=-593.31 (exact to 6 dp) -/// -/// The perturbation case sits in the practical error range (same band as the -/// real-audio validation pairs); the identical case pins the zero-error path -/// with no floating-point tolerance. No audio files or external tools needed. -#[test] -fn opus_compare_err_pinned_against_c() { - let _timing = timing_shared(); - const N: usize = 48000 * 4; // 4 s per channel - let t: Vec = (0..N).map(|i| i as f64 / 48000.0).collect(); - - let base = |c: usize| -> Vec { - let ph = 0.5 * c as f64; - let ph2 = 0.3 * c as f64; - t.iter() - .map(|&tt| { - 0.3 * (2.0 * std::f64::consts::PI * 440.0 * tt).sin() - + 0.2 * (2.0 * std::f64::consts::PI * 442.0 * tt + ph).sin() - + 0.15 * (2.0 * std::f64::consts::PI * (800.0 + 200.0 * tt) * tt + ph2).sin() - }) - .collect() - }; - let to_i16s = |sig: &[f64]| -> Vec { - sig.iter() - .map(|&v| (v.clamp(-1.0, 1.0) * 32767.0) as i16) - .collect() - }; - let stereo = |l: &[f64], r: &[f64]| -> Vec { - let mut o = Vec::with_capacity(N * 2); - let li = to_i16s(l); - let ri = to_i16s(r); - for i in 0..N { - o.push(li[i]); - o.push(ri[i]); - } - o - }; - - let b0 = base(0); - let b1 = base(1); - - // Case 1: identical -> zero error, Q=100 (exact, no tolerance). - let a = stereo(&b0, &b1); - let err_id = opus_compare_err(&a, &a, 2); - let q_id = opus_compare(&a, &a, 2); - assert_eq!(err_id, 0.0, "identical signals must give err=0"); - assert_eq!(q_id, 100.0, "identical signals must give Q=100"); + // Case 1: identical -> zero error, Q=100 (exact, no tolerance). + let a = stereo(&b0, &b1); + let err_id = opus_compare_err(&a, &a, 2); + let q_id = opus_compare(&a, &a, 2); + assert_eq!(err_id, 0.0, "identical signals must give err=0"); + assert_eq!(q_id, 100.0, "identical signals must give Q=100"); // Case 2: mild perturbation (+0.5 dB on L, quiet 1500 Hz partial on L). let gain = 10f64.powf(0.5 / 10.0); @@ -4401,611 +2697,3 @@ fn opus_compare_err_pinned_against_c() { "pinned Q drift: got {q:.4}, expected -593.31 (C-validated)" ); } - -/// libopus CELT band edges (copy of `celt.rs::E_BANDS`, which is pub(crate)): -/// band `i` ends at `CELT_EBANDS[i] * 240` Hz at 48 kHz. -const CELT_EBANDS: [usize; NBANDS + 1] = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100, -]; - -/// Startup leak repro (lane-opus-reell): the first frames of the reell source -/// (digital silence then an attack) through the library gate's encoder -/// settings and our decoder. Prints per-frame CELT facts; fails if the decode -/// peak exceeds 4x the input peak in any frame. -#[test] -fn celt_silence_then_attack_decodes_bounded() { - let _timing = timing_shared(); - let fs = 960usize; - let ch = 2usize; - let src = shellexpand("~/Music/reell.mp4"); - if !src.exists() { - eprintln!("SKIP: missing {}", src.display()); - return; - } - let pcm = ffmpeg_decode_pcm(&src, 1.0); - let mut enc = Encoder::new(48000, ch, Application::Audio).unwrap(); - enc.set_bitrate(96_000); - enc.set_vbr_constrained(true); - let mut dec = Decoder::new(48000, ch).unwrap(); - let mut bad = Vec::new(); - for frame in 0..12 { - let slice = &pcm[frame * fs * ch..(frame + 1) * fs * ch]; - let in_peak = slice.iter().fold(0f32, |a, &x| a.max(x.abs())); - let pcm_i16 = to_i16(slice); - let mut buf = [0u8; 1500]; - let n = enc.encode(&pcm_i16, fs, &mut buf).unwrap(); - let mut out = vec![0f32; fs * ch]; - let got = dec.decode_float(&buf[..n], &mut out).unwrap(); - let d = dec.last_celt_diag().clone(); - let peak = out[..got * ch].iter().fold(0f32, |a, &x| a.max(x.abs())); - let emax = d.old_band_e.iter().cloned().fold(f32::MIN, f32::max); - println!( - "frame {frame}: in_peak {in_peak:.5} bytes {n} dec(sil {} intra {} trans {} bits {}) bandE max {emax:.2} peak {peak:.5}", - d.silence, d.intra, d.transient, d.total_bits - ); - if peak > 4.0 * in_peak.max(1e-4) { - bad.push(frame); - } - } - assert!(bad.is_empty(), "decode peak >4x input in frames {bad:?}"); -} - -/// Per-frame allocation diagnostics for SHORT-block (transient) frames at a -/// fixed bitrate: decodes both our stream and libopus's with our decoder, then -/// prints per-band mean pulses, fine_quant, alloc_trim, coded_bands, intensity, -/// dual_stereo share, spread/tf histograms, total_bits — ours vs ref, split by -/// the decoder's transient flag. Output: `lanes/opus-sb-r1.bits.txt`. -#[test] -#[ignore = "probe: per-frame short-block allocation dump over the local corpus; a multi-minute ffmpeg report run, not a suite gate"] -fn short_block_bits_vs_libopus() { - let _timing = timing_shared(); - const SECS: f64 = 120.0; - const FRAME: usize = 960; - const CHANNELS: usize = 2; - let kbps_env: u32 = std::env::var("SWEEP_KBPS") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(64); - #[allow(non_snake_case)] - let KBPS: u32 = kbps_env; - - let all: &[(&str, &str)] = &[ - ("reell", "~/Music/reell.mp4"), - ("dl8a", "~/Downloads/8a3b6d1d19.mp3"), - ("her", "~/Music/reeli.mp3"), - ("reelm", "~/Music/reelm.wav"), - ("hein", "~/Downloads/reelm.mp3"), - ]; - let only: Vec = std::env::var("SWEEP_ONLY") - .unwrap_or_else(|_| "reelm,hein".to_owned()) - .split(',') - .filter(|s| !s.is_empty()) - .map(|s| s.trim().to_owned()) - .collect(); - let sources: Vec<(String, PathBuf)> = all - .iter() - .filter(|(tag, _)| only.iter().any(|o| o == tag)) - .map(|(tag, p)| (tag.to_string(), shellexpand(p))) - .collect(); - assert!(!sources.is_empty(), "SWEEP_ONLY matched no sources"); - - let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes"); - fs::create_dir_all(&lanes_dir).unwrap(); - let out_path = lanes_dir.join("opus-sb-r1.bits.txt"); - let scratch = lanes_dir.join("opus-sb-r1.scratch.ogg"); - let nb = ec_opus::celt::NB_BANDS; - let mut report = String::new(); - - for (tag, src) in &sources { - if !src.exists() { - eprintln!("SKIP {tag}: missing {}", src.display()); - continue; - } - let source_pcm = ffmpeg_decode_pcm(src, SECS); - let seconds = source_pcm.len() as f64 / CHANNELS as f64 / 48000.0; - - // Reference: ffmpeg libopus at KBPS, VBR. - ffmpeg_encode_libopus(src, KBPS, &scratch, SECS); - let ref_bytes = fs::metadata(&scratch) - .map(|m| m.len() as usize) - .unwrap_or(0); - let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0; - let ref_pkts: Vec> = ogg_packets(&fs::read(&scratch).unwrap()) - .into_iter() - .skip(2) - .collect(); - - // Decode ref packets with our decoder, capture per-frame CELT diag. - let mut ref_diags: Vec = Vec::new(); - { - let mut d = Decoder::new(48000, CHANNELS).unwrap(); - let mut buf = vec![0.0f32; 5760 * CHANNELS]; - for p in &ref_pkts { - if p.is_empty() { - continue; - } - let toc = ec_opus::Toc::new(p[0]); - if d.decode_float(p, &mut buf).is_ok() && toc.mode() != Mode::Silk { - ref_diags.push(d.last_celt_diag().clone()); - } - } - } - - // Ours at the reference's realised rate. - let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder"); - enc.set_bitrate((ref_kbps * 1000.0).round() as u32); - enc.set_vbr_constrained(true); - let mut dec = Decoder::new(48000, CHANNELS).unwrap(); - let mut packet = vec![0u8; 1500]; - let mut dbuf = vec![0.0f32; 5760 * CHANNELS]; - let mut ours_diags: Vec = Vec::new(); - let mut ours_bytes = 0usize; - for block in source_pcm.chunks(FRAME * CHANNELS) { - let mut padded = block.to_vec(); - padded.resize(FRAME * CHANNELS, 0.0); - let len = enc - .encode_float(&padded, FRAME, &mut packet) - .expect("encode"); - ours_bytes += len; - let toc = ec_opus::Toc::new(packet[0]); - if dec.decode_float(&packet[..len], &mut dbuf).is_ok() && toc.mode() != Mode::Silk { - ours_diags.push(dec.last_celt_diag().clone()); - } - } - let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0; - - report.push_str(&format!( - "\n# source {tag} @{KBPS}k: ours {ours_kbps:.1} kbps, ref {ref_kbps:.1} kbps; \ - ours_celt {} frames, ref_celt {} frames\n", - ours_diags.len(), - ref_diags.len() - )); - - for (label, is_trans) in [("LONG", false), ("SHORT", true)] { - let ours_t: Vec<&ec_opus::celt::CeltDecDiag> = ours_diags - .iter() - .filter(|d| d.transient == is_trans) - .collect(); - let ref_t: Vec<&ec_opus::celt::CeltDecDiag> = ref_diags - .iter() - .filter(|d| d.transient == is_trans) - .collect(); - let on = ours_t.len(); - let rn = ref_t.len(); - if on == 0 && rn == 0 { - continue; - } - report.push_str(&format!("## {label}: ours {on} frames, ref {rn} frames\n")); - - // Per-band mean pulses. - report.push_str("# mean pulses per band (ours / ref)\n"); - report.push_str("# band_hz\tours\tref\tdiff\n"); - // Index loop kept: the index also drives other lookups or parallel arrays. - #[allow(clippy::needless_range_loop)] - for i in 0..nb { - let om: f64 = - ours_t.iter().map(|d| d.pulses[i] as f64).sum::() / on.max(1) as f64; - let rm: f64 = - ref_t.iter().map(|d| d.pulses[i] as f64).sum::() / rn.max(1) as f64; - report.push_str(&format!( - "{}\t{:.1}\t{:.1}\t{:.1}\n", - CELT_EBANDS[i] * 240, - om, - rm, - om - rm - )); - } - - // Per-band mean fine_quant. - report.push_str("# mean fine_quant per band (ours / ref)\n"); - report.push_str("# band_hz\tours\tref\n"); - // Index loop kept: the index also drives other lookups or parallel arrays. - #[allow(clippy::needless_range_loop)] - for i in 0..nb { - let om: f64 = - ours_t.iter().map(|d| d.fine_quant[i] as f64).sum::() / on.max(1) as f64; - let rm: f64 = - ref_t.iter().map(|d| d.fine_quant[i] as f64).sum::() / rn.max(1) as f64; - report.push_str(&format!("{}\t{:.2}\t{:.2}\n", CELT_EBANDS[i] * 240, om, rm)); - } - - // Aggregate stats. - let mean = |v: &[&ec_opus::celt::CeltDecDiag], - f: &dyn Fn(&ec_opus::celt::CeltDecDiag) -> f64| - -> f64 { - v.iter().map(|d| f(d)).sum::() / v.len().max(1) as f64 - }; - let mean_band_hz = |v: &[&ec_opus::celt::CeltDecDiag], - f: &dyn Fn(&ec_opus::celt::CeltDecDiag) -> usize| - -> f64 { - let m = v.iter().map(|d| f(d)).sum::() / v.len().max(1); - CELT_EBANDS[m] as f64 * 240.0 - }; - let dual_share = |v: &[&ec_opus::celt::CeltDecDiag]| -> f64 { - v.iter().filter(|d| d.dual_stereo).count() as f64 / v.len().max(1) as f64 - }; - let fmt_hist = |h: [usize; 4]| -> String { - h.iter() - .map(|x| x.to_string()) - .collect::>() - .join(", ") - }; - let spread_hist = |v: &[&ec_opus::celt::CeltDecDiag]| -> [usize; 4] { - let mut h = [0usize; 4]; - for d in v { - h[d.spread.min(3)] += 1; - } - h - }; - let tf_hist = |v: &[&ec_opus::celt::CeltDecDiag]| -> [usize; 4] { - let mut h = [0usize; 4]; - for d in v { - for &t in &d.tf_res { - h[(t + 1).clamp(0, 3) as usize] += 1; - } - } - h - }; - - let trim_hist = |v: &[&ec_opus::celt::CeltDecDiag]| -> [usize; 11] { - let mut h = [0usize; 11]; - for d in v { - h[d.alloc_trim.clamp(0, 10) as usize] += 1; - } - h - }; - report.push_str(&format!( - "# alloc_trim hist [0..10]: ours {:?} ref {:?}\n", - trim_hist(&ours_t), - trim_hist(&ref_t) - )); - report.push_str("# mean dynalloc boost per band (1/8 bit) ours / ref\n"); - // Index loop kept: the index also drives other lookups or parallel arrays. - #[allow(clippy::needless_range_loop)] - for b in 0..nb { - let mo = mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| { - d.offsets[b] as f64 - }); - let mr = mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| { - d.offsets[b] as f64 - }); - if mo != 0.0 || mr != 0.0 { - report.push_str(&format!("{}\t{:.1}\t{:.1}\n", CELT_EBANDS[b] * 240, mo, mr)); - } - } - report.push_str(&format!( - "# alloc_trim mean: ours {:.2} ref {:.2}\n", - mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.alloc_trim - as f64), - mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.alloc_trim - as f64), - )); - report.push_str(&format!( - "# coded_bands mean Hz: ours {:.0} ref {:.0}\n", - mean_band_hz(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.coded_bands), - mean_band_hz(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.coded_bands), - )); - report.push_str(&format!( - "# intensity mean Hz: ours {:.0} ref {:.0}\n", - mean_band_hz(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.intensity), - mean_band_hz(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.intensity), - )); - report.push_str(&format!( - "# dual_stereo share: ours {:.3} ref {:.3}\n", - dual_share(&ours_t), - dual_share(&ref_t), - )); - report.push_str(&format!( - "# total_bits mean: ours {:.0} ref {:.0}\n", - mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.total_bits - as f64), - mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.total_bits - as f64), - )); - report.push_str(&format!( - "# balance mean: ours {:.0} ref {:.0}\n", - mean(&ours_t, &|d: &ec_opus::celt::CeltDecDiag| d.balance as f64), - mean(&ref_t, &|d: &ec_opus::celt::CeltDecDiag| d.balance as f64), - )); - report.push_str(&format!( - "# spread hist [0..3]: ours [{}] ref [{}]\n", - fmt_hist(spread_hist(&ours_t)), - fmt_hist(spread_hist(&ref_t)), - )); - report.push_str(&format!( - "# tf_res hist [-1..2]: ours [{}] ref [{}]\n", - fmt_hist(tf_hist(&ours_t)), - fmt_hist(tf_hist(&ref_t)), - )); - } - } - - fs::write(&out_path, &report).unwrap(); - eprintln!("wrote {}", out_path.display()); -} - -// --------------------------------------------------------------------------- -// opus_compare error map, any gate source (lane opus-her r1, generalised r3). -// -// Source/rate/tag come from EC_ERRMAP_SRC / EC_ERRMAP_KBPS / EC_ERRMAP_TAG -// (default: her@96, the row this was first written for). This localises it: both encoders run through -// the gate's exact path, opus_compare's per-2.5 ms hop ef² is bucketed into -// 1 s windows, and the top-10 windows (by ours/ref window ratio and by ours -// error share) are printed with our encoder flags plus both encoders' coded -// decisions — libopus's packets decoded with our decoder, the reell-r2 method. -// Frame mapping is in source-sample time (±1 frame of codec delay). -// Output: lanes/.map.txt (default `opus-her-r1`). HER_KBPS (or -// EC_ERRMAP_KBPS) overrides the rate, EC_ERRMAP_SRC the source file: the map is -// the same analysis for any row of the library gate, not just her@96. -// --------------------------------------------------------------------------- - -/// Per-frame ours-vs-libopus coded decisions over a window of frames, decoded -/// with our own decoder on both sides. FRAME_SRC / FRAME_KBPS / FRAME_FROM / -/// FRAME_TO pick the source, rate and frame range (diagnostic). -#[test] -#[ignore = "probe: FRAME_SRC/FRAME_FROM/FRAME_TO-driven per-frame decision dump; returns silently when FRAME_SRC is missing, so it can never be a suite gate"] -fn frame_decisions_vs_libopus() { - let _timing = timing_shared(); - const CH: usize = 2; - let src_s = std::env::var("FRAME_SRC").unwrap_or_else(|_| "~/Music/reell.mp4".into()); - let src = shellexpand(&src_s); - if !src.exists() { - eprintln!("SKIP: missing {}", src.display()); - return; - } - let kbps: u32 = std::env::var("FRAME_KBPS") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(64); - let from: usize = std::env::var("FRAME_FROM") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(0); - let to: usize = std::env::var("FRAME_TO") - .ok() - .and_then(|v| v.parse().ok()) - .unwrap_or(6); - let secs = (to as f64 * 0.02 + 1.0).max(2.0); - let pcm = ffmpeg_decode_pcm(&src, secs); - let scratch = std::env::temp_dir().join("ec-opus-frame-dec.opus"); - ffmpeg_encode_libopus(&src, kbps, &scratch, secs); - let ref_pkts: Vec> = ogg_packets(&fs::read(&scratch).unwrap()) - .into_iter() - .skip(2) - .collect(); - - let show = |tag: &str, f: usize, bytes: usize, d: &ec_opus::celt::CeltDecDiag| { - let e: Vec = d.old_band_e[..NB_BANDS_DIAG] - .iter() - .map(|v| format!("{v:.1}")) - .collect(); - println!( - "f{f} {tag}: bytes {bytes} sil {} intra {} trans {} ac {} trim {} spread {} cb {} \ - tf {:?} pulses {:?} fine {:?} E {}", - d.silence, - d.intra, - d.transient, - d.anti_collapse, - d.alloc_trim, - d.spread, - d.coded_bands, - &d.tf_res[..NB_BANDS_DIAG], - &d.pulses[..NB_BANDS_DIAG], - &d.fine_quant[..NB_BANDS_DIAG], - e.join(",") - ); - }; - - let mut d = Decoder::new(48000, CH).unwrap(); - let mut buf = vec![0.0f32; 5760 * CH]; - let mut ref_rows = Vec::new(); - for p in ref_pkts.iter().take(to) { - let ok = !p.is_empty() - && ec_opus::Toc::new(p[0]).mode() != Mode::Silk - && d.decode_float(p, &mut buf).is_ok(); - ref_rows.push(if ok { - Some((p.len(), d.last_celt_diag().clone())) - } else { - None - }); - } - - // Encode at the reference's REALISED rate, like the library gate does: - // ffmpeg's libopus overshoots its -b:a target by up to 12% on these - // sources, and a flat target makes every byte column meaningless. - let ref_bytes: usize = ref_pkts.iter().take(to).map(Vec::len).sum(); - let ref_kbps = ref_bytes as f64 * 8.0 / (ref_pkts.len().min(to) as f64 * 0.02) / 1000.0; - println!("ffmpeg target {kbps} kbps, realised {ref_kbps:.1} kbps"); - let mut enc = Encoder::new(48000, CH, Application::Audio).unwrap(); - enc.set_bitrate((ref_kbps * 1000.0).round() as u32); - enc.set_vbr_constrained(true); - let mut dec = Decoder::new(48000, CH).unwrap(); - let mut out = vec![0u8; 1500]; - let mut ours_rows = Vec::new(); - for block in pcm.as_chunks::<{ 960 * CH }>().0.iter().take(to) { - let n = enc.encode_float(block, 960, &mut out).unwrap(); - let ok = ec_opus::Toc::new(out[0]).mode() != Mode::Silk - && dec.decode_float(&out[..n], &mut buf).is_ok(); - ours_rows.push(if ok { - Some((n, dec.last_celt_diag().clone())) - } else { - None - }); - } - - if to - from <= 40 { - for f in from..to { - match ours_rows.get(f).and_then(|x| x.as_ref()) { - Some((n, d)) => show("ours", f, *n, d), - None => println!("f{f} ours: (silk/absent)"), - } - match ref_rows.get(f).and_then(|x| x.as_ref()) { - Some((n, d)) => show("ref ", f, *n, d), - None => println!("f{f} ref : (silk/absent)"), - } - } - } - - // Aggregate over the frames BOTH sides coded as CELT, split by whether - // either side called the frame transient: which coded decision differs. - let mut agg = [(0usize, [0.0f64; 8]); 2]; - let mut trans_diff = 0usize; - for f in from..to { - let (Some((no, o)), Some((nr, r))) = ( - ours_rows.get(f).and_then(|x| x.as_ref()), - ref_rows.get(f).and_then(|x| x.as_ref()), - ) else { - continue; - }; - if o.transient != r.transient { - trans_diff += 1; - } - let slot = usize::from(o.transient || r.transient); - let tf = |d: &ec_opus::celt::CeltDecDiag| { - d.tf_res[..NB_BANDS_DIAG].iter().sum::() as f64 / NB_BANDS_DIAG as f64 - }; - let a = &mut agg[slot]; - a.0 += 1; - for (k, v) in [ - *no as f64, - *nr as f64, - o.alloc_trim as f64, - r.alloc_trim as f64, - tf(o), - tf(r), - f64::from(u8::from(o.anti_collapse)), - f64::from(u8::from(r.anti_collapse)), - ] - .into_iter() - .enumerate() - { - a.1[k] += v; - } - } - println!("frames {from}..{to}, transient-flag disagreements {trans_diff}"); - for (slot, name) in [(1usize, "transient"), (0, "steady ")] { - let (n, v) = agg[slot]; - if n == 0 { - continue; - } - let m = |k: usize| v[k] / n as f64; - println!( - "{name} n={n}: bytes o {:.1} r {:.1} | trim o {:.2} r {:.2} | mean tf_res o {:.3} \ - r {:.3} | anti_collapse o {:.2} r {:.2}", - m(0), - m(1), - m(2), - m(3), - m(4), - m(5), - m(6), - m(7) - ); - } -} - -const NB_BANDS_DIAG: usize = ec_opus::celt::NB_BANDS; - -// --------------------------------------------------------------------------- -// Rate against the target: the CBR default must land within 5% of the bitrate -// asked for, on stereo music and speech. -// --------------------------------------------------------------------------- - -/// Encodes each corpus source at 32, 64 and 128 kbps (default CBR), decodes it -/// with our decoder, and asserts the realised rate is within 5% of the target and -/// that no CBR packet exceeds its byte budget (the D2b packet budget). Speech is -/// coded in Voip mode, where SILK packets come from. Corpus-backed like the -/// library gates: `cargo test --release -p ec-opus --test conformance -/// encoder_rate_target_gate -- --ignored --nocapture` with the sources in place. -#[test] -#[ignore = "corpus gate: needs ffmpeg and the ~/Music, ~/Downloads sources (about 3 min)"] -fn encoder_rate_target_gate() { - let _timing = timing_shared(); - const SECS: f64 = 120.0; - const FRAME: usize = 960; // 20 ms at 48 kHz - const CHANNELS: usize = 2; - const MAX_LAG: usize = 2000; - let sources: &[(&str, &str, &str)] = &[ - ("nik", "music", "~/Music/reeln.mp4"), - ("reelo", "music", "~/Music/reelo.mp3"), - ("her", "music", "~/Music/reeli.mp3"), - ("reell", "music", "~/Music/reell.mp4"), - ("hein", "speech", "~/Downloads/reelm.mp3"), - ]; - let mut rows = Vec::new(); - let mut violations = Vec::new(); - for &(tag, kind, path) in sources { - let src = shellexpand(path); - if !src.exists() { - eprintln!("SKIP {tag}: missing {}", src.display()); - continue; - } - let pcm = ffmpeg_decode_pcm(&src, SECS); - let frames = pcm.len() / CHANNELS; - assert!(frames > 48_000, "{tag}: source too short"); - let seconds = frames as f64 / 48000.0; - for &kbps in &[32u32, 64, 128] { - // Speech goes through Voip, which is where SILK packets come from. - let app = if kind == "speech" { - Application::Voip - } else { - Application::Audio - }; - let mut enc = Encoder::new(48000, CHANNELS, app).expect("encoder"); - enc.set_bitrate(kbps * 1000); - // CBR packet budget, as the encoder derives it (payload bytes). - let budget = - ((kbps as u64 * 1000 * FRAME as u64 + 4 * 48000) / (8 * 48000)) as usize - 1; - let mut dec = Decoder::new(48000, CHANNELS).unwrap(); - let mut out = vec![0u8; 1500]; - let mut buf = vec![0.0f32; 5760 * CHANNELS]; - let mut decoded = Vec::new(); - let mut bytes = 0usize; - let (mut over, mut under) = (0usize, 0usize); - let mut padded = Vec::new(); - for block in pcm.chunks(FRAME * CHANNELS) { - let block = if block.len() < FRAME * CHANNELS { - padded.clear(); - padded.extend_from_slice(block); - padded.resize(FRAME * CHANNELS, 0.0); - &padded[..] - } else { - block - }; - let len = enc.encode_float(block, FRAME, &mut out).expect("encode"); - bytes += len; - let payload = len - 1; - over += usize::from(payload > budget); - under += usize::from(payload < budget); - let n = dec.decode_float(&out[..len], &mut buf).expect("decode"); - decoded.extend_from_slice(&buf[..n * CHANNELS]); - } - let real = bytes as f64 * 8.0 / seconds / 1000.0; - let pct = (real / kbps as f64 - 1.0) * 100.0; - let (_, aligned) = align_to_source(&pcm, &decoded, CHANNELS, MAX_LAG); - let cmp = (pcm.len().min(aligned.len())) / CHANNELS * CHANNELS; - let q = opus_compare(&to_i16(&pcm[..cmp]), &to_i16(&aligned[..cmp]), CHANNELS); - println!( - "{tag} ({kind}) @{kbps}k: realised {real:.2} kbps ({pct:+.2}%), Q {q:.2}, \ - budget {budget} B: {over} over, {under} under" - ); - if pct.abs() > 5.0 { - violations.push(format!("{tag} ({kind}) @{kbps}k: {pct:+.2}% (|>5%|)")); - } - if over > 0 { - violations.push(format!( - "{tag} ({kind}) @{kbps}k: {over} packets over the {budget} B budget" - )); - } - rows.push(format!( - "{tag}\t{kind}\t{kbps}\t{real:.2}\t{pct:+.2}\t{q:.2}\t{over}\t{under}" - )); - } - } - assert!(!rows.is_empty(), "no rate rows: no corpus source present"); - assert!( - violations.is_empty(), - "rate or packet budget violated:\n{}", - violations.join("\n") - ); -} diff --git a/crates/ec-pcm-ext/Cargo.toml b/crates/ec-pcm-ext/Cargo.toml index fd1f3de6..5a802fb8 100644 --- a/crates/ec-pcm-ext/Cargo.toml +++ b/crates/ec-pcm-ext/Cargo.toml @@ -10,5 +10,6 @@ authors.workspace = true ec-core = { workspace = true } [dev-dependencies] +ec-testkit.workspace = true ec-mp4 = { workspace = true } ec-riff = { workspace = true } diff --git a/crates/ec-pcm-ext/tests/oracle.rs b/crates/ec-pcm-ext/tests/oracle.rs index de2992c8..1d467fa0 100644 --- a/crates/ec-pcm-ext/tests/oracle.rs +++ b/crates/ec-pcm-ext/tests/oracle.rs @@ -1,31 +1,17 @@ //! Bit-exact oracle: fixtures are generated with ffmpeg from synthetic lavfi //! sources, decoded here and by ffmpeg (`-f s16le`), and must match exactly. //! -//! Without ffmpeg the tests skip loudly; with `EC_REQUIRE_FIXTURES=1` a -//! missing ffmpeg is a failure. +//! Needs ffmpeg; a missing one fails. use std::fs::File; use std::io::BufReader; use std::path::{Path, PathBuf}; -use std::process::Command; -use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Demuxer, MediaParameters}; use ec_core::frame::{ChannelLayout, SampleFormat}; use ec_core::packet::Buf; +use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Demuxer, MediaParameters}; use ec_pcm_ext::PcmExtDecoder; -fn have_ffmpeg() -> bool { - let ok = Command::new("ffmpeg").arg("-version").output().is_ok(); - if !ok { - assert!( - std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "EC_REQUIRE_FIXTURES=1 but ffmpeg is not installed" - ); - eprintln!("ffmpeg absent - skipping"); - } - ok -} - fn tmpdir(tag: &str) -> PathBuf { let d = std::env::temp_dir().join(format!("ec-pcm-ext-{tag}-{}", std::process::id())); std::fs::create_dir_all(&d).expect("tmp"); @@ -35,9 +21,7 @@ fn tmpdir(tag: &str) -> PathBuf { /// Synthetic source: `kind` 0 = tones with a chirp, 1 = noise. fn source(kind: u32, channels: u32, rate: u32) -> String { match (kind, channels) { - (0, 1) => format!( - "aevalsrc='0.6*sin(2*PI*440*t)+0.25*sin(2*PI*1234*t*t)':s={rate}:d=1.3" - ), + (0, 1) => format!("aevalsrc='0.6*sin(2*PI*440*t)+0.25*sin(2*PI*1234*t*t)':s={rate}:d=1.3"), (0, _) => format!( "aevalsrc='0.6*sin(2*PI*440*t)+0.25*sin(2*PI*1234*t*t)|0.5*sin(2*PI*660*t)':s={rate}:d=1.3" ), @@ -51,21 +35,27 @@ fn source(kind: u32, channels: u32, rate: u32) -> String { fn make(dir: &Path, name: &str, codec: &str, kind: u32, channels: u32, rate: u32) -> PathBuf { let out = dir.join(name); let src = source(kind, channels, rate); - let mut cmd = Command::new("ffmpeg"); + let mut cmd = ec_testkit::ffmpeg(); cmd.args(["-nostdin", "-y", "-v", "error", "-f", "lavfi"]); if src.contains(';') { - cmd.args(["-i", "anullsrc=d=0.01", "-filter_complex"]).arg(&src); + cmd.args(["-i", "anullsrc=d=0.01", "-filter_complex"]) + .arg(&src); } else { cmd.arg("-i").arg(&src); } - cmd.args(["-ac", &channels.to_string(), "-c:a", codec]).arg(&out); + cmd.args(["-ac", &channels.to_string(), "-c:a", codec]) + .arg(&out); let o = cmd.output().expect("ffmpeg"); - assert!(o.status.success(), "{name}: {}", String::from_utf8_lossy(&o.stderr)); + assert!( + o.status.success(), + "{name}: {}", + String::from_utf8_lossy(&o.stderr) + ); out } fn ffmpeg_pcm(path: &Path) -> Vec { - let o = Command::new("ffmpeg") + let o = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-i"]) .arg(path) .args(["-f", "s16le", "-"]) @@ -114,7 +104,8 @@ fn decode_demuxer(mut d: impl Demuxer, want: CodecId) -> Vec { } fn decode_wav(path: &Path) -> Vec { - let mut r = ec_riff::WavReader::new(BufReader::new(File::open(path).expect("open"))).expect("wav"); + let mut r = + ec_riff::WavReader::new(BufReader::new(File::open(path).expect("open"))).expect("wav"); let c = r.compressed().expect("compressed wav").clone(); let spec = r.spec(); let codec = ec_riff::WavCompressed::codec_of(c.tag).expect("codec"); @@ -157,9 +148,6 @@ fn check(name: &str, got: Vec, path: &Path) { #[test] fn every_format_is_bit_exact_against_ffmpeg() { - if !have_ffmpeg() { - return; - } let dir = tmpdir("oracle"); let mut n = 0; // (ffmpeg encoder, codec id, containers) @@ -194,23 +182,26 @@ fn every_format_is_bit_exact_against_ffmpeg() { /// All 256 G.711 code points decode like ffmpeg's tables. #[test] fn g711_tables_match_ffmpeg() { - if !have_ffmpeg() { - return; - } let dir = tmpdir("g711"); let raw: Vec = (0..=255u8).collect(); for (fmt, codec) in [("alaw", CodecId::PcmAlaw), ("mulaw", CodecId::PcmMulaw)] { let p = dir.join(format!("all.{fmt}")); std::fs::write(&p, &raw).expect("write"); - let o = Command::new("ffmpeg") - .args(["-nostdin", "-v", "error", "-f", fmt, "-ar", "8000", "-ac", "1", "-i"]) + let o = ec_testkit::ffmpeg() + .args([ + "-nostdin", "-v", "error", "-f", fmt, "-ar", "8000", "-ac", "1", "-i", + ]) .arg(&p) .args(["-f", "s16le", "-"]) .output() .expect("ffmpeg"); assert!(o.status.success()); let mut dec = PcmExtDecoder::from_parameters(params(codec, 1, 8000, &[])).expect("dec"); - assert_eq!(to_bytes(dec.decode(&raw).expect("decode")), o.stdout, "{fmt}"); + assert_eq!( + to_bytes(dec.decode(&raw).expect("decode")), + o.stdout, + "{fmt}" + ); } std::fs::remove_dir_all(&dir).ok(); } diff --git a/crates/ec-truehd/Cargo.toml b/crates/ec-truehd/Cargo.toml index 78f9a23a..e679f70d 100644 --- a/crates/ec-truehd/Cargo.toml +++ b/crates/ec-truehd/Cargo.toml @@ -10,4 +10,5 @@ authors.workspace = true ec-core = { workspace = true } [dev-dependencies] +ec-testkit.workspace = true ec-matroska = { workspace = true } diff --git a/crates/ec-truehd/fuzz/seed.sh b/crates/ec-truehd/fuzz/seed.sh index 3f627982..fe7ed3b2 100755 --- a/crates/ec-truehd/fuzz/seed.sh +++ b/crates/ec-truehd/fuzz/seed.sh @@ -13,7 +13,8 @@ set -euo pipefail FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd) ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd) -FIXTURES="$ROOT/fixtures" +FIXTURES=${EC_FIXTURES:-$ROOT/fixtures} +FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg} STREAM_DIR="$FUZZ_DIR/corpus/decode_stream" SYNC_DIR="$FUZZ_DIR/corpus/parse_sync" @@ -22,9 +23,9 @@ mkdir -p "$STREAM_DIR" "$SYNC_DIR" GEN=$(mktemp -d "${TMPDIR:-$HOME}/ec-truehd-seed.XXXXXX") trap 'rm -rf "$GEN"' EXIT -command -v ffmpeg >/dev/null || { echo "seed.sh: ffmpeg not found" >&2; exit 2; } +[ -x "$FF" ] || { echo "seed.sh: ffmpeg not found at $FF" >&2; exit 2; } gen() { # name channels codec muxer - ffmpeg -hide_banner -loglevel error -y -f lavfi -i "sine=frequency=440:duration=1" \ + "$FF" -hide_banner -loglevel error -y -f lavfi -i "sine=frequency=440:duration=1" \ -ac "$2" -c:a "$3" -strict -2 -t 1 -f "$4" "$GEN/$1" } gen stereo.thd 2 truehd truehd diff --git a/crates/ec-truehd/tests/it/atmos_synth.rs b/crates/ec-truehd/tests/it/atmos_synth.rs index 3bc241bc..cefd2a3d 100644 --- a/crates/ec-truehd/tests/it/atmos_synth.rs +++ b/crates/ec-truehd/tests/it/atmos_synth.rs @@ -1,8 +1,7 @@ //! Atmos backward compatibility, tested on a synthetic 4-substream stream. //! -//! No real Atmos TrueHD stream is available to this build, so the stream is -//! built from the real 7.1 Blu-ray remux's own access units (the first -//! [`AUS`] of its TrueHD track, 3 substreams each). For every access unit, +//! The stream is built from the open 7.1 TrueHD sample's own access units (the +//! first [`AUS`], 3 substreams each). For every access unit, //! [`with_object_substream`] rebuilds it with a 4th directory entry: the //! object-audio substream, here a run of [`FILLER_WORDS`] stand-in words //! appended after substream 2's coded data. The rebuilt access unit is: @@ -31,21 +30,17 @@ //! `ffmpeg -f truehd -i -f s32le` can be compared against this //! decoder's output (ffmpeg decodes the same 8-channel presentation). //! -//! Needs the 7.1 remux under `~/Downloads`. Absent, the tests skip loudly; with -//! `EC_REQUIRE_FIXTURES=1` an absent remux is a hard failure. +//! Needs `open/fate/truehd/atmos.thd`. -use std::fs::File; -use std::io::BufReader; -use std::path::{Path, PathBuf}; +use std::path::Path; -use ec_core::CodecId; -use ec_core::Demuxer; use ec_core::frame::ChannelLayout; -use ec_matroska::MatroskaDemuxer; use ec_truehd::TrueHdDecoder; use ec_truehd::sync::AccessUnitHeader; -/// Access units taken from the start of the remux: 1 s of 48 kHz audio, one +use crate::common::raw_access_units; + +/// Access units taken from the start of the sample: 1 s of 48 kHz audio, one /// major sync among them. const AUS: usize = 1200; /// Length of the object-audio stand-in, in 16-bit words. @@ -54,66 +49,16 @@ const FILLER_WORDS: u16 = 4; const MAX_AU_WORDS: usize = 0x0FFF; const MAJOR_SYNC_LEN: usize = 28; -fn find_file() -> Option { - fn walk(dir: &Path, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - for e in entries.flatten() { - let p = e.path(); - if p.is_dir() { - walk(&p, out); - } else { - out.push(p); - } - } - } - let home = std::env::var("HOME").ok()?; - let mut all = Vec::new(); - walk(&PathBuf::from(home).join("Downloads"), &mut all); - all.into_iter().find(|p| { - p.file_name() - .and_then(|n| n.to_str()) - .is_some_and(|n| n.contains("ReelR") && n.ends_with(".mkv")) - }) -} - -/// The first [`AUS`] access units of the remux's TrueHD track, or `None` -/// (after a loud skip, or a hard failure under `EC_REQUIRE_FIXTURES`). -fn truehd_access_units() -> Option>> { - let Some(path) = find_file() else { - assert!( - std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "EC_REQUIRE_FIXTURES=1 but the 7.1 TrueHD remux is absent under ~/Downloads" - ); - eprintln!("skip: no 'ReelR ... TrueHD ...mkv' under ~/Downloads"); - return None; - }; - let file = File::open(&path).expect("open the remux"); - let mut demux = MatroskaDemuxer::new(BufReader::new(file)).expect("open the container"); - let stream_index = demux - .streams() - .iter() - .find(|s| s.params.codec == CodecId::TrueHd) - .expect("a TrueHD track") - .index; - let mut aus = Vec::with_capacity(AUS); - while aus.len() < AUS { - let packet = match demux.next_packet() { - Ok(p) => p, - Err(e) if e.is_eof() => break, - Err(e) => panic!("demux error: {e}"), - }; - if packet.stream == stream_index { - aus.push(packet.data.as_ref().to_vec()); - } - } - assert_eq!( - aus.len(), - AUS, - "the remux has at least {AUS} TrueHD access units" +/// The first [`AUS`] access units of the open 7.1 TrueHD sample. +fn truehd_access_units() -> Vec> { + let data = + std::fs::read(ec_testkit::fixture("open/fate/truehd/atmos.thd")).expect("read atmos.thd"); + let aus = raw_access_units(&data); + assert!( + aus.len() >= AUS, + "atmos.thd has fewer than {AUS} access units" ); - Some(aus) + aus.into_iter().take(AUS).collect() } /// The major sync's CRC-16 (poly `0x002D`, MSB-first table form), the same @@ -246,9 +191,7 @@ fn decode_all(aus: &[Vec]) -> (Decoded, ec_truehd::CheckStats) { #[test] fn synthetic_atmos_decodes_bit_exact_to_the_original_7_1() { - let Some(originals) = truehd_access_units() else { - return; - }; + let originals = truehd_access_units(); let synthetic: Vec> = originals .iter() .map(|au| with_object_substream(au, 0xA5)) @@ -293,9 +236,7 @@ fn synthetic_atmos_decodes_bit_exact_to_the_original_7_1() { #[test] fn object_substream_contents_do_not_change_the_pcm_output() { - let Some(originals) = truehd_access_units() else { - return; - }; + let originals = truehd_access_units(); // Filler bytes are never read, so any value must decode identically. let zeros: Vec> = originals .iter() diff --git a/crates/ec-truehd/tests/it/common.rs b/crates/ec-truehd/tests/it/common.rs index 8dddb6f1..c85ad9d5 100644 --- a/crates/ec-truehd/tests/it/common.rs +++ b/crates/ec-truehd/tests/it/common.rs @@ -1,9 +1,13 @@ -use std::process::Command; +use ec_truehd::sync::AccessUnitHeader; -/// Whether `ffmpeg -version` runs successfully. -pub fn have_ffmpeg() -> bool { - Command::new("ffmpeg") - .arg("-version") - .output() - .is_ok_and(|o| o.status.success()) +pub fn raw_access_units(data: &[u8]) -> Vec> { + let mut aus = Vec::new(); + let mut pos = 0; + while pos < data.len() { + let header = AccessUnitHeader::parse(&data[pos..]) + .unwrap_or_else(|e| panic!("access unit {}: {e}", aus.len())); + aus.push(data[pos..pos + header.length].to_vec()); + pos += header.length; + } + aus } diff --git a/crates/ec-truehd/tests/it/fixture_exact.rs b/crates/ec-truehd/tests/it/fixture_exact.rs index 6e75dfb7..4e12ca68 100644 --- a/crates/ec-truehd/tests/it/fixture_exact.rs +++ b/crates/ec-truehd/tests/it/fixture_exact.rs @@ -1,29 +1,23 @@ //! Sample-for-sample equality with ffmpeg's TrueHD decoder on the committed -//! fixtures in `crates/ec-truehd/fixtures/`. +//! fixtures in `crates/ec-truehd/fixtures/`, and on the open 7.1 sample +//! `open/fate/truehd/atmos.thd`. //! //! The committed fixtures are made with ffmpeg's own TrueHD encoder //! (`-c:a truehd -strict -2`): 2.0 and 5.1 at 16-bit (s16p input) and 24-bit //! (s32p input), 48 kHz. The file name carries the channel count: `2ch` or `51`. //! -//! The 8-channel (7.1) case is not committed: ffmpeg's encoder refuses 7.1, and -//! the only real 7.1 TrueHD source is a copyrighted remux. It is tested by -//! [`remux_71_is_bit_exact_against_ffmpeg`], which reads the remux from its -//! local path (env `EC_TRUEHD_71_REMUX`, or the `truehd_71_remux` key of -//! `real_library.toml`) and skips loudly when it is absent. -//! //! Each file is decoded here and by ffmpeg (`-f s32le`), and every sample must -//! be equal. Lossless decoding has no tolerance. ffmpeg is test tooling and is -//! driven through `std::process`; without it the test skips loudly. +//! be equal. Lossless decoding has no tolerance. A missing fixture or ffmpeg +//! fails. use std::fs::File; use std::io::BufReader; use std::path::{Path, PathBuf}; -use std::process::Command; +use crate::common::raw_access_units; use ec_core::{CodecId, Demuxer}; use ec_matroska::MatroskaDemuxer; use ec_truehd::TrueHdDecoder; -use crate::common::have_ffmpeg; fn fixtures() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures") @@ -82,16 +76,26 @@ fn decode_ours(path: &Path) -> (u32, Vec, usize, u32) { } } let stats = decoder.check_stats(); - assert_eq!(stats.lossless_check_failures, 0, "{}: {stats:?}", path.display()); + assert_eq!( + stats.lossless_check_failures, + 0, + "{}: {stats:?}", + path.display() + ); assert_eq!(stats.parity_failures, 0, "{}: {stats:?}", path.display()); - assert_eq!(stats.restart_crc_failures, 0, "{}: {stats:?}", path.display()); + assert_eq!( + stats.restart_crc_failures, + 0, + "{}: {stats:?}", + path.display() + ); assert_eq!(stats.length_mismatches, 0, "{}: {stats:?}", path.display()); (stream, samples, channels, rate) } /// ffmpeg's decode of track `stream` as interleaved S32 little-endian. fn decode_ffmpeg(path: &Path, stream: u32) -> Vec { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-nostdin", "-i"]) .arg(path) .args(["-map", &format!("0:{stream}"), "-f", "s32le", "-"]) @@ -109,10 +113,6 @@ fn decode_ffmpeg(path: &Path, stream: u32) -> Vec { #[test] fn fixtures_are_bit_exact_against_ffmpeg() { let dir = fixtures(); - if !have_ffmpeg() { - eprintln!("skip: ffmpeg not on PATH"); - return; - } let mut paths: Vec = std::fs::read_dir(&dir) .expect("fixtures dir") .flatten() @@ -138,7 +138,8 @@ fn fixtures_are_bit_exact_against_ffmpeg() { ); let mismatch = ours.iter().zip(&reference).position(|(a, b)| a != b); assert_eq!( - mismatch, None, + mismatch, + None, "{name}: first mismatch at sample {mismatch:?} (channel {:?})", mismatch.map(|i| i % channels) ); @@ -150,68 +151,44 @@ fn fixtures_are_bit_exact_against_ffmpeg() { } } -/// The local 7.1 remux: env `EC_TRUEHD_71_REMUX`, else the `truehd_71_remux` -/// key of `real_library.toml` (env `EC_REAL_LIBRARY`, default under -/// `~/Documents/Code/Rust/edith`). -fn remux_path() -> Option { - if let Ok(p) = std::env::var("EC_TRUEHD_71_REMUX") { - return Some(PathBuf::from(p)); - } - let toml = std::env::var("EC_REAL_LIBRARY").map(PathBuf::from).unwrap_or_else(|_| { - let home = std::env::var("HOME").unwrap_or_default(); - PathBuf::from(home).join("Documents/Code/Rust/edith/real_library.toml") - }); - let text = std::fs::read_to_string(toml).ok()?; - text.lines().find_map(|line| { - let (key, value) = line.trim().split_once('=')?; - if key.trim() != "truehd_71_remux" { - return None; - } - Some(PathBuf::from(value.trim().strip_prefix('"')?.strip_suffix('"')?)) - }) -} - -/// The first 2 s of a real 7.1 TrueHD remux, decoded from the start of the -/// file and compared sample-for-sample with ffmpeg's decode of the same span. +/// The open 7.1 TrueHD sample, decoded from its raw access units and compared +/// sample-for-sample with ffmpeg's decode of the whole file. #[test] -fn remux_71_is_bit_exact_against_ffmpeg() { - let Some(path) = remux_path() else { - eprintln!("skip: no 7.1 remux (set EC_TRUEHD_71_REMUX or truehd_71_remux in real_library.toml)"); - return; - }; - if !path.exists() { - eprintln!("skip: 7.1 remux {} not on disk", path.display()); - return; - } - if !have_ffmpeg() { - eprintln!("skip: ffmpeg not on PATH"); - return; +fn atmos_71_is_bit_exact_against_ffmpeg() { + let path = ec_testkit::fixture("open/fate/truehd/atmos.thd"); + let data = std::fs::read(&path).expect("read atmos.thd"); + let mut decoder = TrueHdDecoder::new(); + let mut ours = Vec::new(); + let mut channels = 0; + for au in raw_access_units(&data) { + if let Some(f) = decoder.decode_access_unit(&au).expect("decode") { + channels = f.channels(); + ours.extend(s32le(&f.data[0])); + } } - const SECONDS: usize = 2; - let (stream, ours, channels, rate) = decode_ours(&path); - assert_eq!(channels, 8, "remux channels"); - assert_eq!(rate, 48_000, "remux rate"); - let want = SECONDS * 48_000 * channels; - assert!(ours.len() >= want, "only {} samples decoded", ours.len()); - let ours = &ours[..want]; - - let out = Command::new("ffmpeg") + assert_eq!(channels, 8, "atmos.thd channels"); + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-nostdin", "-i"]) .arg(&path) - .args(["-map", &format!("0:{stream}"), "-t", &SECONDS.to_string(), "-f", "s32le", "-"]) + .args(["-f", "s32le", "-"]) .output() .expect("run ffmpeg"); - assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); + assert!( + out.status.success(), + "ffmpeg: {}", + String::from_utf8_lossy(&out.stderr) + ); let reference = s32le(&out.stdout); - assert!(reference.len() >= want, "ffmpeg gave {} samples", reference.len()); - let reference = &reference[..want]; - - let mismatch = ours.iter().zip(reference).position(|(a, b)| a != b); + assert_eq!(ours.len(), reference.len(), "sample count vs ffmpeg"); + let mismatch = ours.iter().zip(&reference).position(|(a, b)| a != b); assert_eq!( mismatch, None, "first mismatch at sample {mismatch:?} (channel {:?})", mismatch.map(|i| i % channels) ); - eprintln!("7.1 remux: {channels} ch, {SECONDS} s, {want} samples, bit-exact"); + eprintln!( + "atmos 7.1: {channels} ch, {} samples, bit-exact", + ours.len() + ); } diff --git a/crates/ec-truehd/tests/it/library.rs b/crates/ec-truehd/tests/it/library.rs index c537cdd9..2ef6e9c2 100644 --- a/crates/ec-truehd/tests/it/library.rs +++ b/crates/ec-truehd/tests/it/library.rs @@ -1,140 +1,32 @@ -//! Walks a real Blu-ray remux's TrueHD track and parses every access unit -- -//! a live discovery over `~/Downloads`, absent files skip loudly, nothing is -//! generated or bundled. +//! The open 7.1 TrueHD sample walked access unit by access unit: the units +//! tile the file exactly and their count matches ffprobe's packet count. -use std::fs::File; -use std::io::BufReader; -use std::path::PathBuf; -use std::process::Command; +use crate::common::raw_access_units; -use ec_core::{CodecId, Demuxer}; -use ec_matroska::MatroskaDemuxer; -use ec_truehd::sync::AccessUnitHeader; - -/// The user's own library, not a fixture: a glob over `~/Downloads` for a -/// known 7.1 TrueHD Blu-ray remux. -fn find_file() -> Option { - let home = std::env::var("HOME").ok()?; - let downloads = PathBuf::from(home).join("Downloads"); - for entry in glob_dir(&downloads) { - let name = entry.file_name()?.to_str()?; - if name.contains("ReelR") && name.ends_with(".mkv") { - return Some(entry); - } - } - None -} - -/// A one-level-deep, non-recursive-but-good-enough directory walk (the file -/// this test wants sits in a subdirectory of `~/Downloads`) -- no `glob` -/// crate in this family, so a plain `read_dir` walk stands in for one. -fn glob_dir(dir: &std::path::Path) -> Vec { - let mut out = Vec::new(); - let Ok(entries) = std::fs::read_dir(dir) else { - return out; - }; - for entry in entries.flatten() { - let path = entry.path(); - if path.is_dir() { - out.extend(glob_dir(&path)); - } else { - out.push(path); - } - } - out -} - -fn have_ffprobe() -> bool { - Command::new("ffprobe") - .arg("-version") - .output() - .map(|o| o.status.success()) - .unwrap_or(false) -} - -/// ffprobe's own packet count for the file's TrueHD stream, by absolute -/// stream index. -fn ffprobe_packet_count(path: &std::path::Path, stream: usize) -> Option { - let out = Command::new("ffprobe") - .args(["-v", "error", "-select_streams"]) - .arg(stream.to_string()) +#[test] +fn walks_every_truehd_access_unit_of_atmos() { + let path = ec_testkit::fixture("open/fate/truehd/atmos.thd"); + let data = std::fs::read(&path).expect("read atmos.thd"); + let aus = raw_access_units(&data); + assert!(!aus.is_empty(), "found no TrueHD access units at all"); + let out = ec_testkit::ffprobe() .args([ + "-v", + "error", + "-select_streams", + "a:0", "-count_packets", "-show_entries", "stream=nb_read_packets", "-of", "csv=p=0", ]) - .arg(path) + .arg(&path) .output() - .ok()?; - if !out.status.success() { - return None; - } - String::from_utf8_lossy(&out.stdout).trim().parse().ok() -} - -#[test] -fn walks_every_truehd_access_unit_of_a_real_7_1_remux() { - let Some(path) = find_file() else { - eprintln!("skip: no 'ReelR ... TrueHD ...mkv' under ~/Downloads"); - return; - }; - - let file = File::open(&path).expect("open the file"); - let mut demux = MatroskaDemuxer::new(BufReader::new(file)).expect("open the container"); - - let track = demux - .streams() - .iter() - .find(|s| s.params.codec == CodecId::TrueHd) - .expect("a TrueHD track"); - let stream_index = track.index; - let audio = track.params.audio().expect("audio parameters"); - assert_eq!(audio.sample_rate, 48_000, "rate"); - assert_eq!(audio.layout.channel_count(), 8, "channels"); - // Matroska's `BitDepth` element is optional and this remux's TrueHD - // track does not carry one; report what the container states rather - // than asserting a value it never claimed. - eprintln!("container-reported bit depth: {:?}", audio.bits_per_sample); - - let mut au_count = 0u64; - let mut major_syncs = 0u64; - loop { - let packet = match demux.next_packet() { - Ok(p) => p, - Err(e) if e.is_eof() => break, - Err(e) => panic!("demux error: {e}"), - }; - if packet.stream != stream_index { - continue; - } - let header = AccessUnitHeader::parse(&packet.data) - .unwrap_or_else(|e| panic!("access unit {au_count}: {e}")); - assert_eq!( - header.length, - packet.data.len(), - "access unit {au_count} claims a length that does not match its packet" - ); - if header.major_sync.is_some() { - major_syncs += 1; - } - au_count += 1; - } - - eprintln!("{au_count} access units, {major_syncs} carrying a major sync"); - assert!(au_count > 0, "found no TrueHD access units at all"); - - if have_ffprobe() { - // Absolute demuxer stream index in the file, for ffprobe's own - // `-select_streams`: the track this family's stream list found. - let absolute = stream_index as usize; - if let Some(expected) = ffprobe_packet_count(&path, absolute) { - assert_eq!(au_count, expected, "AU count vs ffprobe's packet count"); - } else { - eprintln!("skip: ffprobe packet count unavailable for stream {absolute}"); - } - } else { - eprintln!("skip: ffprobe not on PATH, no oracle comparison"); - } + .expect("run ffprobe"); + let expected: usize = String::from_utf8_lossy(&out.stdout) + .trim() + .parse() + .expect("ffprobe packet count"); + assert_eq!(aus.len(), expected, "AU count vs ffprobe's packet count"); } diff --git a/crates/ec-truehd/tests/it/oracle.rs b/crates/ec-truehd/tests/it/oracle.rs index 297fc037..24c9aeab 100644 --- a/crates/ec-truehd/tests/it/oracle.rs +++ b/crates/ec-truehd/tests/it/oracle.rs @@ -1,46 +1,15 @@ -//! Bit-exactness against an external decoder: the first 60 s of a real 7.1 -//! Blu-ray TrueHD remux (3 substreams, noise type 1 matrices), and -//! externally encoded MLP/TrueHD streams (mono, stereo, 5.1 pink noise — -//! every codebook, matrices with the 2-channel noise generator, two -//! substreams). Both need `ffmpeg` on PATH and skip loudly without it; the -//! remux is a live discovery over `~/Downloads`. +//! Bit-exactness against an external decoder: the first 60 s of the open +//! 7.1 TrueHD sample (3 substreams, noise type 1 matrices), and externally +//! encoded MLP/TrueHD streams (mono, stereo, 5.1 pink noise — every codebook, +//! matrices with the 2-channel noise generator, two substreams). Both need +//! `ffmpeg`; a missing one fails. -use std::fs::File; -use std::io::BufReader; -use std::path::{Path, PathBuf}; -use std::process::Command; - -use ec_core::{CodecId, Demuxer}; -use ec_matroska::MatroskaDemuxer; use ec_truehd::{TrueHdDecoder, TrueHdEncoder, frame_length}; -use crate::common::have_ffmpeg; -fn find_file() -> Option { - fn walk(dir: &Path, out: &mut Vec) { - let Ok(entries) = std::fs::read_dir(dir) else { - return; - }; - for e in entries.flatten() { - let p = e.path(); - if p.is_dir() { - walk(&p, out); - } else { - out.push(p); - } - } - } - let home = std::env::var("HOME").ok()?; - let mut all = Vec::new(); - walk(&PathBuf::from(home).join("Downloads"), &mut all); - all.into_iter().find(|p| { - p.file_name() - .and_then(|n| n.to_str()) - .is_some_and(|n| n.contains("ReelR") && n.ends_with(".mkv")) - }) -} +use crate::common::raw_access_units; fn ffmpeg(args: &[&str]) -> Vec { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-nostdin"]) .args(args) .output() @@ -79,29 +48,12 @@ fn compare(ours: &[i32], reference: &[i32]) -> (usize, usize, Option) { } #[test] -fn first_60_seconds_of_a_real_7_1_remux_are_bit_exact() { - let Some(path) = find_file() else { - eprintln!("skip: no 'ReelR ... TrueHD ...mkv' under ~/Downloads"); - return; - }; - if !have_ffmpeg() { - eprintln!("skip: ffmpeg not on PATH"); - return; - } +fn first_60_seconds_of_atmos_are_bit_exact() { const SECONDS: usize = 60; - let mut demux = MatroskaDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap(); - let track = demux - .streams() - .iter() - .find(|s| s.params.codec == CodecId::TrueHd) - .expect("a TrueHD track"); - let stream_index = track.index; - + let path = ec_testkit::fixture("open/fate/truehd/atmos.thd"); let reference = s32le(&ffmpeg(&[ "-i", path.to_str().unwrap(), - "-map", - &format!("0:{stream_index}"), "-t", &SECONDS.to_string(), "-f", @@ -110,21 +62,17 @@ fn first_60_seconds_of_a_real_7_1_remux_are_bit_exact() { ])); let channels = 8; let wanted = SECONDS * 48_000 * channels; + let data = std::fs::read(&path).expect("read atmos.thd"); let mut decoder = TrueHdDecoder::new(); let mut ours: Vec = Vec::with_capacity(wanted); let mut aus = 0; - while ours.len() < wanted { - let packet = match demux.next_packet() { - Ok(p) => p, - Err(e) if e.is_eof() => break, - Err(e) => panic!("demux: {e}"), - }; - if packet.stream != stream_index { - continue; + for au in raw_access_units(&data) { + if ours.len() >= wanted { + break; } let frame = decoder - .decode_access_unit(&packet.data) + .decode_access_unit(&au) .unwrap_or_else(|e| panic!("AU {aus}: {e}")); aus += 1; if let Some(f) = frame { @@ -165,10 +113,6 @@ fn first_60_seconds_of_a_real_7_1_remux_are_bit_exact() { /// codebook and a wide range of LSB widths. #[test] fn externally_encoded_mlp_round_trips_bit_exact() { - if !have_ffmpeg() { - eprintln!("skip: ffmpeg not on PATH"); - return; - } let dir = std::env::temp_dir().join(format!("ec-truehd-oracle-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); let mut failures = Vec::new(); @@ -242,10 +186,6 @@ fn externally_encoded_mlp_round_trips_bit_exact() { /// other. #[test] fn ffmpeg_decodes_our_encoder_bit_exact() { - if !have_ffmpeg() { - eprintln!("ffmpeg not found, skipping"); - return; - } use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat}; use ec_core::packet::Buf; use ec_core::registry::Encoder; diff --git a/crates/ec-vorbis/Cargo.toml b/crates/ec-vorbis/Cargo.toml index 54b1771d..bb2ed881 100644 --- a/crates/ec-vorbis/Cargo.toml +++ b/crates/ec-vorbis/Cargo.toml @@ -11,4 +11,5 @@ ec-core.workspace = true ec-dsp.workspace = true [dev-dependencies] +ec-testkit.workspace = true ec-ogg = { path = "../ec-ogg", version = "0.1.0" } diff --git a/crates/ec-vorbis/fuzz/seed.sh b/crates/ec-vorbis/fuzz/seed.sh index c11dbfea..806974af 100755 --- a/crates/ec-vorbis/fuzz/seed.sh +++ b/crates/ec-vorbis/fuzz/seed.sh @@ -14,8 +14,8 @@ set -euo pipefail FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd) REPO=$(cd -- "$FUZZ_DIR/../../.." && pwd) -FIXTURES="$REPO/fixtures" -[ -d "$FIXTURES/audio" ] || { echo "seed.sh: $FIXTURES/audio missing; run scripts/link-fixtures.sh" >&2; exit 2; } +FIXTURES=${EC_FIXTURES:-$REPO/fixtures} +[ -d "$FIXTURES/audio" ] || { echo "seed.sh: $FIXTURES/audio missing; run scripts/fixtures.sh" >&2; exit 2; } HEADERS_DIR="$FUZZ_DIR/headers" SETUP_DIR="$FUZZ_DIR/corpus/setup" diff --git a/crates/ec-vorbis/tests/oracle.rs b/crates/ec-vorbis/tests/oracle.rs index 8b041285..88d4529f 100644 --- a/crates/ec-vorbis/tests/oracle.rs +++ b/crates/ec-vorbis/tests/oracle.rs @@ -8,14 +8,13 @@ use std::fs::File; use std::path::{Path, PathBuf}; -use std::process::Command; use ec_core::{Decoder, Demuxer, Frame}; use ec_ogg::{OggDemuxer, granule_of}; -use ec_vorbis::{BlockLog, EncoderConfig, VorbisDecoder, VorbisEncoder}; +use ec_vorbis::{EncoderConfig, VorbisDecoder, VorbisEncoder}; fn fixtures() -> PathBuf { - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") + ec_testkit::root() } fn scratch() -> PathBuf { @@ -37,7 +36,7 @@ fn ffmpeg_decode(path: &Path) -> Option<(Vec>, u32)> { let channels: usize = probe_field(path, "channels")?.parse().ok()?; let rate: u32 = probe_field(path, "sample_rate")?.parse().ok()?; - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"]) @@ -62,7 +61,7 @@ fn ffmpeg_decode(path: &Path) -> Option<(Vec>, u32)> { /// One `stream=` field of the first audio stream. fn probe_field(path: &Path, field: &str) -> Option { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -356,39 +355,6 @@ fn encode_to_file(source: &[Vec], rate: u32, bitrate: i32, name: &str) -> P path } -/// Like [`encode_to_file`] but also returns the per-block rate-loop log. -fn encode_to_file_with_log( - source: &[Vec], - rate: u32, - bitrate: i32, - name: &str, -) -> (PathBuf, Vec) { - let channels = source.len() as u16; - let mut encoder = VorbisEncoder::new(EncoderConfig { - sample_rate: rate, - channels, - bitrate_bps: bitrate, - quality: 0.6, - }) - .expect("encoder"); - encoder.enable_block_log(); - let borrowed: Vec<&[f32]> = source.iter().map(|c| &c[..]).collect(); - encoder.push_planar(&borrowed).expect("push"); - encoder.finish(); - let mut packets = Vec::new(); - loop { - match encoder.next_packet() { - Ok(packet) => packets.push((packet.data, packet.granule)), - Err(e) if e.is_eof() => break, - Err(e) => panic!("encode: {e}"), - } - } - let log = encoder.take_block_log(); - let path = scratch().join(name); - mux(&path, &encoder, &packets, rate, channels); - (path, log) -} - /// Duration ffprobe reports, in samples of the stream's own rate. fn probed_samples(path: &Path) -> i64 { probe_field(path, "duration_ts") @@ -633,18 +599,17 @@ fn onset_after_silence_has_no_pre_echo() { // The reference oracle must decode the short-block stream // cleanly: no warnings, let alone errors. - let warn = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "warning", "-i"]) .arg(&path) .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"]) - .output(); - if let Ok(out) = warn { - assert!( - out.stderr.is_empty(), - "{name}: oracle decode warnings: {}", - String::from_utf8_lossy(&out.stderr) - ); - } + .output() + .expect("ffmpeg runs"); + assert!( + out.stderr.is_empty(), + "{name}: oracle decode warnings: {}", + String::from_utf8_lossy(&out.stderr) + ); let tone_rms = rms(&source[0][onset..]); let check = |label: &str, planes: &[Vec]| { @@ -804,932 +769,3 @@ fn quiet_content_reaches_the_target_or_is_transparent() { } } } - -/// Per-Bark-band quantised-residue histogram comparison: ours vs libvorbis -/// reference. We encode the source with our encoder (capturing residue), then -/// encode the same source with libvorbis and decode that stream with our own -/// decoder, capturing its decoded residue (after inverse coupling, before -/// floor multiply — the same domain as the encoder's `quantised`). The -/// reference is libvorbis's own residue, so per-band divergence names where -/// our psy spends differently from libvorbis. -#[test] -#[ignore = "slow: encodes 7 sources × 128k, needs ffmpeg/libvorbis"] -fn residue_histogram_vs_reference() { - use std::io::Write; - - let sources: &[(&str, &str)] = &[ - ("nik", "~/Music/reeln.mp4"), - ("reelo", "~/Music/reelo.mp3"), - ("her", "~/Music/reeli.mp3"), - ("reell", "~/Music/reell.mp4"), - ("reelm", "~/Music/reelm.wav"), - ("dl8a", "~/Downloads/8a3b6d1d19.mp3"), - ( - "hein", - "~/Downloads/reelm.mp3", - ), - ]; - let bitrate = 128_000i32; - let rate = 48_000u32; - let channels = 2u16; - // Limit to ~12 s for speed — enough blocks for a stable histogram. - let max_samples = rate as usize * 12; - - let out_dir = scratch().join("vorbis7"); - std::fs::create_dir_all(&out_dir).expect("out dir"); - let mut report = String::new(); - report.push_str("# Residue histogram: ours vs libvorbis reference\n\n"); - report.push_str(&format!( - "Bitrate: {} kbps, {} Hz, {}ch, {} s max\n\n", - bitrate / 1000, - rate, - channels, - max_samples / rate as usize - )); - let mut total_ours_bytes = 0u64; - let mut total_ref_bytes = 0u64; - - let mut rows = 0usize; - for &(name, src_path) in sources { - let expanded = shellexpand(src_path); - let src = PathBuf::from(&expanded); - if !src.exists() { - report.push_str(&format!("## {name}: SKIP (file not found: {expanded})\n\n")); - continue; - } - rows += 1; - // Decode source with ffmpeg, limit duration. - let Some((source_pcm, src_rate)) = ffmpeg_decode_limited(&src, rate, max_samples) else { - report.push_str(&format!("## {name}: SKIP (ffmpeg decode failed)\n\n")); - continue; - }; - if source_pcm.len() < 2 || source_pcm[0].is_empty() { - report.push_str(&format!("## {name}: SKIP (empty decode)\n\n")); - continue; - } - // Resample to 48k if needed — ffmpeg_decode_limited already targets 48k. - let _ = src_rate; - - // --- Ours: encode source with our encoder, capture residue, keep the ogg --- - let ours_ogg = out_dir.join(format!("ours-{name}-128k.ogg")); - let (ours_residue, ours_bytes) = - encode_and_capture(&source_pcm, rate, channels, bitrate, &ours_ogg); - - // --- Sanity: decoding our own ogg with capture on must reproduce the - // encoder's capture band for band, or the two captures are not in the - // same domain and the table below means nothing. --- - let (roundtrip, ours_split) = decode_capture_with_bits(&ours_ogg); - let (sanity_ok, sanity_detail) = compare_captures(&ours_residue, &roundtrip, rate); - let ours_bits = bit_split_summary(&ours_split, &roundtrip); - - // --- Reference: encode with libvorbis, decode with OUR decoder, capture --- - let ref_ogg = out_dir.join(format!("ref-{name}-128k.ogg")); - let ref_status = Command::new("ffmpeg") - // `-vn`: with the video stream still attached (reell, h264+aac mp4) - // ffmpeg's libvorbis wrapper ignores -b:a and encodes at ~3.2x the - // target; audio-only input encodes at the requested rate. - .args(["-y", "-v", "error", "-i"]) - .arg(&src) - .args([ - "-vn", - "-t", - &format!("{}", max_samples / rate as usize), - "-ac", - "2", - "-ar", - "48000", - "-c:a", - "libvorbis", - "-b:a", - "128k", - ]) - .arg(&ref_ogg) - .status(); - let (ref_residue, ref_split) = match ref_status { - Ok(s) if s.success() => decode_capture_with_bits(&ref_ogg), - _ => { - report.push_str(&format!("## {name}: libvorbis encode failed\n\n")); - continue; - } - }; - let ref_bytes = std::fs::metadata(&ref_ogg).expect("ref ogg").len(); - total_ours_bytes += ours_bytes; - total_ref_bytes += ref_bytes; - - // --- Build per-Bark-band histograms --- - let bins = 6; // |q|: 0, 1, 2, 3-4, 5-8, 9+ - let max_bark = 25; - let mut ours_hist = vec![vec![0u64; bins]; max_bark]; - let mut ref_hist = vec![vec![0u64; bins]; max_bark]; - for (half, quantised) in &ours_residue { - accumulate(quantised, *half, rate, &mut ours_hist, max_bark); - } - for (half, quantised) in &ref_residue { - accumulate(quantised, *half, rate, &mut ref_hist, max_bark); - } - - report.push_str(&format!( - "## {name} — sanity {}: {} — ours {} B vs ref {} B ({:.2}x)\n\n", - if sanity_ok { "PASS" } else { "FAIL" }, - sanity_detail, - ours_bytes, - ref_bytes, - ours_bytes as f64 / ref_bytes as f64 - )); - let ref_bits = bit_split_summary(&ref_split, &ref_residue); - for (who, b) in [("ours", ours_bits), ("ref", ref_bits)] { - let (f, r, p, nz) = b; - report.push_str(&format!( - "bits {who}: floor {f} ({:.1}%), residue {r} ({:.1}%), other {}, packet {p}; non-zero {nz}, residue bits/non-zero {:.2}\n", - 100.0 * f as f64 / p.max(1) as f64, - 100.0 * r as f64 / p.max(1) as f64, - p.saturating_sub(f + r), - r as f64 / nz.max(1) as f64 - )); - } - report.push('\n'); - report.push_str("| Bark | q=0 ours/ref | q=1 | q=2 | q=3-4 | q=5-8 | q=9+ | total ours/ref | spend ratio |\n"); - report.push_str("|------|-------------|-----|-----|-------|-------|------|-----------------|-------------|\n"); - for band in 0..max_bark { - let o = &ours_hist[band]; - let r = &ref_hist[band]; - let o_total: u64 = o.iter().sum(); - let r_total: u64 = r.iter().sum(); - if o_total == 0 && r_total == 0 { - continue; - } - // "Spend" = non-zero entries (bins 1..) — proxy for bits spent. - let o_spend: u64 = o[1..].iter().sum(); - let r_spend: u64 = r[1..].iter().sum(); - let ratio = if r_spend > 0 { - o_spend as f64 / r_spend as f64 - } else { - f64::INFINITY - }; - report.push_str(&format!( - "| {} | {}/{} | {}/{} | {}/{} | {}/{} | {}/{} | {}/{} | {}/{} | {:.2} |\n", - band, - o[0], - r[0], - o[1], - r[1], - o[2], - r[2], - o[3], - r[3], - o[4], - r[4], - o[5], - r[5], - o_total, - r_total, - ratio, - )); - } - - // Fraction table: per-band share of entries in each |q| class and the - // shape distance = sum |f_ours - f_ref| over the four classes - // (0 = identical spend shape; convergence target < 0.15 in Bark 3-22). - report.push_str("| Bark | f0 ours | f0 ref | f1 ours | f1 ref | f2 ours | f2 ref | f3+ ours | f3+ ref | dist |\n"); - report.push_str("|------|---------|--------|---------|--------|---------|--------|----------|---------|------|\n"); - let frac = |h: &[u64], total: u64| { - vec![ - h[0] as f64 / total as f64, - h[1] as f64 / total as f64, - h[2] as f64 / total as f64, - (h[3] + h[4] + h[5]) as f64 / total as f64, - ] - }; - let mut band_dist: Vec<(usize, f64)> = Vec::new(); - for band in 0..max_bark { - let o_total: u64 = ours_hist[band].iter().sum(); - let r_total: u64 = ref_hist[band].iter().sum(); - if o_total == 0 || r_total == 0 { - continue; - } - let fo = frac(&ours_hist[band], o_total); - let fr = frac(&ref_hist[band], r_total); - let dist: f64 = fo.iter().zip(&fr).map(|(a, b)| (a - b).abs()).sum(); - band_dist.push((band, dist)); - report.push_str(&format!( - "| {} | {:.3} | {:.3} | {:.3} | {:.3} | {:.3} | {:.3} | {:.3} | {:.3} | {:.3} |\n", - band, fo[0], fr[0], fo[1], fr[1], fo[2], fr[2], fo[3], fr[3], dist, - )); - } - let in_scope: Vec<(usize, f64)> = band_dist - .iter() - .filter(|(b, _)| (3..=22).contains(b)) - .cloned() - .collect(); - if !in_scope.is_empty() { - let max_d = in_scope.iter().map(|(_, d)| *d).fold(f64::MIN, f64::max); - let over = in_scope.iter().filter(|(_, d)| *d >= 0.15).count(); - report.push_str(&format!( - "\nshape Bark 3-22: max dist {max_d:.3}, bands >= 0.15: {over}/{} — {}\n", - in_scope.len(), - if over == 0 { - "SHAPE PASS" - } else { - "shape fail" - }, - )); - } - report.push('\n'); - } - - // The seven sources are the user's own library, so each may be absent on a - // given host -- but a run that encoded none of them is a measurement of - // nothing, and the report it writes looks the same as a real one. - assert!(rows > 0, "no library sources were readable"); - report.push_str(&format!( - "\nTotal bytes: ours {total_ours_bytes} vs ref {total_ref_bytes} ({:.2}x)\n", - total_ours_bytes as f64 / total_ref_bytes as f64, - )); - let report_path = - PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../lanes/vorbis-psy-r1.histogram.txt"); - let mut f = File::create(&report_path).expect("create report"); - f.write_all(report.as_bytes()).expect("write report"); - println!("Histogram report: {}", report_path.display()); - // Also print to stdout for immediate viewing. - print!("{report}"); -} - -/// Encode PCM with our encoder, capturing per-block quantised residue, and mux -/// Per-block residue of one stream: (block size, one residue vector per channel). -type ResidueCapture = Vec<(usize, Vec>)>; - -/// the result to `out` so it can be decoded back (sanity check + rate). -fn encode_and_capture( - source: &[Vec], - rate: u32, - channels: u16, - bitrate: i32, - out: &Path, -) -> (ResidueCapture, u64) { - let mut encoder = VorbisEncoder::new(EncoderConfig { - sample_rate: rate, - channels, - bitrate_bps: bitrate, - quality: 0.6, - }) - .expect("encoder"); - encoder.enable_residue_capture(); - let borrowed: Vec<&[f32]> = source.iter().map(|c| &c[..]).collect(); - encoder.push_planar(&borrowed).expect("push"); - encoder.finish(); - let mut packets = Vec::new(); - loop { - match encoder.next_packet() { - Ok(packet) => packets.push((packet.data, packet.granule)), - Err(e) if e.is_eof() => break, - Err(e) => panic!("encode: {e}"), - } - } - mux(out, &encoder, &packets, rate, channels); - let bytes = std::fs::metadata(out).expect("muxed file").len(); - (encoder.take_residue_capture(), bytes) -} - -/// Bit split summed over the stream: (floor bits, residue bits, packet bits, -/// non-zero residue count) — bits per coded value is the coding-efficiency oracle. -fn bit_split_summary( - split: &[(u64, u64, u64)], - residue: &[(usize, Vec>)], -) -> (u64, u64, u64, u64) { - let (mut f, mut r, mut p) = (0u64, 0u64, 0u64); - for &(a, b, c) in split { - f += a; - r += b; - p += c; - } - let nz: u64 = residue - .iter() - .map(|(_, chs)| { - chs.iter() - .map(|c| c.iter().filter(|&&v| v != 0).count() as u64) - .sum::() - }) - .sum(); - (f, r, p, nz) -} - -fn decode_capture_with_bits(path: &Path) -> (ResidueCapture, Vec<(u64, u64, u64)>) { - let mut demuxer = OggDemuxer::open(File::open(path).expect("open")).expect("ogg"); - let stream = demuxer - .streams() - .iter() - .find(|s| s.params.codec == ec_core::CodecId::Vorbis) - .expect("a Vorbis stream") - .clone(); - let extradata = stream.params.extradata.clone().expect("headers"); - let mut decoder = VorbisDecoder::from_extradata(&extradata).expect("headers parse"); - decoder.enable_residue_capture(); - loop { - let packet = match demuxer.next_packet() { - Ok(packet) => packet, - Err(e) if e.is_eof() => break, - Err(e) => panic!("demux {}: {e}", path.display()), - }; - if packet.stream != stream.index { - continue; - } - // A packet the decoder cannot use is skipped, like in `our_decode`. - if decoder.decode_audio(&packet.data).is_err() { - continue; - } - } - let residue = decoder.take_residue_capture(); - let bits = decoder.take_bit_split(); - (residue, bits) -} - -/// Bin two captures by Bark and compare every histogram cell. -fn compare_captures( - a: &[(usize, Vec>)], - b: &[(usize, Vec>)], - rate: u32, -) -> (bool, String) { - let bins = 6; - let max_bark = 25; - let mut ha = vec![vec![0u64; bins]; max_bark]; - let mut hb = vec![vec![0u64; bins]; max_bark]; - for (half, q) in a { - accumulate(q, *half, rate, &mut ha, max_bark); - } - for (half, q) in b { - accumulate(q, *half, rate, &mut hb, max_bark); - } - let mut diffs = Vec::new(); - for band in 0..max_bark { - for bucket in 0..bins { - if ha[band][bucket] != hb[band][bucket] { - diffs.push(format!( - "bark {band} q{bucket}: {} vs {}", - ha[band][bucket], hb[band][bucket] - )); - } - } - } - if diffs.is_empty() { - ( - true, - format!("identical histograms ({} vs {} blocks)", a.len(), b.len()), - ) - } else { - ( - false, - format!( - "{} vs {} blocks; first diffs: {}", - a.len(), - b.len(), - diffs.iter().take(5).cloned().collect::>().join("; ") - ), - ) - } -} - -/// Decode with ffmpeg into planar f32, resampled to `rate`, limited to `max_samples`. -fn ffmpeg_decode_limited( - path: &Path, - rate: u32, - max_samples: usize, -) -> Option<(Vec>, u32)> { - let out = Command::new("ffmpeg") - .args(["-v", "error", "-i"]) - .arg(path) - .args([ - "-t", - &format!("{}", max_samples / rate as usize), - "-ac", - "2", - "-ar", - &rate.to_string(), - "-f", - "f32le", - "-acodec", - "pcm_f32le", - "-", - ]) - .output() - .expect("ffmpeg runs"); - if !out.stderr.is_empty() { - eprintln!("ffmpeg stderr: {}", String::from_utf8_lossy(&out.stderr)); - return None; - } - let channels = 2usize; - let interleaved: Vec = out - .stdout - .as_chunks::<4>() - .0 - .iter() - .map(|b| f32::from_le_bytes(*b)) - .collect(); - let n = interleaved.len() / channels; - let n = n.min(max_samples); - let mut planes: Vec> = (0..channels).map(|_| Vec::with_capacity(n)).collect(); - for (i, value) in interleaved.into_iter().enumerate().take(n * channels) { - planes[i % channels].push(value); - } - Some((planes, rate)) -} - -/// Accumulate per-Bark-band |q| histograms from quantised residue. -fn accumulate( - quantised: &[Vec], - half: usize, - rate: u32, - hist: &mut [Vec], - max_bark: usize, -) { - for channel in quantised { - for (bin, &q) in channel.iter().enumerate() { - if bin >= half { - break; - } - let hz = bin as f64 * f64::from(rate) / (2.0 * half as f64); - let bark = VorbisEncoder::bark_hz(hz) as usize; - let band = bark.min(max_bark - 1); - let bucket = match q.abs() { - 0 => 0, - 1 => 1, - 2 => 2, - 3..=4 => 3, - 5..=8 => 4, - _ => 5, - }; - hist[band][bucket] += 1; - } - } -} - -/// Expand `~` in a path string. -fn shellexpand(path: &str) -> String { - if let Some(rest) = path.strip_prefix("~/") { - let home = std::env::var("HOME").unwrap_or_else(|_| "/home".to_string()); - format!("{home}/{rest}") - } else { - path.to_string() - } -} - -/// Full-file sweep over the user's library at the two managed rates: ours -/// encoded at the size libvorbis actually produced (ffmpeg's -b:a is -/// unmanaged VBR, 10-30% under nominal on real music), bytes within ±3% of -/// it and correlation-to-source within .005 of it. Both encodes decode -/// through our decoder so the gap measures the encoders, not the decoders. -/// Writes `lanes/vorbis-psy-r1.sweep.txt`. -#[test] -#[ignore = "slow: encodes 7 full sources × 2 rates, needs ffmpeg/libvorbis"] -fn real_library_sweep_vs_reference() { - let sources: &[(&str, &str)] = &[ - ("nik", "~/Music/reeln.mp4"), - ("reelo", "~/Music/reelo.mp3"), - ("her", "~/Music/reeli.mp3"), - ("reell", "~/Music/reell.mp4"), - ("reelm", "~/Music/reelm.wav"), - ("dl8a", "~/Downloads/8a3b6d1d19.mp3"), - ( - "hein", - "~/Downloads/reelm.mp3", - ), - ]; - let rate = 48_000u32; - let max_samples = rate as usize * 600; - let out_dir = scratch().join("vorbis7-sweep"); - std::fs::create_dir_all(&out_dir).expect("out dir"); - let mut table = String::from( - "source kbps ours_kbps ref_kbps rate% corr_ours corr_ref gap minsec_o minsec_r drops verdict\n", - ); - let mut failures = Vec::new(); - let only = std::env::var("SWEEP_ONLY").ok(); - let dump_drops = std::env::var("DROPS_DUMP").is_ok(); - let mut drops = String::new(); - let mut rows = 0usize; - for &(name, src_path) in sources { - if only - .as_deref() - .is_some_and(|o| !o.split(',').any(|n| n == name)) - { - continue; - } - let src = PathBuf::from(shellexpand(src_path)); - if !src.exists() { - table.push_str(&format!("{name:<7} - SKIP (missing)\n")); - continue; - } - rows += 1; - let Some((source_pcm, _)) = ffmpeg_decode_limited(&src, rate, max_samples) else { - table.push_str(&format!("{name:<7} - SKIP (decode)\n")); - continue; - }; - let seconds = source_pcm[0].len() as f64 / f64::from(rate); - for &kbps in &[96i32, 128] { - // libvorbis under ffmpeg's -b:a runs unmanaged VBR and lands - // 10-30% under the nominal rate on real music, so ours is asked - // for the bytes it actually produced: quality at equal size. - let reference = out_dir.join(format!("ref-{name}-{kbps}k.ogg")); - let status = Command::new("ffmpeg") - .args(["-y", "-v", "error", "-i"]) - .arg(&src) - .args([ - "-vn", - "-t", - "600", - "-ac", - "2", - "-ar", - "48000", - "-c:a", - "libvorbis", - "-b:a", - &format!("{kbps}k"), - ]) - .arg(&reference) - .status() - .expect("ffmpeg runs"); - assert!(status.success(), "libvorbis encode of {name} at {kbps}k"); - let bytes = |p: &Path| std::fs::metadata(p).expect("size").len() as f64; - let ref_kbps = bytes(&reference) * 8.0 / seconds / 1000.0; - let (ours, block_log) = encode_to_file_with_log( - &source_pcm, - rate, - (ref_kbps * 1000.0).round() as i32, - &format!("vorbis7-sweep/ours-{name}-{kbps}k.ogg"), - ); - let ours_kbps = bytes(&ours) * 8.0 / seconds / 1000.0; - let rate_pct = (ours_kbps / ref_kbps - 1.0) * 100.0; - // Whole-file corr plus a per-second trace: a dropout (the - // rate-loop windup class, 200 ms silences after transients) is - // invisible in the mean and bimodal per second, so it is gated - // as "seconds where ours is under 0.9 and the reference is not". - let corr_of = |p: &Path| -> (f64, Vec) { - let (pcm, _) = our_decode(p); - let n = pcm[0].len().min(source_pcm[0].len()); - let mean = (0..2) - .map(|c| correlation(&pcm[c][..n], &source_pcm[c][..n])) - .sum::() - / 2.0; - let step = rate as usize; - let per_second = (0..n / step) - .map(|s| { - let r = s * step..(s + 1) * step; - (0..2) - .map(|c| correlation(&pcm[c][r.clone()], &source_pcm[c][r.clone()])) - .sum::() - / 2.0 - }) - .collect(); - (mean, per_second) - }; - let (corr_ours, sec_ours) = corr_of(&ours); - let (corr_ref, sec_ref) = corr_of(&reference); - let gap = corr_ref - corr_ours; - let min_of = |v: &[f64]| v.iter().copied().fold(1.0f64, f64::min); - let (min_ours, min_ref) = (min_of(&sec_ours), min_of(&sec_ref)); - let dropouts = sec_ours - .iter() - .zip(&sec_ref) - .filter(|(o, r)| **o < 0.9 && **r >= 0.9) - .count(); - let dropout_secs: Vec = sec_ours - .iter() - .zip(&sec_ref) - .enumerate() - .filter(|(_, (o, r))| **o < 0.9 && **r >= 0.9) - .map(|(s, _)| s) - .collect(); - let pass = rate_pct.abs() <= 3.0 && gap <= 0.005 && dropouts == 0; - if !pass { - failures.push(format!( - "{name}@{kbps}k rate {rate_pct:+.2}% gap {gap:.4} dropouts {dropouts}" - )); - } - table.push_str(&format!( - "{name:<7} {kbps:<6} {ours_kbps:<9.1} {ref_kbps:<8.1} {rate_pct:+6.2} {corr_ours:<9.4} {corr_ref:<8.4} {gap:<7.4} {min_ours:<8.3} {min_ref:<7.3} {dropouts:<5} {}\n", - if pass { "PASS" } else { "FAIL" } - )); - eprintln!("{}", table.lines().last().unwrap()); - if dump_drops { - drops.push_str(&format!( - "\n=== {name}@{kbps}k rate {rate_pct:+.2}% gap {gap:.4} dropouts {dropouts} ===\n" - )); - for &s in &dropout_secs { - let lo = (s.saturating_sub(2)) as i64 * rate as i64; - let hi = (s + 3) as i64 * rate as i64; - drops.push_str(&format!( - " sec {s}: ours {:.3} ref {:.3}\n", - sec_ours[s], sec_ref[s] - )); - drops.push_str(" idx centre_s n kind steady bits headroom rate_hr reservoir target\n"); - for (i, b) in block_log.iter().enumerate() { - if b.centre < lo || b.centre >= hi { - continue; - } - drops.push_str(&format!( - " {i:<4} {:>8.2} {:<5} {:<5} {:<6} {:<6} {:>8.1} {:>7.1} {:>9.1} {:>7.1}\n", - b.centre as f64 / rate as f64, - b.n, - if b.is_long { "L" } else { "S" }, - b.steady, - b.bits, - b.headroom, - b.rate_headroom, - b.reservoir, - b.target, - )); - } - } - } - } - } - eprintln!("\n{table}"); - if dump_drops { - let _ = std::fs::write( - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes/vorbis-hf-r2.drops.txt"), - &drops, - ); - } - let _ = std::fs::write( - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes/vorbis-psy-r1.sweep.txt"), - &table, - ); - assert!(rows > 0, "no library sources were readable"); - assert!(failures.is_empty(), "sweep failures: {failures:?}"); -} - -/// In-place radix-2 FFT. Only magnitudes and differences of identically -/// transformed spectra are used, so the twiddle sign convention is irrelevant. -fn fft(re: &mut [f64], im: &mut [f64]) { - let n = re.len(); - assert!(n.is_power_of_two()); - let bits = n.trailing_zeros(); - for i in 0..n { - let j = ((i as u32).reverse_bits() >> (32 - bits)) as usize; - if j > i { - re.swap(i, j); - im.swap(i, j); - } - } - let mut len = 2; - while len <= n { - let half = len / 2; - let step = std::f64::consts::TAU / len as f64; - for start in (0..n).step_by(len) { - for k in 0..half { - let angle = step * k as f64; - let (wr, wi) = (angle.cos(), angle.sin()); - let i = start + k; - let j = i + half; - let tr = re[j] * wr - im[j] * wi; - let ti = re[j] * wi + im[j] * wr; - re[j] = re[i] - tr; - im[j] = im[i] - ti; - re[i] += tr; - im[i] += ti; - } - } - len *= 2; - } -} - -/// Per-Bark-band spectral error, ours vs libvorbis, both decoded through our -/// decoder (so the gap measures encoders, not decoders): every 2048-sample -/// Hann frame (hop 1024) of the 48 kHz source, band edges in Hz (25 edges → -/// 24 bands), energies summed over frames and both channels. -/// NSR = 10log10(Σ|X_sig−X_src|²/Σ|X_src|²), E = 10log10(Σ|X_sig|²/Σ|X_src|²). -/// The same pass records the bit split of both streams (the decode-side -/// capture `decode_capture_with_bits` provides), so the bits table covers the -/// same rows without a second encode pass. Writes -/// `lanes/vorbis-psy-r1.bands.txt` and `lanes/vorbis-psy-r1.bits.txt`. -#[test] -#[ignore = "slow: encodes 7 full sources × 2 rates, needs ffmpeg/libvorbis"] -fn band_error_vs_reference() { - use std::io::Write; - - let sources: &[(&str, &str)] = &[ - ("nik", "~/Music/reeln.mp4"), - ("reelo", "~/Music/reelo.mp3"), - ("her", "~/Music/reeli.mp3"), - ("reell", "~/Music/reell.mp4"), - ("reelm", "~/Music/reelm.wav"), - ("dl8a", "~/Downloads/8a3b6d1d19.mp3"), - ( - "hein", - "~/Downloads/reelm.mp3", - ), - ]; - let rate = 48_000u32; - let max_samples = rate as usize * 600; - let out_dir = scratch().join("vorbis7-bands"); - std::fs::create_dir_all(&out_dir).expect("out dir"); - - const FRAME: usize = 2048; - const HOP: usize = 1024; - const EDGES: [f64; 25] = [ - 100.0, 200.0, 300.0, 400.0, 510.0, 630.0, 770.0, 920.0, 1080.0, 1270.0, 1480.0, 1720.0, - 2000.0, 2320.0, 2700.0, 3150.0, 3700.0, 4400.0, 5300.0, 6400.0, 7700.0, 9500.0, 12000.0, - 15500.0, 24000.0, - ]; - let band_of: Vec> = (0..=FRAME / 2) - .map(|bin| { - let hz = bin as f64 * f64::from(rate) / FRAME as f64; - EDGES.windows(2).position(|w| hz >= w[0] && hz < w[1]) - }) - .collect(); - let window: Vec = (0..FRAME) - .map(|i| 0.5 - 0.5 * (std::f64::consts::TAU * i as f64 / FRAME as f64).cos()) - .collect(); - - let mut bands = String::from("# Band error: ours vs libvorbis, both via our decoder\n\n"); - let mut bits = String::from("# Bit split over full sources, same rows as the band error\n\n"); - let only = std::env::var("SWEEP_ONLY").ok(); - let mut rows = 0usize; - for &(name, src_path) in sources { - if only - .as_deref() - .is_some_and(|o| !o.split(',').any(|n| n == name)) - { - continue; - } - let src = PathBuf::from(shellexpand(src_path)); - if !src.exists() { - bands.push_str(&format!("## {name}: SKIP (missing)\n\n")); - continue; - } - rows += 1; - let Some((source_pcm, _)) = ffmpeg_decode_limited(&src, rate, max_samples) else { - bands.push_str(&format!("## {name}: SKIP (decode)\n\n")); - continue; - }; - let seconds = source_pcm[0].len() as f64 / f64::from(rate); - let bytes = |p: &Path| std::fs::metadata(p).expect("size").len() as f64; - for &kbps in &[96i32, 128] { - let t0 = std::time::Instant::now(); - let reference = out_dir.join(format!("ref-{name}-{kbps}k.ogg")); - let status = Command::new("ffmpeg") - .args(["-y", "-v", "error", "-i"]) - .arg(&src) - .args([ - "-vn", - "-t", - "600", - "-ac", - "2", - "-ar", - "48000", - "-c:a", - "libvorbis", - "-b:a", - &format!("{kbps}k"), - ]) - .arg(&reference) - .status() - .expect("ffmpeg runs"); - assert!(status.success(), "libvorbis encode of {name} at {kbps}k"); - let ref_kbps = bytes(&reference) * 8.0 / seconds / 1000.0; - // Ours at the size libvorbis actually produced, exactly as the sweep. - let ours = encode_to_file( - &source_pcm, - rate, - (ref_kbps * 1000.0).round() as i32, - &format!("vorbis7-bands/ours-{name}-{kbps}k.ogg"), - ); - let ours_kbps = bytes(&ours) * 8.0 / seconds / 1000.0; - - // PCM through our decoder for the band error; bit split from the - // same file's residue-domain capture (decode twice — the capture - // path returns no PCM). - let (ours_pcm, ours_split) = { - let (residue, split) = decode_capture_with_bits(&ours); - (our_decode(&ours).0, bit_split_summary(&split, &residue)) - }; - let (ref_pcm, ref_split) = { - let (residue, split) = decode_capture_with_bits(&reference); - ( - our_decode(&reference).0, - bit_split_summary(&split, &residue), - ) - }; - - // Bit-split block: (floor, residue, packet, non-zero) per stream. - let (of, ores, op, onz) = ours_split; - let (rf, rres, rp, rnz) = ref_split; - bits.push_str(&format!( - "## {name} @ {kbps}k (ours {ours_kbps:.1} vs ref {ref_kbps:.1} kbps)\n" - )); - for (who, f, r, p, nz) in [("ours", of, ores, op, onz), ("ref ", rf, rres, rp, rnz)] { - bits.push_str(&format!( - "{who} floor {fb:>10.1}/s ({fpc:5.1}%) residue {rb:>10.1}/s ({rpc:5.1}%) other {ob:>8.1}/s nz {nz:>10} bits/nz {bnz:.2}\n", - fb = f as f64 / seconds, - fpc = 100.0 * f as f64 / p.max(1) as f64, - rb = r as f64 / seconds, - rpc = 100.0 * r as f64 / p.max(1) as f64, - ob = p.saturating_sub(f + r) as f64 / seconds, - bnz = r as f64 / nz.max(1) as f64, - )); - } - bits.push_str(&format!( - "ratio floor {:.3} residue {:.3} bits/nz {:.3}\n\n", - of as f64 / rf.max(1) as f64, - ores as f64 / rres.max(1) as f64, - (ores as f64 / onz.max(1) as f64) / (rres as f64 / rnz.max(1) as f64), - )); - - // Band error: align to the source exactly as the sweep does — - // common length from sample 0 (pre-roll trim inside `our_decode`). - let n = source_pcm[0] - .len() - .min(ours_pcm[0].len()) - .min(ref_pcm[0].len()); - let nb = EDGES.len() - 1; - let (mut e_src, mut e_ours, mut e_ref) = - (vec![0f64; nb], vec![0f64; nb], vec![0f64; nb]); - let (mut err_ours, mut err_ref) = (vec![0f64; nb], vec![0f64; nb]); - let mut spec: Vec<(Vec, Vec)> = (0..3) - .map(|_| (vec![0.0; FRAME], vec![0.0; FRAME])) - .collect(); - let mut start = 0; - while start + FRAME <= n { - for ch in 0..2 { - for (sig, pcm) in [&source_pcm, &ours_pcm, &ref_pcm].iter().enumerate() { - let s = &mut spec[sig]; - for i in 0..FRAME { - s.0[i] = f64::from(pcm[ch][start + i]) * window[i]; - s.1[i] = 0.0; - } - fft(&mut s.0, &mut s.1); - } - for (k, band) in band_of.iter().enumerate().take(FRAME / 2 + 1) { - let Some(b) = *band else { continue }; - let (sr, si) = (spec[0].0[k], spec[0].1[k]); - e_src[b] += sr * sr + si * si; - let (ur, ui) = (spec[1].0[k], spec[1].1[k]); - e_ours[b] += ur * ur + ui * ui; - let (dr, di) = (ur - sr, ui - si); - err_ours[b] += dr * dr + di * di; - let (vr, vi) = (spec[2].0[k], spec[2].1[k]); - e_ref[b] += vr * vr + vi * vi; - let (er, ei) = (vr - sr, vi - si); - err_ref[b] += er * er + ei * ei; - } - } - start += HOP; - } - let db = |e: f64, s: f64| { - if s > 0.0 { - 10.0 * (e / s).log10() - } else { - f64::NAN - } - }; - bands.push_str(&format!( - "## {name} @ {kbps}k (ours {ours_kbps:.1} vs ref {ref_kbps:.1} kbps)\n" - )); - bands.push_str("band NSR_ours NSR_ref dNSR E_ours E_ref\n"); - for b in 0..nb { - if e_src[b] == 0.0 { - continue; // no source energy: NSR/E undefined - } - let (nsr_o, nsr_r) = (db(err_ours[b], e_src[b]), db(err_ref[b], e_src[b])); - bands.push_str(&format!( - "{:<8} {:7.1} {:7.1} {:6.1} {:7.1} {:7.1}\n", - format!("{}-{}", EDGES[b] as usize, EDGES[b + 1] as usize), - nsr_o, - nsr_r, - nsr_o - nsr_r, - db(e_ours[b], e_src[b]), - db(e_ref[b], e_src[b]), - )); - } - let corr = |pcm: &[Vec]| { - (0..2) - .map(|c| correlation(&pcm[c][..n], &source_pcm[c][..n])) - .sum::() - / 2.0 - }; - bands.push_str(&format!( - "broadband corr: ours {:.4} ref {:.4}\n\n", - corr(&ours_pcm), - corr(&ref_pcm), - )); - eprintln!( - "{name}@{kbps}k: ours {ours_kbps:.1} ref {ref_kbps:.1} kbps, {:.1} s", - t0.elapsed().as_secs_f32() - ); - } - } - // Both report files above are written unconditionally, so a run that - // measured no source writes a report indistinguishable from a real one. - assert!(rows > 0, "no library sources were readable"); - for (text, file) in [ - (&bands, "vorbis-psy-r1.bands.txt"), - (&bits, "vorbis-psy-r1.bits.txt"), - ] { - let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../../lanes") - .join(file); - let mut f = File::create(&path).expect("create report"); - f.write_all(text.as_bytes()).expect("write report"); - println!("{file}: {}", path.display()); - } -} diff --git a/crates/ec-vorbis/tests/trim.rs b/crates/ec-vorbis/tests/trim.rs index 0f26c5cb..c2667306 100644 --- a/crates/ec-vorbis/tests/trim.rs +++ b/crates/ec-vorbis/tests/trim.rs @@ -7,7 +7,6 @@ use std::fs::File; use std::path::{Path, PathBuf}; -use std::process::Command; use ec_core::{Buf, Decoder, Demuxer, Frame, Packet, TimeBase}; use ec_ogg::{OggDemuxer, granule_of, granule_side_data}; @@ -22,7 +21,7 @@ fn scratch() -> PathBuf { /// A sine of `seconds` at `rate`, libvorbis-encoded to `path`. Returns the /// number of sample frames the source holds. fn encode(path: &Path, rate: u32, channels: u32, seconds: f64) -> usize { - let status = Command::new("ffmpeg") + let status = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i"]) .arg(format!( "sine=frequency=440:sample_rate={rate}:duration={seconds}" @@ -48,7 +47,7 @@ fn encode(path: &Path, rate: u32, channels: u32, seconds: f64) -> usize { /// ffmpeg's own decode, planar f32, one vector per channel. fn ffmpeg_decode(path: &Path, channels: usize) -> Vec> { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-i"]) .arg(path) .args(["-map", "0:a:0", "-f", "f32le", "-"])