diff --git a/Cargo.lock b/Cargo.lock index cc823cef..7281ffe9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -330,6 +330,7 @@ dependencies = [ "ec-dsp", "ec-matroska", "ec-mp4", + "ec-testkit", ] [[package]] @@ -338,6 +339,7 @@ version = "0.1.0" dependencies = [ "ec-core", "ec-dsp", + "ec-testkit", ] [[package]] @@ -347,6 +349,7 @@ dependencies = [ "ec-core", "ec-mp4", "ec-riff", + "ec-testkit", ] [[package]] @@ -356,6 +359,7 @@ dependencies = [ "ec-core", "ec-mp4", "ec-riff", + "ec-testkit", ] [[package]] diff --git a/crates/ec-aac/Cargo.toml b/crates/ec-aac/Cargo.toml index 812e8d74..802d3d16 100644 --- a/crates/ec-aac/Cargo.toml +++ b/crates/ec-aac/Cargo.toml @@ -13,3 +13,4 @@ ec-dsp = { workspace = true } [dev-dependencies] ec-mp4 = { workspace = true } ec-matroska = { workspace = true } +ec-testkit.workspace = true diff --git a/crates/ec-aac/fuzz/seed.sh b/crates/ec-aac/fuzz/seed.sh index 0c97ad54..84274d8b 100755 --- a/crates/ec-aac/fuzz/seed.sh +++ b/crates/ec-aac/fuzz/seed.sh @@ -18,8 +18,8 @@ mkdir -p "$HE_CORPUS" for f in "$HE_DIR"/*.aac; do cp -f "$f" "$HE_CORPUS/"; done echo "seeded $(ls "$HE_CORPUS" | wc -l) decode_he seeds" -FIXTURES=$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures/audio -[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/link-fixtures.sh (decode_he is seeded)" >&2; exit 0; } +FIXTURES=${EC_FIXTURES:-$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures}/audio +[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/fixtures.sh" >&2; exit 2; } ADTS=("$FIXTURES"/aac-adts-*.aac) [ -e "${ADTS[0]}" ] || { echo "seed.sh: no aac-adts-*.aac fixtures in $FIXTURES" >&2; exit 2; } diff --git a/crates/ec-aac/tests/common/mod.rs b/crates/ec-aac/tests/common/mod.rs deleted file mode 100644 index ef1af44a..00000000 --- a/crates/ec-aac/tests/common/mod.rs +++ /dev/null @@ -1,18 +0,0 @@ -//! Helpers shared by the ec-aac test binaries that need them: `oracle`, -//! `obs_real_content`, `sbr_real_library` and the merged `it` binary. - -use std::path::{Path, PathBuf}; -use std::process::Command; - -pub fn have_ffmpeg() -> bool { - Command::new("ffmpeg") - .arg("-version") - .output() - .map(|o| o.status.success()) - .unwrap_or(false) -} - -#[allow(dead_code)] // not used by the sbr_real_library binary -pub fn fixtures() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") -} diff --git a/crates/ec-aac/tests/it/implicit_sbr.rs b/crates/ec-aac/tests/it/implicit_sbr.rs index b37592c3..47c40add 100644 --- a/crates/ec-aac/tests/it/implicit_sbr.rs +++ b/crates/ec-aac/tests/it/implicit_sbr.rs @@ -2,28 +2,10 @@ //! ADTS header says plain AAC-LC, but whose frames carry an SBR extension //! payload, is decoded as HE-AAC at twice the core rate, as ffmpeg does. -use crate::shared::fixtures; -use crate::shared::have_ffmpeg; use std::path::{Path, PathBuf}; -use std::process::Command; use ec_aac::{AacDecoder, SbrSupport}; -/// Same contract as `oracle.rs`: an absent fixture skips loudly, and under -/// `EC_REQUIRE_FIXTURES=1` it is a hard failure instead. -fn require_fixture(path: &Path) -> bool { - let present = path.exists(); - assert!( - present || std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "EC_REQUIRE_FIXTURES=1 but fixture {} is absent", - path.display() - ); - if !present { - eprintln!("SKIP: fixture {} absent", path.display()); - } - present -} - /// The implicit-signalling HE-AAC fixture: 2 s of `heaac_44100_48k.m4a` remuxed to /// bare ADTS with `ffmpeg -c copy -f adts`. Its headers say AAC-LC at 22050 Hz. fn implicit_fixture() -> PathBuf { @@ -32,7 +14,7 @@ fn implicit_fixture() -> PathBuf { /// ffmpeg's decode of a file, as planar-by-channel `f32`. fn ffmpeg_decode(path: &Path) -> Vec> { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"]) @@ -112,9 +94,6 @@ fn decode_adts(path: &Path) -> (Vec>, Option, Vec, AacDecoder #[test] fn implicit_he_aac_adts_switches_to_double_rate() { let path = implicit_fixture(); - if !require_fixture(&path) { - return; - } let (ours, before, rates, decoder) = decode_adts(&path); // Headers say 22050 Hz AAC-LC: nothing is known about the rate before frame 1. @@ -139,14 +118,7 @@ fn implicit_he_aac_adts_switches_to_double_rate() { #[test] fn implicit_he_aac_adts_matches_ffmpeg_per_channel() { - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } let path = implicit_fixture(); - if !require_fixture(&path) { - return; - } let (ours, _, _, _) = decode_adts(&path); let theirs = ffmpeg_decode(&path); assert_eq!(theirs.len(), ours.len()); @@ -158,14 +130,7 @@ fn implicit_he_aac_adts_matches_ffmpeg_per_channel() { #[test] fn plain_aac_lc_adts_is_unchanged_by_implicit_detection() { - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } - let path = fixtures().join("audio/aac-adts-stereo-44100.aac"); - if !require_fixture(&path) { - return; - } + let path = ec_testkit::fixture("audio/aac-adts-stereo-44100.aac"); let (ours, _, rates, decoder) = decode_adts(&path); // A plain LC stream has no SBR payload: no switch, and the rate stays at the core. @@ -189,9 +154,6 @@ fn plain_aac_lc_adts_is_unchanged_by_implicit_detection() { #[test] fn core_only_decode_of_implicit_he_aac_stays_at_core_rate() { let path = implicit_fixture(); - if !require_fixture(&path) { - return; - } let data = std::fs::read(&path).expect("fixture readable"); let mut decoder = AacDecoder::new().core_only(); let mut frames = 0usize; diff --git a/crates/ec-aac/tests/it/main.rs b/crates/ec-aac/tests/it/main.rs index ba44c9f4..a7758904 100644 --- a/crates/ec-aac/tests/it/main.rs +++ b/crates/ec-aac/tests/it/main.rs @@ -1,8 +1,6 @@ #![forbid(unsafe_code)] //! Merged integration tests for ec-aac: one module per former `tests/*.rs` file. -#[path = "../common/mod.rs"] -mod shared; mod common; mod he_parity; diff --git a/crates/ec-aac/tests/it/multichannel_parity.rs b/crates/ec-aac/tests/it/multichannel_parity.rs index e4f28940..f6dd6f9a 100644 --- a/crates/ec-aac/tests/it/multichannel_parity.rs +++ b/crates/ec-aac/tests/it/multichannel_parity.rs @@ -11,13 +11,10 @@ //! then each channel's correlation must reach 0.999. For 5.1 and 7.1 the channel //! order is also checked: our channel k must correlate best with FFmpeg's channel k. //! -//! Fixtures are generated at test time, so no media is committed. Without ffmpeg -//! the test skips loudly; with `EC_REQUIRE_FIXTURES=1` a missing ffmpeg is a failure. use std::fs::File; use std::io::BufReader; use std::path::{Path, PathBuf}; -use std::process::Command; use ec_aac::{AacDecoder, is_adts, parse_adts}; use ec_core::{CodecId, Demuxer, Packet}; @@ -74,41 +71,13 @@ const LAYOUTS: &[Layout] = &[ Layout { name: "7.1", channels: 8, freqs: &[300, 450, 620, 780, 960, 1130, 1310, 1500] }, ]; -/// The encoders under test. Native `aac` is always present; `libfdk_aac` is used -/// only when the local ffmpeg lists it. const ENCODERS: &[&str] = &["aac", "libfdk_aac"]; fn fixtures_dir() -> PathBuf { PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("aac_multichannel") } -fn ffmpeg_ok(args: &[&str]) -> bool { - Command::new("ffmpeg") - .args(args) - .output() - .map(|o| o.status.success()) - .unwrap_or(false) -} - -fn have_ffmpeg() -> bool { - ffmpeg_ok(&["-version"]) -} - -fn have_encoder(name: &str) -> bool { - let out = Command::new("ffmpeg") - .args(["-hide_banner", "-encoders"]) - .output(); - match out { - Ok(o) => String::from_utf8_lossy(&o.stdout) - .lines() - .any(|l| l.split_whitespace().nth(1) == Some(name)), - Err(_) => false, - } -} - -/// Encodes a multitone of `layout` with `encoder` into `container`. Returns the path, -/// or `None` when the encoder refuses the configuration. -fn encode(layout: &Layout, encoder: &str, container: Container) -> Option { +fn encode(layout: &Layout, encoder: &str, container: Container) -> PathBuf { let dir = fixtures_dir(); std::fs::create_dir_all(&dir).expect("fixture dir"); let out = dir.join(format!( @@ -130,19 +99,20 @@ fn encode(layout: &Layout, encoder: &str, container: Container) -> Option Vec> { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args(["-f", "f32le", "-acodec", "pcm_f32le", "-ac"]) @@ -310,10 +280,7 @@ fn matrix(ours: &[Vec], theirs: &[Vec], lag: i64) -> Vec> { fn check_case(layout: &Layout, encoder: &str, container: Container, failures: &mut Vec) { let label = format!("{:<6} {:<5} {:<10}", layout.name, container.label(), encoder); - let Some(path) = encode(layout, encoder, container) else { - println!("SKIP {label}: encoder refused the configuration"); - return; - }; + let path = encode(layout, encoder, container); let theirs = ffmpeg_decode(&path, layout.channels); let (ours, channels, rate) = match container { Container::Adts => ours_adts(&path), @@ -369,20 +336,8 @@ fn check_case(layout: &Layout, encoder: &str, container: Container, failures: &m #[test] fn multichannel_matches_ffmpeg_per_channel() { - if !have_ffmpeg() { - assert!( - std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "EC_REQUIRE_FIXTURES=1 but ffmpeg is not installed" - ); - eprintln!("SKIP: ffmpeg not installed"); - return; - } let mut failures = Vec::new(); for encoder in ENCODERS { - if *encoder != "aac" && !have_encoder(encoder) { - println!("SKIP encoder {encoder}: not built into this ffmpeg"); - continue; - } for layout in LAYOUTS { for container in [Container::Adts, Container::Mp4] { check_case(layout, encoder, container, &mut failures); diff --git a/crates/ec-aac/tests/it/no_panic.rs b/crates/ec-aac/tests/it/no_panic.rs index e4a80c5f..42764da0 100644 --- a/crates/ec-aac/tests/it/no_panic.rs +++ b/crates/ec-aac/tests/it/no_panic.rs @@ -6,7 +6,6 @@ //! produced it instead of aborting the whole run. use std::panic::{catch_unwind, AssertUnwindSafe}; -use std::path::{Path, PathBuf}; use ec_aac::AacDecoder; @@ -40,10 +39,6 @@ impl Rng { } } -fn audio_dir() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio") -} - /// Decodes one packet with a fresh decoder. Returns false if it panicked. fn decode_no_panic(label: &str, packet: &[u8]) -> bool { let outcome = catch_unwind(AssertUnwindSafe(|| { @@ -76,27 +71,11 @@ fn adts_frame_starts(data: &[u8]) -> Vec { #[test] fn fixtures_truncated_and_corrupted_never_panic() { - let dir = audio_dir(); - let mut found = 0usize; let mut failures: Vec = Vec::new(); let mut rng = Rng(SEED); for name in ADTS_FIXTURES { - let path = dir.join(name); - let data = match std::fs::read(&path) { - Ok(d) => d, - Err(_) => { - if std::env::var_os("EC_REQUIRE_FIXTURES").is_some() { - panic!( - "EC_REQUIRE_FIXTURES=1 but fixture {} is absent -- regenerate with: scripts/gen-fixtures.sh", - path.display() - ); - } - eprintln!("SKIP: fixture {} absent", path.display()); - continue; - } - }; - found += 1; + let data = std::fs::read(ec_testkit::fixture(&format!("audio/{name}"))).expect("fixture"); assert!(!adts_frame_starts(&data).is_empty(), "{name} is not an ADTS stream"); // Ten truncation points spread across the file (never the full length). @@ -124,12 +103,6 @@ fn fixtures_truncated_and_corrupted_never_panic() { } } - if found == 0 { - if std::env::var_os("EC_REQUIRE_FIXTURES").is_some() { - panic!("no ADTS fixtures found under {}", dir.display()); - } - eprintln!("SKIP: no ADTS fixtures under {}", dir.display()); - } assert!(failures.is_empty(), "{} inputs panicked: {:?}", failures.len(), failures); } diff --git a/crates/ec-aac/tests/it/ps_mp4.rs b/crates/ec-aac/tests/it/ps_mp4.rs index cb128456..59bbf4d3 100644 --- a/crates/ec-aac/tests/it/ps_mp4.rs +++ b/crates/ec-aac/tests/it/ps_mp4.rs @@ -7,12 +7,10 @@ //! produce two channels at the extension rate, matching FFmpeg's own decode of //! the same mp4. -use crate::shared::have_ffmpeg; use crate::common::fixture; use std::fs::File; use std::io::BufReader; use std::path::{Path, PathBuf}; -use std::process::Command; use ec_aac::AacDecoder; use ec_core::{CodecId, Demuxer, Packet}; @@ -23,7 +21,7 @@ const RATE: u32 = 48_000; /// FFmpeg's decode of `path` as interleaved f32, two channels at `RATE`. fn ffmpeg_stereo(path: &Path) -> Vec { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args(["-f", "f32le", "-ac", "2", "-ar", "48000", "-"]) @@ -50,16 +48,11 @@ fn correlation(a: &[f32], b: &[f32]) -> f64 { #[test] fn ps_in_mp4_decodes_to_stereo_like_ffmpeg() { - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not installed"); - return; - } let src = fixture(FIXTURE); - assert!(src.exists(), "fixture {} is absent", src.display()); let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR")); std::fs::create_dir_all(&dir).expect("temp dir"); let mp4 = dir.join("ps_48000_music.m4a"); - let status = Command::new("ffmpeg") + let status = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-i"]) .arg(&src) .args(["-c", "copy", "-f", "mp4"]) diff --git a/crates/ec-aac/tests/it/ps_oracle.rs b/crates/ec-aac/tests/it/ps_oracle.rs index ff852e4f..1839e96e 100644 --- a/crates/ec-aac/tests/it/ps_oracle.rs +++ b/crates/ec-aac/tests/it/ps_oracle.rs @@ -6,13 +6,11 @@ //! at least 0.999 after a bounded lag search, which absorbs decoder priming //! delay, as `sbr_real_library.rs` does for HE-AAC v1. -use crate::shared::have_ffmpeg; use crate::common::fixture; use crate::common::deinterleave; use crate::common::correlation; use ec_aac::AacDecoder; use std::path::Path; -use std::process::Command; /// Per-channel correlation the reconstruction must reach against FFmpeg. const MIN_CORR: f64 = 0.999; @@ -39,7 +37,7 @@ const FIXTURES: &[(&str, u32)] = &[ /// FFmpeg's decode of `path` as planar stereo `f32`. fn ffmpeg_reference(path: &Path) -> Vec> { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args(["-ac", "2", "-f", "f32le", "-acodec", "pcm_f32le", "-"]) @@ -97,24 +95,9 @@ fn best_lag(ours: &[f32], theirs: &[f32]) -> (i64, f64) { #[test] fn ps_fixtures_decode_to_stereo_matching_ffmpeg() { - let require = std::env::var_os("EC_REQUIRE_FIXTURES").is_some(); - if !have_ffmpeg() { - assert!(!require, "EC_REQUIRE_FIXTURES=1 but ffmpeg is not installed"); - eprintln!("SKIP: ffmpeg not installed"); - return; - } let mut failures = Vec::new(); for &(name, rate) in FIXTURES { let path = fixture(name); - assert!( - path.exists() || !require, - "EC_REQUIRE_FIXTURES=1 but fixture {} is absent", - path.display() - ); - if !path.exists() { - eprintln!("SKIP: fixture {} absent", path.display()); - continue; - } let bytes = std::fs::read(&path).expect("fixture reads"); let audio = AacDecoder::new() .decode(&bytes, None) diff --git a/crates/ec-aac/tests/it/reelh_per_frame.rs b/crates/ec-aac/tests/it/reelh_per_frame.rs index 5b5648fa..e1c1e9ee 100644 --- a/crates/ec-aac/tests/it/reelh_per_frame.rs +++ b/crates/ec-aac/tests/it/reelh_per_frame.rs @@ -3,11 +3,8 @@ //! collapses mid-stream, sequentially, with no seek/reset. Finds the first //! bad frame and its side info, to compare with the frame before. -use crate::shared::have_ffmpeg; use std::fs::File; use std::io::BufReader; -use std::path::Path; -use std::process::Command; use ec_aac::AacDecoder; use ec_core::{CodecId, Demuxer, Packet}; @@ -15,21 +12,13 @@ use ec_mp4::Mp4Demuxer; #[test] fn reelh_per_frame_scan() { - if !have_ffmpeg() { - eprintln!("skip: no ffmpeg"); - return; - } - let path = Path::new("/home/user/Downloads/reelh.mp4"); - if !path.exists() { - eprintln!("skip: file not present"); - return; - } + let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"); let _knob = ec_aac::knobs::set_tool_sideinfo_debug(Some(true)); // ffmpeg's channel-0-only decode (pan, not -ac, per the repro). - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) - .arg(path) + .arg(&path) .args([ "-map", "0:a:0", "-af", "pan=1c|c0=c0", "-f", "f32le", "-acodec", "pcm_f32le", "-", ]) @@ -43,7 +32,7 @@ fn reelh_per_frame_scan() { .collect(); // Our sequential decode: one decoder, no reset, packet 0 onward. - let f = File::open(path).unwrap(); + let f = File::open(&path).unwrap(); let mut d = Mp4Demuxer::new(BufReader::new(f)).unwrap(); let aac = d .streams() diff --git a/crates/ec-aac/tests/obs_real_content.rs b/crates/ec-aac/tests/obs_real_content.rs deleted file mode 100644 index ebca9b19..00000000 --- a/crates/ec-aac/tests/obs_real_content.rs +++ /dev/null @@ -1,249 +0,0 @@ -//! Table over every screen recording under `~/Videos/OBS`, diagnosing the -//! PNS/M/S decorrelation the consumer sweep found in that encoder's output -//! (see repo ledger). Real files, read-only, absent directory skips loudly. - -mod common; - -use common::have_ffmpeg; -use std::path::{Path, PathBuf}; -use std::process::Command; - -use ec_aac::AacDecoder; -use ec_core::{CodecId, Demuxer, Packet}; -use ec_mp4::Mp4Demuxer; -use std::fs::File; -use std::io::BufReader; - -const MAX_SAMPLES: usize = 480_000; // 10s @ 48kHz -const LAG_MAX: usize = 4_000; -const WINDOW: usize = 200_000; - -fn ffmpeg_decode(path: &Path, channels: usize) -> Vec> { - let out = Command::new("ffmpeg") - .args(["-v", "error", "-i"]) - .arg(path) - .args([ - "-map", - "0:a:0", - "-t", - "10", - "-f", - "f32le", - "-acodec", - "pcm_f32le", - "-", - ]) - .output() - .expect("ffmpeg runs"); - assert!( - out.status.success(), - "{}", - String::from_utf8_lossy(&out.stderr) - ); - let samples: Vec = out - .stdout - .as_chunks::<4>().0.iter() - .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]])) - .collect(); - let mut planes = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels]; - for (i, &v) in samples.iter().enumerate() { - planes[i % channels].push(v); - } - planes -} - -fn extract_aac_track(path: &Path) -> Option<(Vec, Vec>)> { - let f = File::open(path).ok()?; - let mut d = Mp4Demuxer::new(BufReader::new(f)).ok()?; - let aac = d - .streams() - .iter() - .find(|s| s.params.codec == CodecId::Aac)?; - let idx = aac.index; - let asc = aac.params.extradata.as_ref()?.to_vec(); - let mut aus = Vec::new(); - while aus.len() < 1_500 { - match d.next_packet() { - Ok(Packet { stream, data, .. }) if stream == idx => aus.push(data.to_vec()), - Ok(_) => continue, - Err(_) => break, - } - } - Some((asc, aus)) -} - -fn our_decode(path: &Path) -> Option>> { - let (asc, aus) = extract_aac_track(path)?; - let mut decoder = AacDecoder::with_config_bytes(&asc).ok()?; - let mut planes: Vec> = Vec::new(); - let mut failed = 0usize; - for au in &aus { - let frame = match decoder.decode(au, None) { - Ok(f) => f, - Err(_) => { - failed += 1; - continue; - } - }; - let ch = usize::from(frame.channels); - if ch == 0 { - continue; - } - if planes.is_empty() { - planes = vec![Vec::new(); ch]; - } - for (i, v) in frame.samples.iter().enumerate() { - planes[i % ch].push(*v); - } - if planes[0].len() >= MAX_SAMPLES { - break; - } - } - eprintln!(" {failed}/{} AUs failed", aus.len()); - if planes.is_empty() { - None - } else { - Some(planes) - } -} - -fn dot(a: &[f32], b: &[f32]) -> f64 { - a.iter() - .zip(b) - .map(|(x, y)| f64::from(*x) * f64::from(*y)) - .sum() -} - -fn correlation(a: &[f32], b: &[f32]) -> f64 { - let n = a.len().min(b.len()); - if n < 1024 { - return 0.0; - } - let (a, b) = (&a[..n], &b[..n]); - let ma = a.iter().map(|v| f64::from(*v)).sum::() / n as f64; - let mb = b.iter().map(|v| f64::from(*v)).sum::() / n as f64; - let ac: Vec = a.iter().map(|v| (f64::from(*v) - ma) as f32).collect(); - let bc: Vec = b.iter().map(|v| (f64::from(*v) - mb) as f32).collect(); - let num = dot(&ac, &bc); - let den = (dot(&ac, &ac) * dot(&bc, &bc)).sqrt(); - if den == 0.0 { 0.0 } else { num / den } -} - -fn best_lag_correlation(ours: &[f32], theirs: &[f32]) -> (i64, f64) { - const COARSE: usize = 4_096; - let start = ours - .len() - .min(theirs.len()) - .saturating_sub(WINDOW) - .min(ours.len() / 4); - let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> { - let (oa, ob) = if lag >= 0 { - (start, start + lag as usize) - } else { - (start + (-lag) as usize, start) - }; - if oa + len > ours.len() || ob + len > theirs.len() { - None - } else { - Some((oa, ob)) - } - }; - let mut coarse_best = (0i64, -1.0f64, 0.0f64); - for lag in -(LAG_MAX as i64)..=(LAG_MAX as i64) { - let Some((oa, ob)) = slice_at(lag, COARSE) else { - continue; - }; - let c = correlation(&ours[oa..oa + COARSE], &theirs[ob..ob + COARSE]); - if c.abs() > coarse_best.1 { - coarse_best = (lag, c.abs(), c); - } - } - let mut best = (coarse_best.0, -1.0f64, 0.0f64); - for lag in (coarse_best.0 - 8)..=(coarse_best.0 + 8) { - let Some((oa, ob)) = slice_at(lag, WINDOW) else { - continue; - }; - let c = correlation(&ours[oa..oa + WINDOW], &theirs[ob..ob + WINDOW]); - if c.abs() > best.1 { - best = (lag, c.abs(), c); - } - } - (best.0, best.2) -} - -fn rms(a: &[f32]) -> f64 { - (a.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::() / a.len().max(1) as f64).sqrt() -} - -#[test] -fn obs_content_table() { - if !have_ffmpeg() { - eprintln!("skip: no ffmpeg"); - return; - } - // lane-h264reallib: `unwrap_or_default()` rather than a bare `unwrap()`. - // A host with no HOME -- a fleet runner -- panicked here before reaching - // the `read_dir` guard one line down, which already reports an absent - // directory correctly. With an empty HOME the guard simply reports - // `skip: no ./Videos/OBS`, so the test degrades to the silent skip its - // own guard was written for instead of a red that says nothing about AAC. - let dir = PathBuf::from(std::env::var("HOME").unwrap_or_default()).join("Videos/OBS"); - let Ok(rd) = std::fs::read_dir(&dir) else { - eprintln!("skip: no {}", dir.display()); - return; - }; - let mut files: Vec = rd - .filter_map(|e| e.ok()) - .map(|e| e.path()) - .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("mp4")) - .collect(); - files.sort(); - let _knob = ec_aac::knobs::set_tool_sideinfo_debug(Some(true)); - for path in files { - eprintln!("== {}", path.display()); - let before = ec_aac::tool_sideinfo_log().len(); - let Some(ours) = our_decode(&path) else { - eprintln!(" our_decode: None"); - continue; - }; - let theirs = ffmpeg_decode(&path, ours.len()); - for (ch, (o, t)) in ours.iter().zip(theirs.iter()).enumerate() { - let (lag, corr) = best_lag_correlation(o, t); - // Also the direct, un-windowed corr from t=0 (no lag search) -- - // this is what the consumer sweep that found this regression - // measured, and can disagree with the windowed/lag-searched - // number above if only part of the file is corrupted. - let corr0 = correlation(o, t); - let non_finite = o.iter().filter(|v| !v.is_finite()).count(); - eprintln!( - " ch{ch}: corr={corr:.4} corr@lag0={corr0:.4} lag={lag} rms_ours={:.5} rms_ffmpeg={:.5} non_finite={non_finite}", - rms(o), - rms(t) - ); - } - let all_rows = ec_aac::tool_sideinfo_log(); - let rows = &all_rows[before..]; - let (mut pns, mut is_, mut ms, mut tns, mut cpe) = (0usize, 0usize, 0usize, 0usize, 0usize); - for r in rows { - if r.pns_bands > 0 { - pns += 1; - } - if r.is_bands > 0 { - is_ += 1; - } - if r.ms_bands > 0 { - ms += 1; - } - if r.tns_present { - tns += 1; - } - if r.is_cpe { - cpe += 1; - } - } - eprintln!( - " tools over {} AUs: cpe={cpe} pns_aus={pns} is_aus={is_} ms_aus={ms} tns_aus={tns}", - rows.len() - ); - } -} diff --git a/crates/ec-aac/tests/oracle.rs b/crates/ec-aac/tests/oracle.rs index 1f5986ae..02802b2e 100644 --- a/crates/ec-aac/tests/oracle.rs +++ b/crates/ec-aac/tests/oracle.rs @@ -1,42 +1,11 @@ -//! Decoder and encoder against ffmpeg, on the generated fixtures and on the -//! real library. Every test that needs a fixture or ffmpeg skips loudly when it -//! is absent rather than passing quietly. -mod common; - -use common::{fixtures, have_ffmpeg}; use std::path::{Path, PathBuf}; -use std::process::Command; use ec_aac::{AacDecoder, AacEncoder, AacEncoderConfig}; -/// Fixture-presence probe for the committed `fixtures/audio` media this file -/// decodes. 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 -} - /// ffmpeg's decode of a file, as planar-by-channel `f32`. fn ffmpeg_decode(path: &Path, channels: usize) -> Vec> { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"]) @@ -128,11 +97,6 @@ fn compare(path: &Path) -> Vec { #[test] fn adts_fixtures_match_ffmpeg_per_channel() { - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } - let dir = fixtures().join("audio"); let mut checked = 0; for name in [ "aac-adts-mono-44100.aac", @@ -142,10 +106,7 @@ fn adts_fixtures_match_ffmpeg_per_channel() { "aac-adts-5.1-44100.aac", "aac-adts-5.1-48000.aac", ] { - let path = dir.join(name); - if !require_fixture(&path, "scripts/gen-fixtures.sh") { - continue; - } + let path = ec_testkit::fixture(&format!("audio/{name}")); let corr = compare(&path); println!("{name}: {corr:?}"); for (ch, c) in corr.iter().enumerate() { @@ -164,11 +125,6 @@ fn adts_fixtures_match_ffmpeg_per_channel() { #[test] fn mp4_fixtures_match_ffmpeg_per_channel() { - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } - let dir = fixtures().join("audio"); let tmp = std::env::temp_dir().join("ec-aac-mp4-oracle"); std::fs::create_dir_all(&tmp).expect("temp dir"); let mut checked = 0; @@ -177,14 +133,11 @@ fn mp4_fixtures_match_ffmpeg_per_channel() { "aac-mp4-stereo-48000.mp4", "aac-mp4-5.1-48000.mp4", ] { - let path = dir.join(name); - if !require_fixture(&path, "scripts/gen-fixtures.sh") { - continue; - } + let path = ec_testkit::fixture(&format!("audio/{name}")); // The mp4 side of the family is another slice; the elementary stream // comes out with a stream copy so this test stays about AAC. let adts = tmp.join(format!("{name}.aac")); - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-i"]) .arg(&path) .args(["-c:a", "copy", "-f", "adts"]) @@ -211,22 +164,14 @@ fn mp4_fixtures_match_ffmpeg_per_channel() { /// its bands before M/S and intensity stereo combine them. #[test] fn aac_coding_tools_match_ffmpeg_in_isolation() { - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } - let dir = fixtures().join("audio"); let tmp = std::env::temp_dir().join("ec-aac-tools-oracle"); std::fs::create_dir_all(&tmp).expect("temp dir"); let mut checked = 0; for tool in ["pns", "is", "ms", "tns", "all"] { let name = format!("aac-tool-{tool}-mp4-stereo-48000.m4a"); - let path = dir.join(&name); - if !require_fixture(&path, "scripts/gen-fixtures.sh") { - continue; - } + let path = ec_testkit::fixture(&format!("audio/{name}")); let adts = tmp.join(format!("{name}.aac")); - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-i"]) .arg(&path) .args(["-c:a", "copy", "-f", "adts"]) @@ -258,17 +203,13 @@ fn aac_coding_tools_match_ffmpeg_in_isolation() { /// wrong element order shows up as the wrong tone on the wrong channel. #[test] fn five_one_comes_out_in_film_order() { - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } let tmp = std::env::temp_dir().join("ec-aac-order"); std::fs::create_dir_all(&tmp).expect("temp dir"); let src = tmp.join("order.aac"); // The LFE tone stays low: the reference encoder band-limits that channel, // and a 1.5 kHz tone would simply not survive the trip. let tones = [300.0, 700.0, 1100.0, 60.0, 1900.0, 2300.0]; - let mut cmd = Command::new("ffmpeg"); + let mut cmd = ec_testkit::ffmpeg(); cmd.args(["-v", "error", "-y"]); for f in tones { cmd.args([ @@ -424,19 +365,11 @@ fn best_correlation(source: &[f32], decoded: &[f32]) -> f64 { /// lossless fixtures at the same bitrates. #[test] fn encoder_beats_the_incumbent_bar() { - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } - let dir = fixtures().join("audio"); let tmp = std::env::temp_dir().join("ec-aac-bar"); std::fs::create_dir_all(&tmp).expect("temp dir"); let mut checked = 0; for (name, channels, kbps, bar) in INCUMBENT_BAR { - let src = dir.join(format!("flac-{name}-48000.flac")); - if !require_fixture(&src, "scripts/gen-fixtures.sh") { - continue; - } + let src = ec_testkit::fixture(&format!("audio/flac-{name}-48000.flac")); let source = ffmpeg_decode(&src, *channels); let mut interleaved = Vec::with_capacity(source[0].len() * channels); for i in 0..source[0].len() { @@ -493,20 +426,12 @@ const LAYOUT_BAR: &[(&str, usize, u32, f64, &str)] = &[ /// ADTS rate within 5% of the target. #[test] fn encoder_meets_every_layout_bar() { - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } - let dir = fixtures().join("audio"); let tmp = std::env::temp_dir().join("ec-aac-layout-bar"); std::fs::create_dir_all(&tmp).expect("temp dir"); let mut checked = 0; let mut failed = Vec::new(); for (name, channels, kbps, bar, incumbent) in LAYOUT_BAR { - let src = dir.join(format!("flac-{name}-48000.flac")); - if !require_fixture(&src, "scripts/gen-aac-layouts.sh OUTDIR (3.0, 4.0, 5.0, 7.1)") { - continue; - } + let src = ec_testkit::fixture(&format!("audio/flac-{name}-48000.flac")); let source = ffmpeg_decode(&src, *channels); let mut interleaved = Vec::with_capacity(source[0].len() * channels); for i in 0..source[0].len() { @@ -622,7 +547,7 @@ fn noisy_clip(name: &str, dir: &Path) -> PathBuf { .iter() .find(|(n, _, _)| *n == name) .expect("a NOISY_CLIPS entry"); - let mut cmd = Command::new("ffmpeg"); + let mut cmd = ec_testkit::ffmpeg(); cmd.args(["-v", "error", "-y"]); for input in *inputs { cmd.args(["-f", "lavfi", "-i", input]); @@ -642,10 +567,6 @@ fn noisy_clip(name: &str, dir: &Path) -> PathBuf { /// correlation against the incumbent's bar, and the ADTS rate within 5% of the target. #[test] fn encoder_meets_noisy_bar() { - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } let tmp = std::env::temp_dir().join("ec-aac-noisy-bar"); std::fs::create_dir_all(&tmp).expect("temp dir"); let mut failed = Vec::new(); @@ -706,10 +627,6 @@ fn tone_pcm(rate: u32, channels: usize, secs: f64) -> Vec { #[test] fn encoder_output_decodes_in_ffmpeg_without_warnings() { - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } let tmp = std::env::temp_dir().join("ec-aac-enc"); std::fs::create_dir_all(&tmp).expect("temp dir"); for (channels, kbps) in [(1u16, 96u32), (2, 128), (2, 192), (6, 384)] { @@ -719,7 +636,7 @@ fn encoder_output_decodes_in_ffmpeg_without_warnings() { assert!(!adts.is_empty(), "{channels}ch encode produced nothing"); let path = tmp.join(format!("enc-{channels}ch-{kbps}k.aac")); std::fs::write(&path, &adts).expect("write"); - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "warning", "-i"]) .arg(&path) .args(["-f", "null", "-"]) @@ -816,10 +733,6 @@ fn band_tables_span_the_window() { /// means in practice. #[test] fn asc_matches_the_one_ffmpeg_writes() { - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } let tmp = std::env::temp_dir().join("ec-aac-esds"); std::fs::create_dir_all(&tmp).expect("temp dir"); for (channels, rate) in [(1u16, 48_000u32), (2, 48_000), (2, 44_100), (6, 48_000)] { @@ -828,7 +741,7 @@ fn asc_matches_the_one_ffmpeg_writes() { let src = tmp.join(format!("asc-{channels}-{rate}.aac")); std::fs::write(&src, &adts).expect("write"); let mp4 = tmp.join(format!("asc-{channels}-{rate}.mp4")); - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-y", "-i"]) .arg(&src) .args(["-c:a", "copy"]) @@ -903,146 +816,10 @@ fn esds_asc(mp4: &[u8]) -> Option> { None } -/// AAC tracks from the machine's own library, not just generated fixtures: the -/// elementary stream is copied out to ADTS and decoded both ways. -// lane-h264reallib: same shape as the ec-h264 `real_library_streams_match_ffmpeg` -// fix, same reason. The manifest is generated by `scripts/scan-real-library.sh` -// from `~/Videos ~/Downloads ~/Music` and is gitignored because it is -// machine-local. The guard below makes a host with NO manifest print green -// (nothing was checked), and a host that ran the scan but has since moved or -// deleted files falls through to `checked >= 3` and goes red for a reason that -// has nothing to do with the decoder. An ignore is visible in `--list` and -// cannot go green silently, which an env gate would. -// Run on the workstation: cargo test -p ec-aac --test oracle real_library_tracks_match_ffmpeg -- --ignored -#[ignore = "sweeps the PERSONAL media library (~/Videos, ~/Downloads, ~/Music) through the gitignored fixtures/real-library-manifest.tsv and asserts >= 3 tracks swept; a runner host has no such library, so it is either a silent green or a red for the wrong reason. Run it on the workstation with --ignored."] -#[test] -fn real_library_tracks_match_ffmpeg() { - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } - let manifest = fixtures().join("real-library-manifest.tsv"); - let Ok(text) = std::fs::read_to_string(&manifest) else { - eprintln!("SKIP: no real-library manifest; run scripts/scan-real-library.sh"); - return; - }; - let tmp = std::env::temp_dir().join("ec-aac-real"); - std::fs::create_dir_all(&tmp).expect("temp dir"); - let mut stereo = 0; - let mut wide = 0; - let mut checked = 0; - for line in text.lines().skip(1) { - if stereo >= 3 && wide >= 2 { - break; - } - let path = line.split('\t').next().unwrap_or_default(); - if path.is_empty() || !line.to_lowercase().contains("aac") { - continue; - } - let file = Path::new(path); - if !file.exists() { - continue; - } - let Some((index, channels, profile)) = aac_stream(file) else { - continue; - }; - // HE-AAC is reported, not decoded: see `sbr_is_reported_not_silently_upsampled`. - if profile.contains("HE-AAC") { - continue; - } - if channels <= 2 { - if stereo >= 3 { - continue; - } - stereo += 1; - } else { - if wide >= 2 { - continue; - } - wide += 1; - } - let adts = tmp.join(format!("real-{checked}.aac")); - let out = Command::new("ffmpeg") - .args(["-v", "error", "-y", "-t", "20", "-i"]) - .arg(file) - .args(["-map", &format!("0:{index}"), "-c:a", "copy", "-f", "adts"]) - .arg(&adts) - .output() - .expect("ffmpeg runs"); - if !out.status.success() { - eprintln!("SKIP {path}: stream copy failed"); - continue; - } - let corr = compare(&adts); - let worst = corr.iter().copied().fold(f64::MAX, f64::min); - println!( - "real {channels}ch {profile} worst {worst:.6} -- {}", - file.file_name().unwrap_or_default().to_string_lossy() - ); - for (ch, c) in corr.iter().enumerate() { - assert!( - *c >= 0.999, - "channel {ch} correlation {c:.6} < 0.999 for {path}" - ); - } - checked += 1; - } - assert!( - checked >= 3, - "wanted at least three library tracks, swept {checked}" - ); - assert!(wide >= 1, "no multichannel AAC track was swept"); -} - -/// The first AAC audio stream of a file: `(stream index, channels, profile)`. -fn aac_stream(path: &Path) -> Option<(usize, usize, String)> { - let out = Command::new("ffprobe") - .args([ - "-v", - "error", - "-select_streams", - "a", - "-show_entries", - "stream=index,codec_name,channels,profile", - "-of", - "default=noprint_wrappers=1", - ]) - .arg(path) - .output() - .ok()?; - let text = String::from_utf8_lossy(&out.stdout); - let (mut index, mut channels, mut codec, mut profile) = - (None, None, String::new(), String::new()); - for line in text.lines() { - let (key, value) = line.split_once('=')?; - match key { - "index" => { - if codec == "aac" { - return Some((index?, channels?, profile)); - } - index = value.parse().ok(); - codec.clear(); - profile.clear(); - } - "codec_name" => codec = value.to_string(), - "channels" => channels = value.parse().ok(), - "profile" => profile = value.to_string(), - _ => {} - } - } - if codec == "aac" { - return Some((index?, channels?, profile)); - } - None -} - /// Decode speed on 5.1, the shape a film soundtrack has. #[test] fn five_one_decodes_faster_than_realtime() { - let path = fixtures().join("audio/aac-adts-5.1-48000.aac"); - if !require_fixture(&path, "scripts/gen-fixtures.sh") { - return; - } + let path = ec_testkit::fixture("audio/aac-adts-5.1-48000.aac"); let data = std::fs::read(&path).expect("fixture readable"); let rounds = 8; let start = std::time::Instant::now(); @@ -1078,170 +855,3 @@ fn five_one_decodes_faster_than_realtime() { ); } } - -/// The one HE-AAC track in this machine's library, decoded to its AAC-LC core. -/// The claim under test is the honest one: the core comes out, at the core -/// rate, matching what a reference decoder makes of the same core band. -#[test] -fn he_aac_library_track_decodes_to_its_core() { - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } - let manifest = fixtures().join("real-library-manifest.tsv"); - let Ok(text) = std::fs::read_to_string(&manifest) else { - eprintln!("SKIP: no real-library manifest"); - return; - }; - let tmp = std::env::temp_dir().join("ec-aac-he"); - std::fs::create_dir_all(&tmp).expect("temp dir"); - for line in text.lines().skip(1) { - let path = line.split('\t').next().unwrap_or_default(); - let file = Path::new(path); - if path.is_empty() || !file.exists() { - continue; - } - let Some((index, _, profile)) = aac_stream_matching(file, "HE-AAC") else { - continue; - }; - let _ = profile; - let adts = tmp.join("he.aac"); - let out = Command::new("ffmpeg") - .args(["-v", "error", "-y", "-t", "10", "-i"]) - .arg(file) - .args(["-map", &format!("0:{index}"), "-c:a", "copy", "-f", "adts"]) - .arg(&adts) - .output() - .expect("ffmpeg runs"); - if !out.status.success() { - continue; - } - let (ours, rate) = our_decode(&adts); - assert!(!ours.is_empty(), "the HE-AAC core decoded to nothing"); - // The reference decode carries SBR, so it runs at twice this rate; - // resampling it down to the core rate low-passes exactly the band the - // core carries, which is the part we are claiming to reproduce. - let core = tmp.join("he-core.f32"); - let out = Command::new("ffmpeg") - .args(["-v", "error", "-y", "-i"]) - .arg(&adts) - .args(["-ar", &rate.to_string(), "-f", "f32le"]) - .arg(&core) - .output() - .expect("ffmpeg runs"); - assert!( - out.status.success(), - "reference decode of the HE-AAC track failed" - ); - let theirs = deinterleave( - &bytes_to_f32(&std::fs::read(&core).expect("read")), - ours.len(), - ); - // Sample-by-sample comparison would need the reference resampler's own - // delay; the claim here is about *content*, so it is checked on the - // long-term band energies, which no delay moves. - let corr: Vec = ours - .iter() - .zip(&theirs) - .map(|(a, b)| pearson(&band_energies(a, rate), &band_energies(b, rate))) - .collect(); - let worst = corr.iter().copied().fold(f64::MAX, f64::min); - println!("HE-AAC core at {rate} Hz: band-energy match, worst channel {worst:.4} {corr:?}"); - assert!( - worst >= 0.95, - "the AAC-LC core of an HE-AAC track should carry the reference's \ - core band; worst channel {worst:.4}" - ); - return; - } - eprintln!("SKIP: no HE-AAC track in the library manifest"); -} - -/// Pearson correlation with no minimum length: for short feature vectors. -fn pearson(a: &[f32], b: &[f32]) -> f64 { - let n = a.len().min(b.len()); - let ma = a[..n].iter().map(|v| f64::from(*v)).sum::() / n as f64; - let mb = b[..n].iter().map(|v| f64::from(*v)).sum::() / n as f64; - let (mut num, mut da, mut db) = (0.0, 0.0, 0.0); - for i in 0..n { - let (x, y) = (f64::from(a[i]) - ma, f64::from(b[i]) - mb); - num += x * y; - da += x * x; - db += y * y; - } - if da == 0.0 || db == 0.0 { - return 1.0; - } - num / (da * db).sqrt() -} - -/// Long-term energy in 32 logarithmic bands: a spectral fingerprint that a -/// resampler's delay cannot shift. -fn band_energies(samples: &[f32], rate: u32) -> Vec { - let bands = 32usize; - let mut out = vec![0.0f64; bands]; - let n = 1024usize; - let mut blocks = 0usize; - for chunk in samples.chunks_exact(n).take(400) { - blocks += 1; - for (b, slot) in out.iter_mut().enumerate() { - // Geometric spacing from 100 Hz to the Nyquist limit. - let lo = 100.0 * (f64::from(rate) / 2.0 / 100.0).powf(b as f64 / bands as f64); - let hi = 100.0 * (f64::from(rate) / 2.0 / 100.0).powf((b + 1) as f64 / bands as f64); - let (mut re, mut im) = (0.0f64, 0.0f64); - let f = (lo * hi).sqrt(); - let w = 2.0 * std::f64::consts::PI * f / f64::from(rate); - for (i, &v) in chunk.iter().enumerate() { - re += f64::from(v) * (w * i as f64).cos(); - im += f64::from(v) * (w * i as f64).sin(); - } - *slot += (re * re + im * im).sqrt(); - } - } - out.iter() - .map(|v| ((v / blocks.max(1) as f64) + 1e-9).ln() as f32) - .collect() -} - -fn aac_stream_matching(path: &Path, want: &str) -> Option<(usize, usize, String)> { - let out = Command::new("ffprobe") - .args([ - "-v", - "error", - "-select_streams", - "a", - "-show_entries", - "stream=index,codec_name,channels,profile", - "-of", - "default=noprint_wrappers=1", - ]) - .arg(path) - .output() - .ok()?; - let text = String::from_utf8_lossy(&out.stdout); - let mut index = None; - let mut channels = None; - let mut codec = String::new(); - let mut profile = String::new(); - for line in text.lines() { - let (key, value) = line.split_once('=')?; - match key { - "index" => { - if codec == "aac" && profile.contains(want) { - return Some((index?, channels?, profile)); - } - index = value.parse().ok(); - codec.clear(); - profile.clear(); - } - "codec_name" => codec = value.to_string(), - "channels" => channels = value.parse().ok(), - "profile" => profile = value.to_string(), - _ => {} - } - } - if codec == "aac" && profile.contains(want) { - return Some((index?, channels?, profile)); - } - None -} diff --git a/crates/ec-aac/tests/sbr_real_library/chunk_a.rs b/crates/ec-aac/tests/sbr_real_library/chunk_a.rs index ee583c96..48bad545 100644 --- a/crates/ec-aac/tests/sbr_real_library/chunk_a.rs +++ b/crates/ec-aac/tests/sbr_real_library/chunk_a.rs @@ -25,15 +25,8 @@ use super::*; #[test] pub(super) fn core_only_matches_reference() { let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } for c in &candidates() { - let Some((ours, core_rate)) = our_decode_core_only(&c.path, c.aac_stream) else { - eprintln!("SKIP {}: could not core-decode", c.path.display()); - continue; - }; + let (ours, core_rate) = our_decode_core_only(&c.path, c.aac_stream).expect("core decode"); let theirs = ffmpeg_decode_at_rate(&c.path, c.ffmpeg_stream, ours.len(), core_rate); println!( "{} core-only ({} ch, {} Hz):", @@ -101,10 +94,6 @@ pub(super) fn dump_sideinfo_kx() { #[test] pub(super) fn wide_lag_search_full_chain() { let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } for c in &candidates() { let Some((ours, sbr, rate)) = our_decode(&c.path, c.aac_stream) else { continue; @@ -227,42 +216,12 @@ pub(super) fn full_chain_low_band_matches_own_core() { } } -/// Round-52: a controlled fixture matrix -- unlike reeln/FMJ (one real -/// file each, whose sample rate, bitrate and content all differ at once), -/// every row here decodes the SAME synthesized source (three summed sine -/// sweeps 100 Hz-18 kHz + seeded pink noise, per-channel phase offset), -/// varying only sample rate (44100/48000) and bitrate (32k/48k/64k/96k, -/// which sweeps the SBR crossover `kx`/`k2`), so a break tied to a rate -/// FAMILY or to `kx` GEOMETRY shows as a pattern across the table instead -/// of being confounded with one file's own content. `aac_low` control rows -/// (no SBR at all) prove the harness itself -- container extraction, -/// decode, correlation -- is sound before the HE-AAC rows next to them are -/// trusted; those are the only asserted numbers here, everything else is -/// instrumentation for the ledger, not a regression gate yet. -/// -/// Env-gated on `EC_AAC_HEAAC_FIXTURES` (defaults to the same -/// `/.cache/heaac-fixtures` `scripts/aac-tables/make-heaac-fixtures.sh` -/// writes to) -- skips loudly, generates nothing itself, when that -/// directory is absent. #[test] pub(super) fn synthetic_heaac_matrix() { let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } - let dir = std::env::var("EC_AAC_HEAAC_FIXTURES") - .unwrap_or_else(|_| format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR"))); - let dir = PathBuf::from(dir); - if !require_fixture(&dir, "scripts/aac-tables/make-heaac-fixtures.sh") { - return; - } let _knob = ec_aac::knobs::set_sbr_sideinfo_debug(Some(true)); println!( - "{:>5} {:>6} {:>4} {:>4} {:>4} {:>8} {:>8} {:>8} {:>6} {:>11} {:>8} {:>10} {:>8} {:>9} {:>9}", - "rate", - "kbps", - "prof", + "{:>4} {:>4} {:>8} {:>8} {:>8} {:>6} {:>11} {:>8} {:>10} {:>8} {:>9} {:>9}", "kx", "k2", "full", @@ -281,295 +240,137 @@ pub(super) fn synthetic_heaac_matrix() { // samples at the doubled/full output rate) both land well inside it, // not right at the edge the way the plain (LAG_MAX=4000) search did. const WIDE_LAG_MAX: i64 = 20_000; - // Floor: the matrix is 2 rates x 4 bitrates x 2 profiles. Without a count - // the whole test is green having probed nothing, which is the same - // false-green this file's `require_fixture` exists to kill. - let mut probed = 0usize; - for rate in [48_000u32, 44_100] { - for br in ["32k", "48k", "64k", "96k"] { - // LC first: its winning lag is the pure container/decoder - // priming delay with no SBR chain involved, and is reused below - // as the anchor for the HE row's own delay-candidate probe. - let mut lc_lag: Option = None; - for (profile, prefix) in [("LC", "lc"), ("HE", "heaac")] { - let path = dir.join(format!("{prefix}_{rate}_{br}.m4a")); - if !require_fixture(&path, "scripts/aac-tables/make-heaac-fixtures.sh") { - continue; - } - probed += 1; - let before = ec_aac::sbr_sideinfo_log().len(); - let Some((ours, _sbr, our_rate)) = our_decode(&path, 0) else { - eprintln!("SKIP {}: could not decode", path.display()); - continue; - }; - let rows = ec_aac::sbr_sideinfo_log(); - let (kx, k2) = rows[before..] - .iter() - .find(|r| r.ch == 0) - .map(|r| (r.kx, r.k2)) - .unwrap_or((-1, -1)); - let theirs = ffmpeg_decode(&path, 0, ours.len()); - let o = &ours[0]; - let t = &theirs[0]; - const TOPK: usize = 5; - let (mut lag, mut full, edge) = robust_lag_topk(o, t, WIDE_LAG_MAX, our_rate, TOPK); - assert!( - !edge, - "{}: {profile} row's refined winning lag {lag} sits at the \ - +/-{WIDE_LAG_MAX} search's own edge", - path.display() - ); - if profile == "LC" { - lc_lag = Some(lag); - } - // HE rows: a per-channel free lag search on periodic/tonal - // content is unreliable (coupled_cpe_channel_swap_probe - // proved this file's ref L vs ref R itself mis-searches -- - // lag=-24 corr=0.213 vs the fixed lag=0 corr=0.873 -- and - // the same coarse search can land two channels of the SAME - // stream on DIFFERENT, individually-wrong lags, faking a - // channel swap that a fixed-lag check rules out). Derive - // ONE lag per stream from the summed (mono) signal instead, - // and reuse it for both channels -- more robust than - // trusting a single, possibly-periodic channel's own search - // -- via the same top-K/refine-on-first-10s robust method. - if profile == "HE" && ours.len() >= 2 && theirs.len() >= 2 { - let mono_o: Vec = - ours[0].iter().zip(&ours[1]).map(|(a, b)| a + b).collect(); - let mono_t: Vec = theirs[0] - .iter() - .zip(&theirs[1]) - .map(|(a, b)| a + b) - .collect(); - let (mono_lag, _, mono_edge) = - robust_lag_topk(&mono_o, &mono_t, WIDE_LAG_MAX, our_rate, TOPK); - assert!( - !mono_edge, - "{}: HE row's mono-derived refined lag {mono_lag} sits at the \ - +/-{WIDE_LAG_MAX} search's own edge", - path.display() - ); - lag = mono_lag; - full = correlation_at_lag(o, t, lag); - } - // Crossover in Hz from the actual parsed kx (band width - // rate/128, same domain `sbr_chain.rs`'s own doc comment - // gives `kx`/`k2` in) when SBR engaged; a fixed quarter-Nyquist - // split for the LC controls, which carry no kx at all. - let crossover_hz = if kx > 0 { - f64::from(our_rate) * (kx as f64) / 128.0 - } else { - f64::from(our_rate) * 0.25 - }; - // Same single robust `lag` the full/above bands use, not an - // independent search: a narrowband low-passed signal's - // correlation surface is broad and flat across nearby lags, - // which used to let an independent search here silently - // report a different (and unvalidated) alignment than the - // one everything else in the row is anchored at. - let below = correlation_at_lag( - &lowpass(o, our_rate, crossover_hz), - &lowpass(t, our_rate, crossover_hz), - lag, - ); - // `above` re-slices at the FULL-band winning `lag` before - // splitting, same convention `sbr_real_library_matches_reference` - // uses -- round-52's first cut of this row measured `o[..n]` - // against `t[..n]` with no lag offset at all, which is only - // valid by accident at lag 0 and was silently wrong for - // every other winning lag in that table. - let (oa, ob) = if lag >= 0 { - (0usize, lag as usize) - } else { - ((-lag) as usize, 0usize) - }; - let n = WINDOW - .min(o.len().saturating_sub(oa)) - .min(t.len().saturating_sub(ob)); - let above = if n >= 1024 { - correlation( - &highpass(&o[oa..oa + n], our_rate, crossover_hz), - &highpass(&t[ob..ob + n], our_rate, crossover_hz), + for path in fate_aac() { + let before = ec_aac::sbr_sideinfo_log().len(); + let (ours, _sbr, our_rate) = our_decode(&path, 0).expect("decodes"); + let rows = ec_aac::sbr_sideinfo_log(); + let (kx, k2) = rows[before..] + .iter() + .find(|r| r.ch == 0) + .map(|r| (r.kx, r.k2)) + .unwrap_or((-1, -1)); + let theirs = ffmpeg_decode(&path, 0, ours.len()); + let o = &ours[0]; + let t = &theirs[0]; + const TOPK: usize = 5; + let (mut lag, mut full, edge) = robust_lag_topk(o, t, WIDE_LAG_MAX, our_rate, TOPK); + assert!( + !edge, + "{}: HE row's refined winning lag {lag} sits at the \ + +/-{WIDE_LAG_MAX} search's own edge", + path.display() + ); + if ours.len() >= 2 && theirs.len() >= 2 { + let mono_o: Vec = + ours[0].iter().zip(&ours[1]).map(|(a, b)| a + b).collect(); + let mono_t: Vec = theirs[0] + .iter() + .zip(&theirs[1]) + .map(|(a, b)| a + b) + .collect(); + let (mono_lag, _, mono_edge) = + robust_lag_topk(&mono_o, &mono_t, WIDE_LAG_MAX, our_rate, TOPK); + assert!( + !mono_edge, + "{}: HE row's mono-derived refined lag {mono_lag} sits at the \ + +/-{WIDE_LAG_MAX} search's own edge", + path.display() + ); + lag = mono_lag; + full = correlation_at_lag(o, t, lag); + } + let crossover_hz = if kx > 0 { + f64::from(our_rate) * (kx as f64) / 128.0 + } else { + f64::from(our_rate) * 0.25 + }; + let below = correlation_at_lag( + &lowpass(o, our_rate, crossover_hz), + &lowpass(t, our_rate, crossover_hz), + lag, + ); + let (oa, ob) = if lag >= 0 { + (0usize, lag as usize) + } else { + ((-lag) as usize, 0usize) + }; + let n = WINDOW + .min(o.len().saturating_sub(oa)) + .min(t.len().saturating_sub(ob)); + let above = if n >= 1024 { + correlation( + &highpass(&o[oa..oa + n], our_rate, crossover_hz), + &highpass(&t[ob..ob + n], our_rate, crossover_hz), + ) + } else { + 0.0 + }; + let decimate = |s: &[f32], from_rate: u32, to_rate: u32| -> Vec { + let cutoff = f64::from(to_rate) * 0.45; + lowpass(s, from_rate, cutoff) + .iter() + .step_by((from_rate / to_rate.max(1)).max(1) as usize) + .copied() + .collect() + }; + let core_lag_max = WIDE_LAG_MAX / 2; + let ours_v_core = if kx > 0 { + our_decode_core_only(&path, 0).map(|(core, core_rate)| { + let full_at_core_rate = decimate(o, our_rate, core_rate); + best_lag_correlation_wide(&full_at_core_rate, &core[0], core_lag_max) + }) + } else { + None + }; + let (core_v_ref, core_rate_str) = if kx > 0 { + match our_decode_core_only(&path, 0) { + Some((core, core_rate)) => { + let ref_at_core_rate = + ffmpeg_decode_at_rate(&path, 0, core.len(), core_rate); + ( + Some(best_lag_correlation_wide( + &core[0], + &ref_at_core_rate[0], + core_lag_max, + )), + core_rate.to_string(), ) - } else { - 0.0 - }; - // Round-51's self-consistency probe (our full chain's low - // band vs our own core-only decode), run per-row so a - // rate/kx-specific self-inconsistency shows in the same - // table instead of needing a second pass. - // - // Fixed (this round): the original convention naively - // nearest-neighbor UPSAMPLED the core 2x and compared it - // against the full-rate signal, low-passed at - // `core_rate*0.4` -- that stairstep-and-lowpass round trip - // is lossy enough on its own to sink a genuinely-correct - // pair's correlation (measured flat ~-0.12 here even on - // rows whose `full`/`below` columns read 0.999+ against the - // real reference). `core_only_matches_reference` already - // proved a clean pattern for this exact comparison: stay in - // the CORE's own native rate (DECIMATE the full/reference - // signal down instead of upsampling the core up) and use a - // wide lag search there. `decimate` below is a lowpass - // (well under the core Nyquist) followed by a plain - // every-other-sample drop -- the inverse of the old - // `[s, s]` upsample, at the same information cost but - // without its stairstep artifact. - let decimate = |s: &[f32], from_rate: u32, to_rate: u32| -> Vec { - let cutoff = f64::from(to_rate) * 0.45; - lowpass(s, from_rate, cutoff) - .iter() - .step_by((from_rate / to_rate.max(1)).max(1) as usize) - .copied() - .collect() - }; - let core_lag_max = WIDE_LAG_MAX / 2; - let ours_v_core = if kx > 0 { - our_decode_core_only(&path, 0).map(|(core, core_rate)| { - let full_at_core_rate = decimate(o, our_rate, core_rate); - best_lag_correlation_wide(&full_at_core_rate, &core[0], core_lag_max) - }) - } else { - None - }; - // Coordinator follow-up 2: splits "our core decode of THIS - // fixture is wrong" (core_v_ref ~0) from "the SBR chain - // scrambles a good core" (core_v_ref >= ~0.99 while `below`/ - // `above` stays ~0/negative) -- OUR core-only decode, same - // native-core-rate convention `ours_v_core` now uses, against - // the REFERENCE decoder's own decode resampled to that same - // core rate (`ffmpeg_decode_at_rate`, the same helper - // `core_only_matches_reference` already trusts) -- wide lag - // search since this is an independent alignment from - // `full`/`below`'s (core-only carries no SBR delay). - let (core_v_ref, core_rate_str) = if kx > 0 { - match our_decode_core_only(&path, 0) { - Some((core, core_rate)) => { - let ref_at_core_rate = - ffmpeg_decode_at_rate(&path, 0, core.len(), core_rate); - ( - Some(best_lag_correlation_wide( - &core[0], - &ref_at_core_rate[0], - core_lag_max, - )), - core_rate.to_string(), - ) - } - None => (None, "n/a".into()), - } - } else { - (None, "n/a".into()) - }; - println!( - "{rate:>5} {br:>6} {profile:>4} {kx:>4} {k2:>4} {full:>8.4} {below:>8.4} {above:>8.4} {lag:>6} {:>11} {:>8} {:>10} {:>8} {:>9} {:>9}", - ours_v_core - .map(|(_, c)| format!("{c:.4}")) - .unwrap_or_else(|| "n/a".into()), - ours_v_core - .map(|(l, _)| l.to_string()) - .unwrap_or_else(|| "n/a".into()), - core_v_ref - .map(|(_, c)| format!("{c:.4}")) - .unwrap_or_else(|| "n/a".into()), - core_v_ref - .map(|(l, _)| l.to_string()) - .unwrap_or_else(|| "n/a".into()), - core_rate_str, - our_rate, - ); - // 44.1k-family HE rows: print per-second full-band corr at - // the row's own robust `lag` over 30s, so a content- - // dependent HF-reconstruction dip (real, not an alignment - // artifact -- `sbr441_family_sample_drift_probe` isolated - // one at t=13-27s on heaac_44100_48k.m4a) is visible per - // second instead of averaged away by the single `full` - // column above. - if profile == "HE" && rate == 44_100 { - println!(" per-second full-band corr @ lag {lag} (t, corr):"); - let step = our_rate.max(1) as usize; - for sec in 0..30usize { - let oa0 = sec * step; - if oa0 + step > o.len() { - break; - } - let ob0 = oa0 as i64 + lag; - if ob0 < 0 { - continue; - } - let ob0 = ob0 as usize; - if ob0 + step > t.len() { - continue; - } - let c = correlation(&o[oa0..oa0 + step], &t[ob0..ob0 + step]); - println!(" t={sec:>2}s corr={c:.6}"); - } - } - // Coordinator follow-up (4): on the two named rows, probe - // candidate total HE-vs-reference delays built from LC's own - // priming lag plus a guessed SBR-chain contribution, to see - // which (if any) actually lands near 1.0 -- and whether that - // offset is constant across the two rows. - if profile == "HE" - && ((rate == 44_100 && br == "48k") || (rate == 48_000 && br == "64k")) - { - let lc = lc_lag.unwrap_or(-2048); - println!(" ch0 delay probe (LC lag {lc}):"); - for (label, extra) in [ - ("2990", 2990i64), - ("3010", 3010), - ("3020", 3020), - ("1505x2", 1505 * 2), - ("962x2", 962 * 2), - ] { - let candidate = (lc - 2048) + extra; - println!( - " offset={label:>6} -> lag={candidate:>6} corr={:.6}", - correlation_at_lag(o, t, candidate) - ); - } - } - if profile == "LC" { - assert!( - full >= 0.999, - "{}: LC control full-band corr {full:.6} < 0.999 -- the \ - harness itself (extraction/decode/correlation) is broken, \ - not the SBR chain this fixture matrix is meant to isolate", - path.display() - ); } + None => (None, "n/a".into()), } - } + } else { + (None, "n/a".into()) + }; + println!( + "{kx:>4} {k2:>4} {full:>8.4} {below:>8.4} {above:>8.4} {lag:>6} {:>11} {:>8} {:>10} {:>8} {:>9} {:>9}", + ours_v_core + .map(|(_, c)| format!("{c:.4}")) + .unwrap_or_else(|| "n/a".into()), + ours_v_core + .map(|(l, _)| l.to_string()) + .unwrap_or_else(|| "n/a".into()), + core_v_ref + .map(|(_, c)| format!("{c:.4}")) + .unwrap_or_else(|| "n/a".into()), + core_v_ref + .map(|(l, _)| l.to_string()) + .unwrap_or_else(|| "n/a".into()), + core_rate_str, + our_rate, + ); } - assert!( - probed >= 16, - "only {probed} of 16 HE-AAC matrix fixtures were present -- rerun \ - scripts/aac-tables/make-heaac-fixtures.sh" - ); } pub(super) fn candidates() -> Vec { - let home = std::env::var("HOME").unwrap_or_default(); - [ - (format!("{home}/Music/reeln.mp4"), 0, 0, 5_000.0), - ( - format!( - "{home}/Downloads/reelp/reelp.mkv" - ), - 1, - 3, - 5_000.0, - ), - ] - .into_iter() - .map(|(p, aac_stream, ffmpeg_stream, crossover_hz)| Candidate { - path: PathBuf::from(p), - aac_stream, - ffmpeg_stream, - crossover_hz, - }) - .filter(|c| c.path.exists()) - .collect() + fate_aac() + .into_iter() + .map(|path| Candidate { + path, + aac_stream: 0, + ffmpeg_stream: 0, + crossover_hz: 5_000.0, + }) + .collect() } /// The SBR chain against the reference decoder on every real HE-AAC file this @@ -581,29 +382,14 @@ pub(super) fn candidates() -> Vec { #[test] pub(super) fn sbr_real_library_matches_reference() { let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } let list = candidates(); - if list.is_empty() { - eprintln!("SKIP: no HE-AAC files found under ~/Music, ~/Downloads, ~/Videos"); - return; - } let mut checked = 0; let mut worst_full = 1.0f64; let mut worst_low = 1.0f64; let mut any_at_edge: Option = None; for c in &list { - let Some((ours, sbr, rate)) = our_decode(&c.path, c.aac_stream) else { - eprintln!("SKIP {}: could not decode", c.path.display()); - continue; - }; + let (ours, sbr, rate) = our_decode(&c.path, c.aac_stream).expect("decode"); if sbr != ec_aac::SbrSupport::V1 { - eprintln!( - "SKIP {}: sbr_support() is {sbr:?}, not a plain-SBR (v1) stream this chain reconstructs", - c.path.display() - ); continue; } let theirs = ffmpeg_decode(&c.path, c.ffmpeg_stream, ours.len()); @@ -1163,10 +949,7 @@ pub(super) fn sbr_real_library_matches_reference() { } checked += 1; } - if checked == 0 { - eprintln!("SKIP: no plain-SBR real files decoded"); - return; - } + assert!(checked > 0, "no plain-SBR real files decoded"); assert!( any_at_edge.is_none(), "lag search hit its bound: {} -- the reported correlations are noise \ diff --git a/crates/ec-aac/tests/sbr_real_library/chunk_b.rs b/crates/ec-aac/tests/sbr_real_library/chunk_b.rs index 46a0009e..f18016b8 100644 --- a/crates/ec-aac/tests/sbr_real_library/chunk_b.rs +++ b/crates/ec-aac/tests/sbr_real_library/chunk_b.rs @@ -23,23 +23,7 @@ use super::*; #[test] pub(super) fn sbr_instrument_anchor_controls() { let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); - if std::env::var("EC_AAC_SBR_INSTRUMENT_ANCHOR").is_err() { - eprintln!( - "SKIP (round-41 Task 1): EC_AAC_SBR_INSTRUMENT_ANCHOR=1 cargo test -p ec-aac \ - --release --test sbr_real_library sbr_instrument_anchor_controls -- --nocapture" - ); - return; - } - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } - let home = std::env::var("HOME").unwrap_or_default(); - let path = PathBuf::from(format!("{home}/Music/reeln.mp4")); - if !path.exists() { - eprintln!("SKIP: {} not found", path.display()); - return; - } + let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"); const MIN_BAND: usize = 14; const TOP_N: usize = 128; // larger than any real band count -- keeps every HF band @@ -103,25 +87,7 @@ pub(super) fn sbr_instrument_anchor_controls() { #[test] pub(super) fn sbr_actual_noise_fraction() { let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); - if std::env::var("EC_AAC_SBR_NOISE_ANCHOR").is_err() { - eprintln!( - "SKIP (round-41 Task 2): EC_AAC_SBR_NOISE_ANCHOR=1 cargo test -p ec-aac \ - --release --test sbr_real_library sbr_actual_noise_fraction -- \ - --nocapture --test-threads=1 (env-gated because it sets process \ - env vars mid-run, which is unsound alongside parallel tests)" - ); - return; - } - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } - let home = std::env::var("HOME").unwrap_or_default(); - let path = PathBuf::from(format!("{home}/Music/reeln.mp4")); - if !path.exists() { - eprintln!("SKIP: {} not found", path.display()); - return; - } + let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"); const MIN_BAND: usize = 14; const TOP_N: usize = 128; @@ -295,17 +261,13 @@ pub(super) fn sbr_actual_noise_fraction() { #[test] pub(super) fn sbr_header_feature_table() { let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } struct Row { label: String, path: PathBuf, aac_stream: usize, ffmpeg_stream: usize, } - let mut rows: Vec = candidates() + let rows: Vec = candidates() .into_iter() .map(|c| Row { label: c @@ -318,28 +280,6 @@ pub(super) fn sbr_header_feature_table() { ffmpeg_stream: c.ffmpeg_stream, }) .collect(); - let fixtures = std::env::var("EC_AAC_HEAAC_FIXTURES") - .unwrap_or_else(|_| format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR"))); - let fixtures = PathBuf::from(fixtures); - if require_fixture(&fixtures, "scripts/aac-tables/make-heaac-fixtures.sh") { - for rate in [48_000u32, 44_100] { - for br in ["32k", "48k", "64k", "96k"] { - let p = fixtures.join(format!("heaac_{rate}_{br}.m4a")); - if require_fixture(&p, "scripts/aac-tables/make-heaac-fixtures.sh") { - rows.push(Row { - label: format!("synth-{rate}-{br}"), - path: p, - aac_stream: 0, - ffmpeg_stream: 0, - }); - } - } - } - } - if rows.is_empty() { - eprintln!("SKIP: no real HE-AAC files and no synthetic fixtures found"); - return; - } let _knob = ec_aac::knobs::set_sbr_sideinfo_debug(Some(true)); const WIDE_LAG_MAX: i64 = 20_000; println!( @@ -366,12 +306,8 @@ pub(super) fn sbr_header_feature_table() { ); for r in &rows { let before = ec_aac::sbr_sideinfo_log().len(); - let Some((ours, sbr, our_rate)) = our_decode(&r.path, r.aac_stream) else { - eprintln!("SKIP {}: could not decode", r.label); - continue; - }; + let (ours, sbr, our_rate) = our_decode(&r.path, r.aac_stream).expect("decode"); if sbr != ec_aac::SbrSupport::V1 { - eprintln!("SKIP {}: not SBR v1", r.label); continue; } let log = ec_aac::sbr_sideinfo_log(); @@ -380,10 +316,7 @@ pub(super) fn sbr_header_feature_table() { .filter(|row| row.ch == 0) .take(20) .collect(); - if frames.is_empty() { - eprintln!("SKIP {}: no sideinfo rows captured", r.label); - continue; - } + assert!(!frames.is_empty(), "{}: no sideinfo rows captured", r.label); let f0 = &frames[0]; let mut env_counts: std::collections::BTreeMap = Default::default(); let mut invf_seen: std::collections::BTreeSet = Default::default(); @@ -467,18 +400,9 @@ pub(super) fn sbr_header_feature_table() { /// -- divergence from the very first AU means a per-stream setup mismatch, /// not a per-frame trigger. pub(super) fn per_au_low_band_probe(label: &str, path: &Path, aac_stream: usize) { - let Some((asc, aus)) = extract_aac_track(path, aac_stream) else { - eprintln!("SKIP {label}: extract_aac_track failed"); - return; - }; - let Ok(full_cfg) = parse_audio_specific_config(&asc) else { - eprintln!("SKIP {label}: asc parse failed"); - return; - }; - if !full_cfg.sbr_present { - eprintln!("SKIP {label}: no SBR"); - return; - } + let (asc, aus) = extract_aac_track(path, aac_stream).expect("extract_aac_track"); + let full_cfg = parse_audio_specific_config(&asc).expect("asc parse"); + assert!(full_cfg.sbr_present, "{label}: no SBR"); let mut core_cfg = full_cfg.clone(); core_cfg.sbr_present = false; core_cfg.ps_present = false; @@ -519,14 +443,12 @@ pub(super) fn per_au_low_band_probe(label: &str, path: &Path, aac_stream: usize) break; } } - if core_ch0.is_empty() || full_ch0.is_empty() { - eprintln!( - "SKIP {label}: empty decode (core {} full {})", - core_ch0.len(), - full_ch0.len() - ); - return; - } + assert!( + !core_ch0.is_empty() && !full_ch0.is_empty(), + "{label}: empty decode (core {} full {})", + core_ch0.len(), + full_ch0.len() + ); // Same convention `full_chain_low_band_matches_own_core` already // validated (0.9967 on reeln): naive nearest-neighbor 2x-upsample @@ -589,20 +511,10 @@ pub(super) fn per_au_low_band_probe(label: &str, path: &Path, aac_stream: usize) #[test] pub(super) fn per_au_low_band_divergence() { let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } let _knob = ec_aac::knobs::set_sbr_sideinfo_debug(Some(true)); for c in &candidates() { per_au_low_band_probe(&c.path.display().to_string(), &c.path, c.aac_stream); } - let dir = std::env::var("EC_AAC_HEAAC_FIXTURES") - .unwrap_or_else(|_| format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR"))); - let failing = PathBuf::from(&dir).join("heaac_44100_48k.m4a"); - if require_fixture(&failing, "scripts/aac-tables/make-heaac-fixtures.sh") { - per_au_low_band_probe("synthetic 44100 48k (failing)", &failing, 0); - } } /// Coordinator follow-up: prints what `parse_audio_specific_config` actually @@ -618,10 +530,6 @@ pub(super) fn per_au_low_band_divergence() { #[test] pub(super) fn probe_explicit_config_and_wide_lag() { let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } fn decode_with(cfg: ec_aac::AudioSpecificConfig, aus: &[Vec]) -> (Vec>, u32) { let rate = match (cfg.sbr_present, cfg.ps_present) { (true, false) => cfg.extension_sample_rate.unwrap_or(cfg.sample_rate * 2), @@ -648,71 +556,14 @@ pub(super) fn probe_explicit_config_and_wide_lag() { (planes, rate) } - // `synthetic` marks the case as coming from the committed fixture library - // (`scripts/aac-tables/make-heaac-fixtures.sh`); the FMJ row is a - // `~/Downloads` host corpus and keeps its plain skip. - for ( - label, - path, - aac_stream, - ffmpeg_stream, - core_sf_index, - core_rate, - ext_rate, - channels, - synthetic, - ) in [ - ( - "FMJ", - format!( - "{}/Downloads/reelp/reelp.mkv", - std::env::var("HOME").unwrap_or_default() - ), - 1usize, - 3usize, - 6u8, - 24_000u32, - 48_000u32, - 2u16, - false, - ), - ( - "heaac_44100_48k", - format!( - "{}/heaac_44100_48k.m4a", - std::env::var("EC_AAC_HEAAC_FIXTURES").unwrap_or_else(|_| format!( - "{}/../../.cache/heaac-fixtures", - env!("CARGO_MANIFEST_DIR") - )) - ), - 0, - 0, - 4, - 44_100, - 0, // filled below from parsed cfg's own extension_sample_rate - 2, - true, - ), - ] { - let path = PathBuf::from(path); - if synthetic { - if !require_fixture(&path, "scripts/aac-tables/make-heaac-fixtures.sh") { - continue; - } - } else if !path.exists() { - eprintln!("SKIP {label}: {} absent", path.display()); - continue; - } - let Some((asc, aus)) = extract_aac_track(&path, aac_stream) else { - eprintln!("SKIP {label}: extract failed"); - continue; - }; + let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"); + let (label, aac_stream, ffmpeg_stream, core_sf_index, core_rate, ext_rate, channels) = + ("al_sbr_cm_48_2", 0usize, 0usize, 6u8, 24_000u32, 0u32, 2u16); + { + let (asc, aus) = extract_aac_track(&path, aac_stream).expect("extract"); let parsed = parse_audio_specific_config(&asc); println!("{label}: asc={asc:02x?} parsed={parsed:?}"); - let Ok(parsed_cfg) = parsed else { - eprintln!("SKIP {label}: parse failed"); - continue; - }; + let parsed_cfg = parsed.expect("asc parse"); let d = AacDecoder::with_config(parsed_cfg.clone()); println!( " runtime: sbr_support={:?} output_sample_rate={:?}", @@ -740,10 +591,7 @@ pub(super) fn probe_explicit_config_and_wide_lag() { pce: Vec::new(), }; let (hand_planes, hand_rate) = decode_with(hand_cfg.clone(), &aus); - if hand_planes.is_empty() { - eprintln!(" hand-built config: no channels decoded"); - continue; - } + assert!(!hand_planes.is_empty(), "{label}: hand-built config decoded no channels"); // Own-core self-consistency (upsample+lowpass convention). let core_cfg = ec_aac::AudioSpecificConfig { sbr_present: false, @@ -777,13 +625,9 @@ pub(super) fn probe_explicit_config_and_wide_lag() { // tests use) -- the coarse search in `full_chain_low_band_matches_own_ // core` landed right at that bound's edge (20005), so this checks // whether FMJ's true delay simply lies further out. - let home = std::env::var("HOME").unwrap_or_default(); - let fmj = PathBuf::from(format!( - "{home}/Downloads/reelp/reelp.mkv" - )); - if fmj.exists() - && let (Some((core, core_rate)), Some((full, sbr, full_rate))) = - (our_decode_core_only(&fmj, 1), our_decode(&fmj, 1)) + let fmj = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"); + if let (Some((core, core_rate)), Some((full, sbr, full_rate))) = + (our_decode_core_only(&fmj, 0), our_decode(&fmj, 0)) && sbr == ec_aac::SbrSupport::V1 { let up: Vec = core[0].iter().flat_map(|&s| [s, s]).collect(); @@ -800,7 +644,7 @@ pub(super) fn probe_explicit_config_and_wide_lag() { /// rule (see `ffmpeg_decode`'s doc and the ledger's "never use -ac 1", which /// applies just as much to picking one of N channels as to downmixing). pub(super) fn ffmpeg_decode_pan_channel(path: &Path, absolute_stream: usize, channel: usize) -> Vec { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args([ diff --git a/crates/ec-aac/tests/sbr_real_library/chunk_c.rs b/crates/ec-aac/tests/sbr_real_library/chunk_c.rs index 6b31382d..61ba8ba2 100644 --- a/crates/ec-aac/tests/sbr_real_library/chunk_c.rs +++ b/crates/ec-aac/tests/sbr_real_library/chunk_c.rs @@ -16,26 +16,15 @@ use super::*; #[test] pub(super) fn reelq_multichannel_lc_matches_reference() { let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } - let home = std::env::var("HOME").unwrap_or_default(); - let path = PathBuf::from(format!( - "{home}/Downloads/reelq/reelq.mp4" - )); - if !path.exists() { - eprintln!("SKIP: {} not present", path.display()); - return; - } + let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_5.1.mp4"); let Some((ours, _sbr, rate)) = our_decode(&path, 0) else { - panic!("ReelQ AAC track failed to decode at all"); + panic!("AAC track failed to decode at all"); }; - assert_eq!(ours.len(), 8, "expected 7.1 (8 channels)"); + assert_eq!(ours.len(), 6, "expected 5.1 (6 channels)"); let want = (rate as usize) * 10; // 10s per the charter for (ch, o) in ours.iter().enumerate() { let o = &o[..o.len().min(want)]; - let t = ffmpeg_decode_pan_channel(&path, 2, ch); + let t = ffmpeg_decode_pan_channel(&path, 0, ch); let t = &t[..t.len().min(want)]; let (lag, corr) = best_lag_correlation(o, t); println!("ReelQ ch{ch}: lag {lag}, corr {corr:.6}"); @@ -76,18 +65,9 @@ pub(super) fn reelq_multichannel_lc_matches_reference() { #[test] pub(super) fn coupled_cpe_channel_swap_probe() { let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } - let dir = std::env::var("EC_AAC_HEAAC_FIXTURES") - .unwrap_or_else(|_| format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR"))); - let path = PathBuf::from(&dir).join("heaac_44100_48k.m4a"); - if !require_fixture(&path, "scripts/aac-tables/make-heaac-fixtures.sh") { - return; - } + let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"); let Some((ours, sbr, out_rate)) = our_decode(&path, 0) else { - panic!("heaac_44100_48k failed to decode"); + panic!("al_sbr_cm_48_2 failed to decode"); }; assert_eq!(sbr, ec_aac::SbrSupport::V1); assert_eq!(ours.len(), 2, "expect stereo"); @@ -337,7 +317,7 @@ pub(super) fn our_decode_uncapped(path: &Path, stream_index: usize) -> Option<(V /// AAC stream, interleaved-`f32` byte count / 4 -- i.e. `channels * /// per_channel_samples`, not capped at 30s the way `ffmpeg_decode` is. pub(super) fn ffmpeg_total_interleaved_samples(path: &Path, absolute_stream: usize) -> u64 { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args([ @@ -364,7 +344,7 @@ pub(super) fn ffmpeg_total_interleaved_samples(path: &Path, absolute_stream: usi /// `duration` against what our decoder derives and what ffmpeg actually /// produces. pub(super) fn ffprobe_field(path: &Path, entry: &str) -> String { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args([ "-v", "error", @@ -423,58 +403,14 @@ pub(super) fn narrow_lag_at( #[test] pub(super) fn sbr441_family_sample_drift_probe() { let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } - let dir = std::env::var("EC_AAC_HEAAC_FIXTURES") - .unwrap_or_else(|_| format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR"))); - let home = std::env::var("HOME").unwrap_or_default(); - // `synthetic` marks the rows served by the committed fixture library - // (`scripts/aac-tables/make-heaac-fixtures.sh`); the reeln control is - // a `~/Music` host corpus and keeps its plain skip. - let cases: [(&str, PathBuf, i64, bool); 3] = [ - ( - "heaac_44100_48k (FAIL family)", - PathBuf::from(&dir).join("heaac_44100_48k.m4a"), - -4674, - true, - ), - ( - "heaac_48000_48k (48k control)", - PathBuf::from(&dir).join("heaac_48000_48k.m4a"), - // corrected via this test's own wide free-search cross-check - // (below) -- 0 was a bad guess, true fixed lag is -4673, same - // as the failing family's. - -4673, - true, - ), - ( - "reeln (44.1k control)", - PathBuf::from(format!("{home}/Music/reeln.mp4")), - // corrected via this test's own wide free-search cross-check - // (below) -- -576 was this file's CORE-vs-FULL-chain delay - // from an earlier probe, not its full-chain-vs-ffmpeg-reference - // lag, which is +385. - 385, - false, - ), + let cases: [(&str, PathBuf, i64); 2] = [ + ("al_sbr_cm_48_2", ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"), 0), + ("al_sbr_sr_48_2_fsaac48", ec_testkit::fixture("open/fate/aac/al_sbr_sr_48_2_fsaac48.mp4"), 0), ]; - for (label, path, seed_lag, synthetic) in cases { + for (label, path, seed_lag) in cases { println!("\n=== {label}: {} ===", path.display()); - if synthetic { - if !require_fixture(&path, "scripts/aac-tables/make-heaac-fixtures.sh") { - continue; - } - } else if !path.exists() { - eprintln!("SKIP {label}: {} absent", path.display()); - continue; - } let holds_before = ec_aac::hold_call_count(); - let Some((ours, out_rate, au_count)) = our_decode_uncapped(&path, 0) else { - eprintln!("SKIP {label}: our_decode_uncapped failed"); - continue; - }; + let (ours, out_rate, au_count) = our_decode_uncapped(&path, 0).expect("our_decode_uncapped"); // `ffmpeg_decode_pan_channel` caps at 10s (per its own charter, // shared with `reelq_multichannel_lc_matches_reference`); // this probe walks out to t=29s, so it needs `ffmpeg_decode`'s 30s @@ -553,22 +489,10 @@ pub(super) fn sbr441_family_sample_drift_probe() { #[test] pub(super) fn sbr_hf_window_band_probe() { let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); - if !have_ffmpeg() { - eprintln!("SKIP: ffmpeg not on PATH"); - return; - } - let dir = std::env::var("EC_AAC_HEAAC_FIXTURES") - .unwrap_or_else(|_| format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR"))); - let path = PathBuf::from(&dir).join("heaac_48000_64k.m4a"); - if !require_fixture(&path, "scripts/aac-tables/make-heaac-fixtures.sh") { - return; - } + let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"); const LAG: i64 = -4673; - let Some((ours, out_rate, _au_count)) = our_decode_uncapped(&path, 0) else { - eprintln!("SKIP: our_decode_uncapped failed"); - return; - }; + let (ours, out_rate, _au_count) = our_decode_uncapped(&path, 0).expect("our_decode_uncapped"); let ref_l = ffmpeg_decode(&path, 0, 2).swap_remove(0); let ch0 = &ours[0]; @@ -661,27 +585,8 @@ pub(super) fn sbr_hf_window_band_probe() { #[test] pub(super) fn sbr_residual_locator() { let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner()); - if !have_ffmpeg() { - return; - } - // lane-h264reallib: `unwrap_or_default()`, the shape this file's five - // other HOME reads already use (:2710, :3426, :4109, :4182, :4575). A bare - // `unwrap()` panicked on any host with no HOME -- a fleet runner -- which - // is a red with no bearing on the decoder. The `path.exists()` guard below - // already handles the absent-file case, so an empty HOME just makes the - // fallback path relative-and-nonexistent and the test returns. - let home = std::env::var("HOME").unwrap_or_default(); - // `EC_AAC_SBR_LOCATOR_FILE` points the same instrument at any other - // HE-AAC file (e.g. a mono, uncoupled, noise-only probe encode). - let path = std::env::var("EC_AAC_SBR_LOCATOR_FILE") - .map(PathBuf::from) - .unwrap_or_else(|_| PathBuf::from(format!("{home}/Music/reeln.mp4"))); - if !path.exists() { - return; - } - let Some((ours, _, rate)) = our_decode(&path, 0) else { - return; - }; + let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"); + let (ours, _, rate) = our_decode(&path, 0).expect("decode"); let theirs = ffmpeg_decode(&path, 0, ours.len()); const W: usize = 2048; const FFT_LEN: usize = 2048; diff --git a/crates/ec-aac/tests/sbr_real_library/helpers.rs b/crates/ec-aac/tests/sbr_real_library/helpers.rs index a1baecf2..e8b0f15d 100644 --- a/crates/ec-aac/tests/sbr_real_library/helpers.rs +++ b/crates/ec-aac/tests/sbr_real_library/helpers.rs @@ -1,33 +1,17 @@ -//! Shared analysis helpers for the SBR real-library probes. use super::*; -pub(super) use crate::common::have_ffmpeg; -/// Fixture-presence probe for the generated HE-AAC matrix under -/// `/.cache/heaac-fixtures` (`scripts/aac-tables/make-heaac-fixtures.sh`). -/// 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. The `~/Music` / `~/Downloads` / `~/Videos` -/// scans in this file are host corpora, not the committed fixture library, and -/// keep their plain skip. -pub(super) 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 +pub(super) fn fate_aac() -> Vec { + [ + "open/fate/aac/al_sbr_cm_48_2.mp4", + "open/fate/aac/al_sbr_cm_48_5.1.mp4", + "open/fate/aac/al_sbr_ps_04_new.mp4", + "open/fate/aac/al_sbr_ps_06_new.mp4", + "open/fate/aac/al_sbr_sr_48_2_fsaac48.mp4", + ] + .iter() + .map(|rel| ec_testkit::fixture(rel)) + .collect() } /// A film's audio track is hours long; the correlation only needs a bounded @@ -37,7 +21,7 @@ pub(super) const MAX_SAMPLES: usize = 1_000_000; /// ffmpeg's decode of a file's given absolute stream index, as /// planar-by-channel `f32`. pub(super) fn ffmpeg_decode(path: &Path, absolute_stream: usize, channels: usize) -> Vec> { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args([ @@ -2149,7 +2133,7 @@ pub(super) fn ffmpeg_decode_at_rate( channels: usize, target_rate: u32, ) -> Vec> { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args([ diff --git a/crates/ec-aac/tests/sbr_real_library/main.rs b/crates/ec-aac/tests/sbr_real_library/main.rs index afd295eb..affe4205 100644 --- a/crates/ec-aac/tests/sbr_real_library/main.rs +++ b/crates/ec-aac/tests/sbr_real_library/main.rs @@ -1,15 +1,7 @@ -//! The SBR chain, against real HE-AAC files pulled from the user's own media -//! directories, decoded through their real container (mp4 `esds` / Matroska -//! `CodecPrivate`) so `AacDecoder::with_config_bytes` actually arms the SBR -//! path -- `tests/oracle.rs` remuxes everything to bare ADTS first, and an -//! ADTS stream carries no AudioSpecificConfig, so its SBR chain never sees a -//! frame. Every file here is a live discovery over `~/Music`, `~/Downloads`, -//! `~/Videos`: absent files skip loudly, nothing is generated or bundled. use std::fs::File; use std::io::{BufReader, Read}; use std::path::{Path, PathBuf}; -use std::process::Command; use ec_aac::{AacDecoder, parse_audio_specific_config}; use ec_core::{CodecId, Demuxer, Packet}; @@ -28,8 +20,6 @@ use ec_mp4::Mp4Demuxer; /// each test. static DECODE_SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(()); -#[path = "../common/mod.rs"] -mod common; mod helpers; mod chunk_a; mod chunk_b; diff --git a/crates/ec-ac3/Cargo.toml b/crates/ec-ac3/Cargo.toml index e960db84..cc4d4290 100644 --- a/crates/ec-ac3/Cargo.toml +++ b/crates/ec-ac3/Cargo.toml @@ -9,3 +9,6 @@ authors.workspace = true [dependencies] ec-core.workspace = true ec-dsp.workspace = true + +[dev-dependencies] +ec-testkit.workspace = true diff --git a/crates/ec-ac3/fuzz/seed.sh b/crates/ec-ac3/fuzz/seed.sh index fdc72f2d..0ec8f813 100755 --- a/crates/ec-ac3/fuzz/seed.sh +++ b/crates/ec-ac3/fuzz/seed.sh @@ -11,8 +11,8 @@ set -euo pipefail FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd) -FIXTURES=$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures/audio -[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/link-fixtures.sh" >&2; exit 2; } +FIXTURES=${EC_FIXTURES:-$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures}/audio +[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/fixtures.sh" >&2; exit 2; } FILES=("$FIXTURES"/ac3-*.ac3 "$FIXTURES"/eac3-*.eac3 "$FIXTURES"/ac3dep-*.eac3) [ -e "${FILES[0]}" ] || { echo "seed.sh: no ac3-*.ac3 or eac3-*.eac3 fixtures in $FIXTURES" >&2; exit 2; } diff --git a/crates/ec-ac3/tests/it/common.rs b/crates/ec-ac3/tests/it/common.rs deleted file mode 100644 index 8dddb6f1..00000000 --- a/crates/ec-ac3/tests/it/common.rs +++ /dev/null @@ -1,9 +0,0 @@ -use std::process::Command; - -/// Whether `ffmpeg -version` runs successfully. -pub fn have_ffmpeg() -> bool { - Command::new("ffmpeg") - .arg("-version") - .output() - .is_ok_and(|o| o.status.success()) -} diff --git a/crates/ec-ac3/tests/it/decode_matrix.rs b/crates/ec-ac3/tests/it/decode_matrix.rs index 40baf893..706c5e73 100644 --- a/crates/ec-ac3/tests/it/decode_matrix.rs +++ b/crates/ec-ac3/tests/it/decode_matrix.rs @@ -2,16 +2,10 @@ //! compared against ffmpeg, plus the header surface a container reads and the //! no-panic contract on damaged input. //! -//! ffmpeg is test tooling — it is driven through `std::process` so the crate -//! itself never gains a media dependency. Missing fixtures or a missing ffmpeg -//! skip the comparison rather than fail it; `scripts/gen-fixtures.sh` writes -//! the fixtures. -use std::path::{Path, PathBuf}; -use std::process::Command; +use std::path::Path; use ec_ac3::{Ac3Decoder, Downmix, Options, Syntax, bsi, eac3, syncinfo}; -use crate::common::have_ffmpeg; /// Per-channel correlation floor (rubric: audio-ac3 MUST). const MIN_CORR: f64 = 0.999; @@ -19,16 +13,9 @@ const MIN_CORR: f64 = 0.999; /// synthetic material. const MAX_RMS: f64 = 1e-3; -fn fixtures() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../fixtures/audio") - .canonicalize() - .unwrap_or_else(|_| PathBuf::from("../../fixtures/audio")) -} - /// ffmpeg's decode of `path` as interleaved `f32`. fn reference(path: &Path) -> Vec { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args(["-f", "f32le", "-"]) @@ -96,13 +83,8 @@ fn correlation(a: &[f32], b: &[f32]) -> (f64, f64) { #[test] fn fixture_matrix_matches_ffmpeg() { - let dir = fixtures(); - if !dir.exists() || !have_ffmpeg() { - eprintln!("skipping: no fixtures or no ffmpeg"); - return; - } let mut checked = 0; - for entry in std::fs::read_dir(&dir).expect("fixtures dir") { + for entry in std::fs::read_dir(ec_testkit::root().join("audio")).expect("audio fixtures") { let path = entry.expect("entry").path(); let name = path.file_name().unwrap_or_default().to_string_lossy(); if !(name.starts_with("ac3-") || name.starts_with("eac3-")) { @@ -140,10 +122,7 @@ fn fixture_matrix_matches_ffmpeg() { #[test] fn dither_only_adds_noise_below_the_signal() { - let path = fixtures().join("ac3-5.1-48000.ac3"); - if !path.exists() { - return; - } + let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3"); let (with, channels) = decode(&path, Options::default()); let (without, _) = decode( &path, @@ -160,10 +139,7 @@ fn dither_only_adds_noise_below_the_signal() { #[test] fn headers_state_what_the_container_needs() { - let path = fixtures().join("ac3-5.1-48000.ac3"); - if !path.exists() { - return; - } + let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3"); let data = std::fs::read(&path).expect("fixture"); // The exact call shape a container makes: syncinfo from the frame start, // bsi from five bytes in. @@ -176,7 +152,7 @@ fn headers_state_what_the_container_needs() { assert_eq!(bsi.channels, 6); assert!((1..=31).contains(&bsi.dialnorm)); - let eac3_path = fixtures().join("eac3-5.1-48000.eac3"); + let eac3_path = ec_testkit::fixture("audio/eac3-5.1-48000.eac3"); let data = std::fs::read(&eac3_path).expect("fixture"); let hdr = eac3::bsi::parse(&data[2..]).expect("eac3 bsi"); assert_eq!(hdr.sample_rate, 48_000); @@ -190,10 +166,7 @@ fn headers_state_what_the_container_needs() { #[test] fn frame_info_surfaces_the_metadata_the_rubric_asks_for() { - let path = fixtures().join("ac3-5.1-48000.ac3"); - if !path.exists() { - return; - } + let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3"); let data = std::fs::read(&path).expect("fixture"); let size = ec_ac3::frame_size(&data).expect("frame size"); let mut decoder = Ac3Decoder::new(); @@ -210,10 +183,7 @@ fn frame_info_surfaces_the_metadata_the_rubric_asks_for() { #[test] fn stereo_downmix_folds_five_one_without_clipping() { - let path = fixtures().join("ac3-5.1-48000.ac3"); - if !path.exists() { - return; - } + let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3"); let (stereo, channels) = decode( &path, Options { @@ -240,10 +210,7 @@ fn stereo_downmix_folds_five_one_without_clipping() { #[test] fn damaged_input_never_panics() { - let path = fixtures().join("ac3-stereo-48000.ac3"); - if !path.exists() { - return; - } + let path = ec_testkit::fixture("audio/ac3-stereo-48000.ac3"); let data = std::fs::read(&path).expect("fixture"); let size = ec_ac3::frame_size(&data).expect("frame size"); let frame = &data[..size]; @@ -281,13 +248,8 @@ fn damaged_input_never_panics() { /// answers the same way for an AC-3 tail. #[test] fn a_concatenated_tail_is_refused_by_name_not_dropped() { - let dir = fixtures(); - if !dir.join("eac3-5.1-48000.eac3").exists() { - eprintln!("skipping: no fixtures"); - return; - } for name in ["ac3-5.1-48000.ac3", "eac3-5.1-48000.eac3"] { - let data = std::fs::read(dir.join(name)).expect("fixture"); + let data = std::fs::read(ec_testkit::fixture(&format!("audio/{name}"))).expect("fixture"); let first = ec_ac3::frame_size(&data).expect("first frame size"); let second = ec_ac3::frame_size(&data[first..]).expect("second frame size"); let mut packet = data[..first].to_vec(); @@ -328,11 +290,7 @@ fn a_concatenated_tail_is_refused_by_name_not_dropped() { /// frame — sample for sample, whatever its length. #[test] fn padding_that_is_not_a_syncframe_still_decodes() { - let path = fixtures().join("ac3-5.1-48000.ac3"); - if !path.exists() { - eprintln!("skipping: no fixtures"); - return; - } + let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3"); let data = std::fs::read(&path).expect("fixture"); let first = ec_ac3::frame_size(&data).expect("frame size"); let frame = &data[..first]; diff --git a/crates/ec-ac3/tests/it/dependent.rs b/crates/ec-ac3/tests/it/dependent.rs index 031a4875..53044953 100644 --- a/crates/ec-ac3/tests/it/dependent.rs +++ b/crates/ec-ac3/tests/it/dependent.rs @@ -2,12 +2,8 @@ //! spliced stream: its channel placement (the replace-or-add rule of Table E2.5) //! and its channel order, which ffprobe names in `channel_layout`. //! -//! The fixtures come from `scripts/gen-ac3dep-fixtures.sh`. Missing fixtures or -//! a missing ffmpeg skip the comparison, as in `decode_matrix.rs`, unless -//! `EC_REQUIRE_FIXTURES=1`, which makes an absent fixture a failure. -use std::path::{Path, PathBuf}; -use std::process::Command; +use std::path::Path; use ec_ac3::{Ac3Decoder, Error, Options, eac3, frame_size}; use ec_core::{ChannelLayout, ChannelPosition}; @@ -16,48 +12,9 @@ use ec_core::{ChannelLayout, ChannelPosition}; const MIN_CORR: f64 = 0.999; const MAX_RMS: f64 = 1e-3; -fn fixtures() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio") -} - -/// Whether every path is present. A missing one skips the test, or fails it -/// under `EC_REQUIRE_FIXTURES=1`. -fn present(name: &str, paths: &[PathBuf]) -> bool { - let missing: Vec<_> = paths.iter().filter(|p| !p.exists()).collect(); - if missing.is_empty() { - return true; - } - assert!( - std::env::var("EC_REQUIRE_FIXTURES").as_deref() != Ok("1"), - "{name}: fixture missing: {missing:?}" - ); - eprintln!("skipping {name}: fixture missing: {missing:?}"); - false -} - -/// Whether ffmpeg and ffprobe run. Missing tools skip, or fail under -/// `EC_REQUIRE_FIXTURES=1`. -fn have_ffmpeg(name: &str) -> bool { - let ok = |tool: &str| { - Command::new(tool) - .arg("-version") - .output() - .is_ok_and(|o| o.status.success()) - }; - if ok("ffmpeg") && ok("ffprobe") { - return true; - } - assert!( - std::env::var("EC_REQUIRE_FIXTURES").as_deref() != Ok("1"), - "{name}: ffmpeg and ffprobe are required" - ); - eprintln!("skipping {name}: ffmpeg or ffprobe missing"); - false -} - /// ffprobe's `channel_layout` name for the first audio stream of `path`. fn ffprobe_layout(path: &Path) -> String { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args(["-v", "error", "-f", "eac3", "-select_streams", "a:0"]) .args(["-show_entries", "stream=channel_layout", "-of", "csv=p=0"]) .arg(path) @@ -68,7 +25,7 @@ fn ffprobe_layout(path: &Path) -> String { /// ffmpeg's decode of `path` as interleaved `f32`, in ffmpeg's channel order. fn reference(path: &Path, channels: usize) -> Vec> { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-f", "eac3", "-i"]) .arg(path) .args(["-f", "f32le", "-"]) @@ -170,15 +127,8 @@ fn correlation(a: &[f32], b: &[f32]) -> (f64, f64, f64) { /// repeats the dependent's left channel. The core decode is ffmpeg's own /// unchanged 5.1 path, so it is the reference that ffmpeg itself gets right. fn check_against_ffmpeg(name: &str, ffprobe_name: &str, layout: &ChannelLayout, side_from_core: bool) { - let stream = fixtures().join(name); - let core = fixtures().join("ac3dep-src-5.1.eac3"); - let mut paths = vec![stream.clone()]; - if side_from_core { - paths.push(core.clone()); - } - if !present(name, &paths) || !have_ffmpeg(name) { - return; - } + let stream = ec_testkit::fixture(&format!("audio/{name}")); + let core_side = side_from_core.then(|| reference(&ec_testkit::fixture("audio/ac3dep-src-5.1.eac3"), 6)); assert_eq!(ffprobe_layout(&stream), ffprobe_name, "{name}: ffprobe channel_layout"); let data = std::fs::read(&stream).expect("fixture"); let (ours, channels, ours_layout) = decode(&data); @@ -186,7 +136,6 @@ fn check_against_ffmpeg(name: &str, ffprobe_name: &str, layout: &ChannelLayout, assert_eq!(channels, layout.channel_count(), "{name}: channels"); let theirs = reference(&stream, channels); - let core_side = side_from_core.then(|| reference(&core, 6)); let frames = ours.len() / channels; assert_eq!(frames, theirs[0].len(), "{name}: frame count vs ffmpeg"); @@ -246,12 +195,8 @@ fn side_pair_replacement_carries_the_dependent_signal() { // The replaced pair is the dependent stereo source (880 Hz and 1320 Hz // sines), not the core's: compare the side channels with ffmpeg's decode // of that source on its own. - let dir = fixtures(); - let repl = dir.join("ac3dep-repl-48000.eac3"); - let src20 = dir.join("ac3dep-src-2.0.eac3"); - if !present("ac3dep-repl-48000.eac3", &[repl.clone(), src20.clone()]) || !have_ffmpeg("replacement signal") { - return; - } + let repl = ec_testkit::fixture("audio/ac3dep-repl-48000.eac3"); + let src20 = ec_testkit::fixture("audio/ac3dep-src-2.0.eac3"); let data = std::fs::read(&repl).expect("fixture"); let (ours, channels, _) = decode(&data); assert_eq!(channels, 6, "replacement keeps the 5.1 channel count"); @@ -266,11 +211,7 @@ fn side_pair_replacement_carries_the_dependent_signal() { #[test] fn dependent_without_an_independent_is_named_not_decoded() { - let dir = fixtures(); - let stream = dir.join("ac3dep-7.1-48000.eac3"); - if !present("ac3dep-7.1-48000.eac3", std::slice::from_ref(&stream)) { - return; - } + let stream = ec_testkit::fixture("audio/ac3dep-7.1-48000.eac3"); let data = std::fs::read(&stream).expect("fixture"); let packet = packets(&data)[0]; // The dependent frame alone, as a first substream. @@ -285,11 +226,7 @@ fn dependent_without_an_independent_is_named_not_decoded() { #[test] fn truncated_dependent_substream_is_an_error_not_a_panic() { - let dir = fixtures(); - let stream = dir.join("ac3dep-7.1-48000.eac3"); - if !present("ac3dep-7.1-48000.eac3", std::slice::from_ref(&stream)) { - return; - } + let stream = ec_testkit::fixture("audio/ac3dep-7.1-48000.eac3"); let data = std::fs::read(&stream).expect("fixture"); let packet = packets(&data)[0]; for cut in [1, 2, 8, 100, 500] { @@ -300,11 +237,7 @@ fn truncated_dependent_substream_is_an_error_not_a_panic() { #[test] fn a_second_independent_substream_in_the_packet_is_still_refused() { - let dir = fixtures(); - let src20 = dir.join("ac3dep-src-2.0.eac3"); - if !present("ac3dep-src-2.0.eac3", std::slice::from_ref(&src20)) { - return; - } + let src20 = ec_testkit::fixture("audio/ac3dep-src-2.0.eac3"); let data = std::fs::read(&src20).expect("fixture"); let first = packets(&data)[0]; let mut two = first.to_vec(); diff --git a/crates/ec-ac3/tests/it/encode_matrix.rs b/crates/ec-ac3/tests/it/encode_matrix.rs index 5ab26217..518a724d 100644 --- a/crates/ec-ac3/tests/it/encode_matrix.rs +++ b/crates/ec-ac3/tests/it/encode_matrix.rs @@ -1,13 +1,10 @@ //! Encoder coverage: frames our own decoder round-trips, and that ffmpeg -//! (when present) accepts as valid AC-3 and decodes to the same audio — on //! synthetic signals and on the real 16-bit fixtures, at every rate and //! layout the encoder offers. use std::path::Path; -use std::process::Command; use ec_ac3::{Ac3Decoder, Ac3Encoder, EncoderConfig}; -use crate::common::have_ffmpeg; /// 440 Hz tone for 1 s, then 0.5 s of silence, interleaved across `channels`. fn tone_then_silence(sample_rate: u32, channels: usize) -> Vec { @@ -80,18 +77,14 @@ fn take_channel(interleaved: &[f32], channels: usize, ch: usize) -> Vec { .collect() } -/// The fixture's PCM decoded by ffmpeg, with its rate and channel count; None -/// without ffmpeg. -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("ffmpeg"); + assert!(out.status.success(), "ffmpeg cannot read {}", path.display()); let samples = out .stdout .as_chunks::<4>().0.iter() @@ -99,11 +92,11 @@ fn read_wav(path: &Path) -> Option<(Vec, u32, usize)> { .collect(); let probe = ffprobe(path, "channels,sample_rate"); let field = |key: &str| probe_field(&probe, key).and_then(|v| v.parse::().ok()); - Some((samples, field("sample_rate")?, field("channels")? as usize)) + (samples, field("sample_rate").unwrap(), field("channels").unwrap() as usize) } fn ffprobe(path: &Path, entries: &str) -> String { - let out = Command::new("ffprobe") + let out = ec_testkit::ffprobe() .args(["-v", "error", "-select_streams", "a:0", "-show_entries"]) .arg(format!("stream={entries}")) .args(["-of", "default=noprint_wrappers=1"]) @@ -121,7 +114,7 @@ fn probe_field(text: &str, key: &str) -> Option { /// ffmpeg's decode of an AC-3 file, asserting it voiced no complaint. fn oracle_decode(path: &Path) -> Vec { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "warning", "-i"]) .arg(path) .args(["-f", "f32le", "-"]) @@ -227,10 +220,6 @@ fn silence_and_tone_frames_decode_in_our_decoder() { #[test] fn oracle_accepts_our_frames() { - if !have_ffmpeg() { - eprintln!("skipping: ffmpeg not found"); - return; - } let config = EncoderConfig { sample_rate: 48_000, channels: 2, @@ -242,7 +231,7 @@ fn oracle_accepts_our_frames() { let path = dir.join("ec_ac3_encode_matrix_oracle.ac3"); std::fs::write(&path, &data).unwrap(); - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "warning", "-i"]) .arg(&path) .args(["-f", "f32le", "-"]) @@ -278,16 +267,12 @@ fn oracle_accepts_our_frames() { /// asked for. Prints the per-file numbers and the stereo strategy shares. #[test] fn real_fixtures_round_trip_through_our_decoder_and_the_oracle() { - if !have_ffmpeg() { - eprintln!("skipping: ffmpeg not found"); - return; - } - let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio"); + let root = ec_testkit::root().join("audio"); let mut failures = Vec::new(); for layout in ["mono", "stereo", "5.1"] { for rate in [48_000u32, 44_100] { let path = root.join(format!("wav16-{layout}-{rate}.wav")); - let (pcm, sample_rate, channels) = read_wav(&path).unwrap_or_else(|| panic!("{}", path.display())); + let (pcm, sample_rate, channels) = read_wav(&path); assert_eq!(sample_rate, rate); let bitrate_kbps = match channels { 1 => 96, 2 => 192, _ => 448 }; let config = EncoderConfig { sample_rate, channels: channels as u16, bitrate_kbps }; @@ -356,14 +341,12 @@ fn click_train_switches_blocks_and_still_round_trips() { let corr = worst_corr(&pcm, &decode_all(&data, channels), channels); eprintln!("click train: ours {corr:.4}, {stats:?}"); assert!(corr >= 0.95, "click train corr {corr}"); - if have_ffmpeg() { - let out = std::env::temp_dir().join("ec_ac3_encode_matrix_clicks.ac3"); - std::fs::write(&out, &data).unwrap(); - let corr = worst_corr(&pcm, &oracle_decode(&out), channels); - let _ = std::fs::remove_file(&out); - eprintln!("click train: oracle {corr:.4}"); - assert!(corr >= 0.95, "click train oracle corr {corr}"); - } + let out = std::env::temp_dir().join("ec_ac3_encode_matrix_clicks.ac3"); + std::fs::write(&out, &data).unwrap(); + let corr = worst_corr(&pcm, &oracle_decode(&out), channels); + let _ = std::fs::remove_file(&out); + eprintln!("click train: oracle {corr:.4}"); + assert!(corr >= 0.95, "click train oracle corr {corr}"); } #[test] @@ -380,16 +363,14 @@ fn tone_at_32khz_round_trips() { let data = encode(config, &pcm); let corr = worst_corr(&pcm, &decode_all(&data, 2), 2); assert!(corr >= 0.99, "32 kHz ours corr {corr}"); - if have_ffmpeg() { - let out = std::env::temp_dir().join("ec_ac3_encode_matrix_32k.ac3"); - std::fs::write(&out, &data).unwrap(); - let corr = worst_corr(&pcm, &oracle_decode(&out), 2); - let probe = ffprobe(&out, "sample_rate,bit_rate"); - let _ = std::fs::remove_file(&out); - assert!(corr >= 0.99, "32 kHz oracle corr {corr}"); - assert_eq!(probe_field(&probe, "sample_rate").as_deref(), Some("32000"), "{probe}"); - assert_eq!(probe_field(&probe, "bit_rate").as_deref(), Some("96000"), "{probe}"); - } + let out = std::env::temp_dir().join("ec_ac3_encode_matrix_32k.ac3"); + std::fs::write(&out, &data).unwrap(); + let corr = worst_corr(&pcm, &oracle_decode(&out), 2); + let probe = ffprobe(&out, "sample_rate,bit_rate"); + let _ = std::fs::remove_file(&out); + assert!(corr >= 0.99, "32 kHz oracle corr {corr}"); + assert_eq!(probe_field(&probe, "sample_rate").as_deref(), Some("32000"), "{probe}"); + assert_eq!(probe_field(&probe, "bit_rate").as_deref(), Some("96000"), "{probe}"); } /// 200 random (rate, channels, bit rate) configurations, two frames of diff --git a/crates/ec-ac3/tests/it/ffmpeg_parity.rs b/crates/ec-ac3/tests/it/ffmpeg_parity.rs index 1a0e4239..afcda071 100644 --- a/crates/ec-ac3/tests/it/ffmpeg_parity.rs +++ b/crates/ec-ac3/tests/it/ffmpeg_parity.rs @@ -11,13 +11,10 @@ //! with the LFE (which carries only rounding-level content here) also held to //! the same correlation since it is not silent. //! -//! Needs ffmpeg on PATH; without it the test skips loudly. use std::path::{Path, PathBuf}; -use std::process::Command; use ec_ac3::{Ac3Decoder, Options}; -use crate::common::have_ffmpeg; const MIN_CORR: f64 = 0.999; /// Seconds of noise per fixture. Long enough for a few hundred frames. @@ -59,14 +56,14 @@ fn encode(work: &Path, name: &str, channels: usize, bitrate: &str) -> PathBuf { "ac3".into(), ]); args.push(out.display().to_string()); - let status = Command::new("ffmpeg").args(&args).status().expect("ffmpeg"); + let status = ec_testkit::ffmpeg().args(&args).status().expect("ffmpeg"); assert!(status.success(), "ffmpeg encode of {name} failed"); out } /// ffmpeg's decode of the stream as interleaved `f32`. fn reference(path: &Path, channels: usize) -> Vec { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-nostdin", "-i"]) .arg(path) .args(["-f", "f32le", "-acodec", "pcm_f32le", "-ac"]) @@ -136,10 +133,6 @@ fn correlation(ours: &[f32], theirs: &[f32], channels: usize, ch: usize) -> f64 } fn check(name: &str, channels: usize, bitrate: &str) { - if !have_ffmpeg() { - eprintln!("skip {name}: ffmpeg not on PATH"); - return; - } let work = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("ffmpeg-parity"); std::fs::create_dir_all(&work).expect("work dir"); let stream = encode(&work, name, channels, bitrate); diff --git a/crates/ec-ac3/tests/it/main.rs b/crates/ec-ac3/tests/it/main.rs index 46ac3d4d..9f8b0b9b 100644 --- a/crates/ec-ac3/tests/it/main.rs +++ b/crates/ec-ac3/tests/it/main.rs @@ -1,7 +1,6 @@ //! One integration-test binary for ec-ac3; each module is one former `tests/*.rs` file. #![forbid(unsafe_code)] -mod common; mod decode_matrix; mod dependent; mod encode_matrix; diff --git a/crates/ec-ac3/tests/it/packet_walk.rs b/crates/ec-ac3/tests/it/packet_walk.rs index 424ba1d6..a4d3e147 100644 --- a/crates/ec-ac3/tests/it/packet_walk.rs +++ b/crates/ec-ac3/tests/it/packet_walk.rs @@ -5,32 +5,10 @@ //! syncframe in the packet against one decoder state. The reference is the //! same bytes decoded one frame at a time on a fresh decoder, which the //! per-frame matrix already holds to ffmpeg, so equality here is exact. -//! -//! Missing fixtures skip, or fail under `EC_REQUIRE_FIXTURES=1`. - -use std::path::{Path, PathBuf}; use ec_ac3::{Ac3Decoder, Error, eac3, frame_size}; use ec_core::{Decoder, Frame, Packet, TimeBase}; -fn fixtures() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio") -} - -/// Whether the fixture is present. A missing one skips the test, or fails it -/// under `EC_REQUIRE_FIXTURES=1`. -fn present(path: &Path) -> bool { - if path.exists() { - return true; - } - assert!( - std::env::var("EC_REQUIRE_FIXTURES").as_deref() != Ok("1"), - "fixture missing: {path:?}" - ); - eprintln!("skipping: fixture missing: {path:?}"); - false -} - /// Every syncframe of an AC-3 or E-AC-3 stream without dependent substreams. fn frames(data: &[u8]) -> Vec<&[u8]> { let mut out = Vec::new(); @@ -95,10 +73,7 @@ fn decode_packet_bytes(packets: &[&[u8]]) -> (Vec, u64) { #[test] fn ac3_packets_of_two_and_three_syncframes_decode_to_their_frames() { - let path = fixtures().join("ac3-5.1-48000.ac3"); - if !present(&path) { - return; - } + let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3"); let data = std::fs::read(&path).expect("fixture"); let all = frames(&data); assert!(all.len() >= 3, "fixture has too few frames"); @@ -112,10 +87,7 @@ fn ac3_packets_of_two_and_three_syncframes_decode_to_their_frames() { #[test] fn eac3_packets_of_two_and_three_syncframes_decode_to_their_frames() { - let path = fixtures().join("eac3-5.1-48000.eac3"); - if !present(&path) { - return; - } + let path = ec_testkit::fixture("audio/eac3-5.1-48000.eac3"); let data = std::fs::read(&path).expect("fixture"); let all = frames(&data); assert!(all.len() >= 3, "fixture has too few frames"); @@ -130,10 +102,7 @@ fn eac3_packets_of_two_and_three_syncframes_decode_to_their_frames() { /// that carries several (7.1 DD+ assembled as 5.1 plus a dependent). #[test] fn e_ac3_dependent_packets_inside_a_multi_syncframe_packet_keep_their_channels() { - let path = fixtures().join("ac3dep-7.1-48000.eac3"); - if !present(&path) { - return; - } + let path = ec_testkit::fixture("audio/ac3dep-7.1-48000.eac3"); let data = std::fs::read(&path).expect("fixture"); let all = packets(&data); assert!(all.len() >= 3, "fixture has too few packets"); @@ -150,10 +119,7 @@ fn e_ac3_dependent_packets_inside_a_multi_syncframe_packet_keep_their_channels() /// bare frames. #[test] fn padding_after_several_syncframes_is_ignored() { - let path = fixtures().join("ac3-5.1-48000.ac3"); - if !present(&path) { - return; - } + let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3"); let data = std::fs::read(&path).expect("fixture"); let all = frames(&data); let mut packet: Vec = all[..3].concat(); @@ -166,11 +132,8 @@ fn padding_after_several_syncframes_is_ignored() { /// A second frame of another channel layout cannot share one output frame. #[test] fn syncframes_of_different_layouts_in_one_packet_are_refused_by_name() { - let surround = fixtures().join("ac3-5.1-48000.ac3"); - let stereo = fixtures().join("ac3-stereo-48000.ac3"); - if !present(&surround) || !present(&stereo) { - return; - } + let surround = ec_testkit::fixture("audio/ac3-5.1-48000.ac3"); + let stereo = ec_testkit::fixture("audio/ac3-stereo-48000.ac3"); let a = std::fs::read(&surround).expect("fixture"); let b = std::fs::read(&stereo).expect("fixture"); let mut packet = frames(&a)[0].to_vec(); @@ -188,10 +151,7 @@ fn syncframes_of_different_layouts_in_one_packet_are_refused_by_name() { /// there and decoded by the packet call. #[test] fn decode_frame_still_takes_one_syncframe() { - let path = fixtures().join("ac3-stereo-48000.ac3"); - if !present(&path) { - return; - } + let path = ec_testkit::fixture("audio/ac3-stereo-48000.ac3"); let data = std::fs::read(&path).expect("fixture"); let all = frames(&data); let packet = [all[0], all[1]].concat(); diff --git a/crates/ec-ac3/tests/it/real_library.rs b/crates/ec-ac3/tests/it/real_library.rs index cd0736b0..cdda537e 100644 --- a/crates/ec-ac3/tests/it/real_library.rs +++ b/crates/ec-ac3/tests/it/real_library.rs @@ -1,23 +1,10 @@ -//! AC-3 and E-AC-3 decode of the real files named in `real_library.toml`, -//! compared against ffmpeg. -//! -//! Local media only: the file list is the user's `real_library.toml` (path in -//! `EC_REAL_LIBRARY`, default `~/Documents/Code/Rust/edith/real_library.toml`). -//! Each entry whose first audio track is `ac3` or `eac3` has its first -//! `EC_REAL_SECONDS` seconds (default 20) of that track copied out as a raw -//! elementary stream (`-c copy`, no re-encode), decoded by `ec-ac3` and by -//! ffmpeg, and compared per channel. Entries that are missing on disk, or that -//! hold no AC-3 or E-AC-3 track, are skipped loudly. Without ffmpeg the whole -//! test skips. //! //! Gate: per-channel correlation >= 0.999 (the matrix floor), and the //! exact-sample share and RMS delta are reported for each file. use std::path::{Path, PathBuf}; -use std::process::Command; use ec_ac3::{Ac3Decoder, Options}; -use crate::common::have_ffmpeg; const MIN_CORR: f64 = 0.999; /// Reference RMS below which a channel counts as silent (-80 dBFS). @@ -25,71 +12,8 @@ const SILENT_RMS: f64 = 1e-4; /// RMS delta ceiling on a silent channel: 1/30 of a 16-bit LSB. const SILENT_DELTA: f64 = 1e-6; -fn library_toml() -> PathBuf { - if let Ok(p) = std::env::var("EC_REAL_LIBRARY") { - return PathBuf::from(p); - } - let home = std::env::var("HOME").unwrap_or_default(); - PathBuf::from(home).join("Documents/Code/Rust/edith/real_library.toml") -} - -/// `key = "path"` lines of the TOML file, as (key, path). Only the flat form -/// the library file uses; comments and other lines are ignored. -fn entries(toml: &Path) -> Vec<(String, PathBuf)> { - let Ok(text) = std::fs::read_to_string(toml) else { - return Vec::new(); - }; - text.lines() - .filter_map(|line| { - let line = line.trim(); - if line.starts_with('#') { - return None; - } - let (key, value) = line.split_once('=')?; - let value = value.trim().strip_prefix('"')?.strip_suffix('"')?; - Some((key.trim().to_string(), PathBuf::from(value))) - }) - .collect() -} - -/// The codec and channel count of the file's first audio track. -fn first_audio(path: &Path) -> Option<(String, usize)> { - let out = Command::new("ffprobe") - .args([ - "-v", - "error", - "-select_streams", - "a:0", - "-show_entries", - "stream=codec_name,channels", - "-of", - "csv=p=0", - ]) - .arg(path) - .output() - .ok()?; - let text = String::from_utf8_lossy(&out.stdout); - let mut parts = text.trim().split(','); - Some((parts.next()?.to_string(), parts.next()?.parse().ok()?)) -} - -/// Copies the first `seconds` of the first audio track to `out` as a raw -/// elementary stream of the same codec. Returns false when that fails. -fn extract(path: &Path, codec: &str, seconds: u32, out: &Path) -> bool { - let muxer = if codec == "eac3" { "eac3" } else { "ac3" }; - Command::new("ffmpeg") - .args(["-v", "error", "-nostdin", "-y", "-i"]) - .arg(path) - .args(["-map", "0:a:0", "-t", &seconds.to_string(), "-c", "copy", "-f", muxer]) - .arg(out) - .status() - .map(|s| s.success()) - .unwrap_or(false) -} - -/// ffmpeg's decode of the raw stream as interleaved `f32`. fn reference(path: &Path) -> Vec { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-v", "error", "-nostdin", "-i"]) .arg(path) .args(["-f", "f32le", "-"]) @@ -103,10 +27,9 @@ fn reference(path: &Path) -> Vec { .collect() } -/// Our decode of the raw stream (dither off, as in the matrix test) and the /// channel count. fn decode(path: &Path) -> (Vec, usize) { - let data = std::fs::read(path).expect("extracted stream"); + let data = std::fs::read(path).expect("fixture"); let options = Options { dither: false, ..Options::default() @@ -171,41 +94,17 @@ fn compare(a: &[f32], b: &[f32]) -> (f64, f64, usize, usize) { } #[test] -fn real_library_ac3_and_eac3_match_ffmpeg() { - if !have_ffmpeg() { - eprintln!("skip: ffmpeg not on PATH"); - return; - } - let toml = library_toml(); - let seconds: u32 = std::env::var("EC_REAL_SECONDS") - .ok() - .and_then(|s| s.parse().ok()) - .unwrap_or(20); - let work = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("real-library-ac3"); - std::fs::create_dir_all(&work).expect("work dir"); - - let mut checked = 0; - for (key, path) in entries(&toml) { - if !path.exists() { - eprintln!("skip {key}: {} not on disk", path.display()); - continue; - } - let Some((codec, channels)) = first_audio(&path) else { - eprintln!("skip {key}: ffprobe found no audio track"); - continue; - }; - if codec != "ac3" && codec != "eac3" { - eprintln!("skip {key}: first audio track is {codec}, not AC-3 or E-AC-3"); - continue; - } - let raw = work.join(format!("{key}.{codec}")); - assert!(extract(&path, &codec, seconds, &raw), "{key}: extract failed"); - - let (ours, decoded_channels) = decode(&raw); - let theirs = reference(&raw); - assert_eq!(decoded_channels, channels, "{key}: channel count"); - assert_eq!(ours.len(), theirs.len(), "{key}: sample count vs ffmpeg"); - assert!(!ours.is_empty(), "{key}: nothing decoded"); +fn fate_ac3_and_eac3_match_ffmpeg() { + let files: Vec = ec_testkit::fixtures("open/fate/ac3", "ac3") + .into_iter() + .chain(ec_testkit::fixtures("open/fate/eac3", "eac3")) + .collect(); + for path in files { + let name = path.file_name().unwrap().to_string_lossy().into_owned(); + let (ours, decoded_channels) = decode(&path); + let theirs = reference(&path); + assert_eq!(ours.len(), theirs.len(), "{name}: sample count vs ffmpeg"); + assert!(!ours.is_empty(), "{name}: nothing decoded"); let mut worst = 1.0f64; let mut worst_rms = 0.0f64; @@ -215,7 +114,7 @@ fn real_library_ac3_and_eac3_match_ffmpeg() { let a: Vec = ours[ch..].iter().step_by(decoded_channels).copied().collect(); let b: Vec = theirs[ch..].iter().step_by(decoded_channels).copied().collect(); let (corr, rms, exact, n) = compare(&a, &b); - eprintln!("{key} {codec} ch{ch}: corr {corr:.6} rms {rms:.3e} exact {exact}/{n}"); + eprintln!("{name} ch{ch}: corr {corr:.6} rms {rms:.3e} exact {exact}/{n}"); // A channel whose reference is numerically silent (an LFE that // carries nothing but rounding) has no meaningful correlation, so // it is gated on RMS against one 16-bit LSB / 30 instead. @@ -223,9 +122,9 @@ fn real_library_ac3_and_eac3_match_ffmpeg() { / b.len().max(1) as f64) .sqrt(); if ref_rms < SILENT_RMS { - assert!(rms <= SILENT_DELTA, "{key} ch{ch}: silent-channel RMS delta {rms:.3e}"); + assert!(rms <= SILENT_DELTA, "{name} ch{ch}: silent-channel RMS delta {rms:.3e}"); } else { - assert!(corr >= MIN_CORR, "{key} ch{ch}: correlation {corr:.6}"); + assert!(corr >= MIN_CORR, "{name} ch{ch}: correlation {corr:.6}"); } worst = worst.min(corr); worst_rms = worst_rms.max(rms); @@ -233,10 +132,8 @@ fn real_library_ac3_and_eac3_match_ffmpeg() { total += n; } eprintln!( - "RESULT {key} {codec} {decoded_channels}ch {seconds}s: min corr {worst:.6}, max rms {worst_rms:.3e}, exact {:.4}%", + "RESULT {name} {decoded_channels}ch: min corr {worst:.6}, max rms {worst_rms:.3e}, exact {:.4}%", 100.0 * exact_total as f64 / total.max(1) as f64 ); - checked += 1; } - eprintln!("{checked} real-library AC-3/E-AC-3 entries checked"); } diff --git a/crates/ec-alac/Cargo.toml b/crates/ec-alac/Cargo.toml index c59dbc26..8628f484 100644 --- a/crates/ec-alac/Cargo.toml +++ b/crates/ec-alac/Cargo.toml @@ -12,3 +12,4 @@ ec-core = { workspace = true } [dev-dependencies] ec-mp4 = { workspace = true } ec-riff = { workspace = true } +ec-testkit.workspace = true diff --git a/crates/ec-alac/tests/encode.rs b/crates/ec-alac/tests/encode.rs index 19806e6c..19b5ea91 100644 --- a/crates/ec-alac/tests/encode.rs +++ b/crates/ec-alac/tests/encode.rs @@ -1,20 +1,14 @@ //! Round-trip the encoder through the decoder it was written to feed, then -//! through a real mp4 mux and (when the oracle is present) ffmpeg/ffprobe. use std::fs::File; use std::io::{BufReader, Cursor}; use std::path::{Path, PathBuf}; -use std::process::Command; use ec_alac::{AlacDecoder, AlacEncoder}; use ec_core::registry::{CodecId, Demuxer, Encoder, Muxer, StreamInfo}; use ec_core::timebase::TimeBase; use ec_core::Packet; -fn fixtures() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio") -} - /// A small deterministic PRNG so a "random data" test does not depend on an /// external crate: xorshift32. struct Rng(u32); @@ -80,17 +74,15 @@ fn mux_to_m4a(enc: &AlacEncoder, channels: usize, sample_rate: u32, samples: &[i (dir, out_path) } -/// ffmpeg's decode of `path` in raw format `fmt`, or None when no oracle is -/// installed. -fn ffmpeg_decode(path: &Path, fmt: &str) -> Option> { - let decode = Command::new("ffmpeg") +fn ffmpeg_decode(path: &Path, fmt: &str) -> Vec { + let decode = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-i"]) .arg(path) .args(["-f", fmt, "-"]) .output() - .ok()?; + .expect("ffmpeg"); assert!(decode.status.success(), "{}", String::from_utf8_lossy(&decode.stderr)); - Some(decode.stdout) + decode.stdout } #[test] @@ -99,11 +91,7 @@ fn twenty_four_bit_uses_byte_shift_when_cheaper() { // byte: exactly the shape a 24-bit master of 16-bit source material has, // and exactly what bytes_shifted exists for — the high bits alone // predict well, but folded together with the dither's noise they do not. - let path = fixtures().join("wav16-stereo-48000.wav"); - if !path.exists() { - eprintln!("fixtures/audio absent (gitignored) — skipping"); - return; - } + let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav"); let mut reader = ec_riff::WavReader::open(&path).expect("open wav"); let spec = reader.spec(); let mut rng = Rng(0xdead_beef); @@ -161,7 +149,6 @@ fn twenty_four_bit_tonal_content_round_trips_bit_exactly() { let (dir, out_path) = mux_to_m4a(&enc, channels as usize, 48_000, samples); let got = ffmpeg_decode(&out_path, "s32le"); std::fs::remove_dir_all(&dir).ok(); - let Some(got) = got else { continue }; let want: Vec = samples.iter().flat_map(|&s| (s << 8).to_le_bytes()).collect(); assert!(got == want, "{channels}ch 24-bit tone, shift={allow_shift}: reference decode differs"); } @@ -182,11 +169,7 @@ fn escape_frames_round_trip_random_data() { #[test] fn real_audio_round_trips_and_compresses() { - let path = fixtures().join("wav16-stereo-48000.wav"); - if !path.exists() { - eprintln!("fixtures/audio absent (gitignored) — skipping"); - return; - } + let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav"); let mut reader = ec_riff::WavReader::open(&path).expect("open wav"); let spec = reader.spec(); let samples = reader.read_all_i32().expect("pcm"); @@ -207,11 +190,7 @@ fn real_audio_round_trips_and_compresses() { #[test] fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() { - let path = fixtures().join("wav16-stereo-48000.wav"); - if !path.exists() { - eprintln!("fixtures/audio absent (gitignored) — skipping"); - return; - } + let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav"); let mut reader = ec_riff::WavReader::open(&path).expect("open wav"); let spec = reader.spec(); let samples = reader.read_all_i32().expect("pcm"); @@ -245,11 +224,7 @@ fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() { // The oracle: ffprobe reads the track back as alac at the right rate and // channel count, and ffmpeg's own decode matches the source exactly. - if Command::new("ffprobe").arg("-version").output().is_err() { - eprintln!("ffprobe absent — skipping oracle checks"); - return; - } - let probe = Command::new("ffprobe") + let probe = ec_testkit::ffprobe() .args([ "-v", "error", "-select_streams", "a:0", "-show_entries", "stream=codec_name,sample_rate,channels", @@ -263,7 +238,7 @@ fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() { assert!(info.contains(&format!("sample_rate={}", spec.sample_rate)), "{info}"); assert!(info.contains(&format!("channels={}", spec.channels)), "{info}"); - let Some(stdout) = ffmpeg_decode(&out_path, "s16le") else { return }; + let stdout = ffmpeg_decode(&out_path, "s16le"); let want: Vec = samples.iter().map(|&s| s as i16).collect(); let got: Vec = stdout .as_chunks::<2>().0.iter() @@ -275,8 +250,6 @@ fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() { } -/// Encode through our encoder, decode through ours and (when installed) the -/// reference decoder via a real m4a; both must hand back `samples` exactly. fn round_trip_both_decoders(channels: u8, samples: &[i32], allow_shift: bool, what: &str) { let mut enc = AlacEncoder::new(48_000, channels, 24, 4096).expect("encoder"); enc.set_byte_shift(allow_shift); @@ -291,7 +264,6 @@ fn round_trip_both_decoders(channels: u8, samples: &[i32], allow_shift: bool, wh let (dir, out_path) = mux_to_m4a(&enc, channels as usize, 48_000, samples); let got = ffmpeg_decode(&out_path, "s32le"); std::fs::remove_dir_all(&dir).ok(); - let Some(got) = got else { return }; let want: Vec = samples.iter().flat_map(|&s| (s << 8).to_le_bytes()).collect(); assert!(got == want, "{what}: {channels}ch 24-bit, shift={allow_shift}: reference decode differs"); } diff --git a/crates/ec-alac/tests/oracle.rs b/crates/ec-alac/tests/oracle.rs index 50478455..64c66d4c 100644 --- a/crates/ec-alac/tests/oracle.rs +++ b/crates/ec-alac/tests/oracle.rs @@ -2,21 +2,14 @@ //! same bytes ffmpeg's decoder produces, sample for sample, in the same channel //! order. //! -//! Fixtures come from `scripts/gen-fixtures.sh`; a missing one skips its row -//! rather than failing, so a checkout without generated fixtures still builds. use std::fs::File; use std::io::BufReader; -use std::path::{Path, PathBuf}; -use std::process::Command; +use std::path::Path; use ec_alac::{AlacDecoder, MagicCookie}; use ec_core::registry::{CodecId, Demuxer}; -fn fixtures() -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio") -} - /// Every sample of `path`'s ALAC track, interleaved, as this crate decodes it. fn decode(path: &Path) -> (MagicCookie, Vec) { let mut demuxer = @@ -43,7 +36,7 @@ fn decode(path: &Path) -> (MagicCookie, Vec) { /// ffmpeg's own decode of the same file, in the raw format `fmt` names. fn ffmpeg(path: &Path, fmt: &str) -> Vec { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-i"]) .arg(path) .args(["-f", fmt, "-"]) @@ -71,10 +64,7 @@ fn every_alac_fixture_decodes_bit_exactly() { "alac24-mp4-stereo-48000.m4a", "alac24-mp4-5.1-48000.m4a", ] { - let path = fixtures().join(name); - if !path.exists() { - continue; - } + let path = ec_testkit::fixture(&format!("audio/{name}")); let (cookie, got) = decode(&path); let (fmt, width) = match cookie.bit_depth <= 16 { true => ("s16le", 2), @@ -102,17 +92,14 @@ fn every_alac_fixture_decodes_bit_exactly() { assert_eq!(bad, None, "{name}: first differing sample"); checked += 1; } - assert!(checked > 0, "no ALAC fixtures found — run gen-fixtures.sh"); + assert!(checked > 0, "no ALAC fixtures found"); eprintln!("alac oracle: {checked} fixtures bit-exact vs ffmpeg"); } /// A truncated frame is an error, not a panic — the fuzz floor in miniature. #[test] fn truncated_frames_are_refused_without_panicking() { - let path = fixtures().join("alac-mp4-stereo-44100.m4a"); - if !path.exists() { - return; - } + let path = ec_testkit::fixture("audio/alac-mp4-stereo-44100.m4a"); let mut demuxer = ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&path).expect("open"))).expect("mp4"); let stream = demuxer.streams()[0].clone(); @@ -135,10 +122,6 @@ fn truncated_frames_are_refused_without_panicking() { /// the checked-in fixtures (16-bit, or 24-bit with a shifted low byte) carry. #[test] fn reference_encoded_24_bit_tone_decodes_bit_exactly() { - if Command::new("ffmpeg").arg("-version").output().is_err() { - eprintln!("ffmpeg absent — skipping"); - return; - } let dir = std::env::temp_dir().join(format!("ec-alac-tone-{}", std::process::id())); std::fs::create_dir_all(&dir).expect("tmp"); let raw = dir.join("tone.raw"); @@ -154,7 +137,7 @@ fn reference_encoded_24_bit_tone_decodes_bit_exactly() { }) .collect(); std::fs::write(&raw, &pcm).expect("raw"); - let enc = Command::new("ffmpeg") + let enc = ec_testkit::ffmpeg() .args(["-nostdin", "-y", "-v", "error", "-f", "s32le", "-ar", "48000", "-ac", "2", "-i"]) .arg(&raw) .args(["-c:a", "alac", "-sample_fmt", "s32p"]) diff --git a/crates/ec-amr/Cargo.toml b/crates/ec-amr/Cargo.toml index 55d3b826..ea247b46 100644 --- a/crates/ec-amr/Cargo.toml +++ b/crates/ec-amr/Cargo.toml @@ -12,3 +12,4 @@ ec-core = { workspace = true } [dev-dependencies] ec-mp4 = { workspace = true } ec-riff = { workspace = true } +ec-testkit.workspace = true diff --git a/crates/ec-amr/fuzz/seed.sh b/crates/ec-amr/fuzz/seed.sh index 0ec84bd0..cd16cf39 100755 --- a/crates/ec-amr/fuzz/seed.sh +++ b/crates/ec-amr/fuzz/seed.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # seed.sh: fill fuzz/corpus// with synthetic AMR-NB files, one per mode. -# Needs ffmpeg with libopencore_amrnb. fuzz_container gets each .amr as-is; +# Needs the pinned ffmpeg (EC_FFMPEG) with libopencore_amrnb. fuzz_container gets each .amr as-is; # fuzz_nb_decode gets it with the 6-byte magic stripped (ToC + frames). # Corpus lives under fuzz/corpus, which is git-ignored. set -euo pipefail @@ -9,13 +9,14 @@ FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd) CONT="$FUZZ_DIR/corpus/fuzz_container" DEC="$FUZZ_DIR/corpus/fuzz_nb_decode" mkdir -p "$CONT" "$DEC" +FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg} TMP=$(mktemp -d) trap 'rm -rf "$TMP"' EXIT i=0 for rate in 4750 5150 5900 6700 7400 7950 10200 12200; do f="$TMP/m$i.amr" - ffmpeg -nostdin -v error -f lavfi -i "sine=frequency=$((300 + 150 * i)):duration=2" \ + "$FF" -nostdin -v error -f lavfi -i "sine=frequency=$((300 + 150 * i)):duration=2" \ -ar 8000 -ac 1 -c:a libopencore_amrnb -b:a "$rate" -f amr "$f" cp -f "$f" "$CONT/mode$i.amr" tail -c +7 "$f" > "$DEC/mode$i" diff --git a/crates/ec-amr/tests/container_roundtrip.rs b/crates/ec-amr/tests/container_roundtrip.rs index 57752d5c..e8caa444 100644 --- a/crates/ec-amr/tests/container_roundtrip.rs +++ b/crates/ec-amr/tests/container_roundtrip.rs @@ -5,7 +5,6 @@ use std::fs::File; use std::io::BufReader; -use std::process::Command; use ec_amr::container::{AmrDemuxer, Kind, probe}; use ec_core::registry::{CodecId, Demuxer, MediaParameters, SeekMode}; @@ -15,7 +14,7 @@ const RATES: [u32; 8] = [4750, 5150, 5900, 6700, 7400, 7950, 10200, 12200]; const PAYLOAD: [usize; 8] = [12, 13, 15, 17, 19, 20, 26, 31]; fn ffmpeg(args: &[&str]) -> bool { - Command::new("ffmpeg") + ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-y"]) .args(args) .status() @@ -23,15 +22,6 @@ fn ffmpeg(args: &[&str]) -> bool { .unwrap_or(false) } -fn skip(why: &str) -> bool { - assert!( - std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "EC_REQUIRE_FIXTURES=1 but {why}" - ); - eprintln!("SKIP: {why}"); - true -} - fn drain(d: &mut dyn Demuxer) -> Vec> { let mut out = Vec::new(); loop { @@ -54,10 +44,7 @@ fn amr_3gp_mp4_agree_for_all_modes() { "-c:a", "libopencore_amrnb", "-b:a", &rate.to_string(), "-f", "amr", amr.to_str().unwrap(), ]); - if !enc { - skip("ffmpeg with libopencore_amrnb is not available"); - return; - } + assert!(enc, "ffmpeg with libopencore_amrnb is required"); let bytes = std::fs::read(&amr).unwrap(); assert_eq!(probe(&bytes), Some(Kind::Nb)); @@ -82,7 +69,7 @@ fn amr_3gp_mp4_agree_for_all_modes() { } // ffprobe's own packet count for the same file (75 frames of 20 ms plus // the encoder's flush frame). - let probed = Command::new("ffprobe") + let probed = ec_testkit::ffprobe() .args(["-v", "error", "-count_packets", "-select_streams", "a:0"]) .args(["-show_entries", "stream=nb_read_packets", "-of", "csv=p=0"]) .arg(&amr) diff --git a/crates/ec-amr/tests/oracle.rs b/crates/ec-amr/tests/oracle.rs index a86921b5..070cf2bb 100644 --- a/crates/ec-amr/tests/oracle.rs +++ b/crates/ec-amr/tests/oracle.rs @@ -3,11 +3,8 @@ //! reference this port follows) the output must be bit-exact; against ffmpeg's native `amrnb` //! decoder the SNR is reported and must stay high. //! -//! The fixtures are generated on the fly with ffmpeg from lavfi sources. Without ffmpeg (or -//! without libopencore) the tests skip, unless `EC_REQUIRE_FIXTURES=1`, which makes that a failure. use std::path::{Path, PathBuf}; -use std::process::Command; use ec_amr::nb::bitstream::frame_bytes; use ec_amr::nb::decoder::AmrNbDecoder; @@ -39,10 +36,6 @@ fn sources() -> Vec<(&'static str, String)> { ] } -fn require() -> bool { - std::env::var("EC_REQUIRE_FIXTURES").map(|v| v == "1").unwrap_or(false) -} - fn workdir() -> PathBuf { let d = std::env::temp_dir().join(format!("ec-amr-oracle-{}", std::process::id())); std::fs::create_dir_all(&d).unwrap(); @@ -50,7 +43,7 @@ fn workdir() -> PathBuf { } fn ffmpeg_ok() -> bool { - Command::new("ffmpeg") + ec_testkit::ffmpeg() .args(["-hide_banner", "-h", "decoder=libopencore_amrnb"]) .output() .map(|o| String::from_utf8_lossy(&o.stdout).contains("libopencore_amrnb")) @@ -58,7 +51,7 @@ fn ffmpeg_ok() -> bool { } fn run(args: &[&str]) -> Option> { - let out = Command::new("ffmpeg").args(["-nostdin", "-v", "error", "-y"]).args(args).output().ok()?; + let out = ec_testkit::ffmpeg().args(["-nostdin", "-v", "error", "-y"]).args(args).output().ok()?; out.status.success().then_some(out.stdout) } @@ -132,18 +125,14 @@ fn first_diff(a: &[i16], b: &[i16]) -> Option { (0..a.len().min(b.len())).find(|&i| a[i] != b[i]).or((a.len() != b.len()).then_some(a.len().min(b.len()))) } -fn setup() -> Option { - if !ffmpeg_ok() { - assert!(!require(), "EC_REQUIRE_FIXTURES=1 but ffmpeg with libopencore_amrnb is unavailable"); - eprintln!("skipping: ffmpeg/libopencore_amrnb not available"); - return None; - } - Some(workdir()) +fn setup() -> PathBuf { + assert!(ffmpeg_ok(), "ffmpeg with libopencore_amrnb is required"); + workdir() } #[test] fn all_modes_bit_exact_vs_libopencore() { - let Some(dir) = setup() else { return }; + let dir = setup(); let mut checked = 0; for dtx in [false, true] { for (rate, label) in MODES { @@ -192,7 +181,7 @@ fn rng(state: &mut u64) -> u64 { #[test] fn lost_and_bit_flipped_frames_vs_libopencore() { - let Some(dir) = setup() else { return }; + let dir = setup(); let mut seed = 0x1234_5678_9abc_def1u64; for (rate, label) in MODES { let (sname, src) = &sources()[2]; diff --git a/crates/ec-amr/tests/wb_oracle.rs b/crates/ec-amr/tests/wb_oracle.rs index 38d108f5..24d791d5 100644 --- a/crates/ec-amr/tests/wb_oracle.rs +++ b/crates/ec-amr/tests/wb_oracle.rs @@ -2,13 +2,10 @@ //! the 3GPP TS 26.173 reference code: the output must match it sample for sample. //! //! Fixtures are made here with ffmpeg's `libvo_amrwbenc` from a synthetic source, one file per -//! mode, as `.awb` and as mp4 (`sawb`). A machine without those ffmpeg codecs skips loudly; with -//! `EC_REQUIRE_FIXTURES=1` that is a failure. use std::fs::File; use std::io::{BufReader, Cursor}; use std::path::{Path, PathBuf}; -use std::process::Command; use ec_amr::container::AmrDemuxer; use ec_amr::wb::AmrWbDecoder; @@ -18,7 +15,7 @@ const RATES: [u32; 9] = [6600, 8850, 12650, 14250, 15850, 18250, 19850, 23050, 2 const PAYLOAD: [usize; 10] = [17, 23, 32, 36, 40, 46, 50, 58, 60, 5]; fn ffmpeg(args: &[&str]) -> Option> { - let out = Command::new("ffmpeg") + let out = ec_testkit::ffmpeg() .args(["-nostdin", "-v", "error", "-y"]) .args(args) .output() @@ -26,15 +23,6 @@ fn ffmpeg(args: &[&str]) -> Option> { out.status.success().then_some(out.stdout) } -fn skip(why: &str) -> bool { - assert!( - std::env::var_os("EC_REQUIRE_FIXTURES").is_none(), - "EC_REQUIRE_FIXTURES=1 but {why}" - ); - eprintln!("SKIP: {why}"); - true -} - struct Dir(PathBuf); impl Dir { fn new(tag: &str) -> Dir { @@ -136,9 +124,7 @@ fn have_tools() -> bool { #[test] fn every_mode_matches_the_reference_decoder_in_awb_and_mp4() { - if !have_tools() && skip("ffmpeg lacks libvo_amrwbenc/libopencore_amrwb") { - return; - } + assert!(have_tools(), "ffmpeg lacks libvo_amrwbenc/libopencore_amrwb"); let dir = Dir::new("modes"); for rate in RATES { let awb = dir.path(&format!("m{rate}.awb")); @@ -183,9 +169,7 @@ fn lcg(state: &mut u64) -> u8 { #[test] fn comfort_noise_lost_and_corrupted_frames_match_the_reference() { - if !have_tools() && skip("ffmpeg lacks libvo_amrwbenc/libopencore_amrwb") { - return; - } + assert!(have_tools(), "ffmpeg lacks libvo_amrwbenc/libopencore_amrwb"); let dir = Dir::new("chaos"); // Real frames of three modes, mixed with SID, lost and corrupted ones (quality bit kept set: // the reference wrapper ignores it). diff --git a/scripts/aac-tables/make-he-fixtures.sh b/scripts/aac-tables/make-he-fixtures.sh index 50d51401..18144a43 100755 --- a/scripts/aac-tables/make-he-fixtures.sh +++ b/scripts/aac-tables/make-he-fixtures.sh @@ -12,7 +12,7 @@ LIBDIR=${1:-}; OUT=$2; mkdir -p "$OUT" if [ -n "$LIBDIR" ]; then export LD_LIBRARY_PATH="$LIBDIR${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" fi -FF="ffmpeg -v error -y -hide_banner" +FF="${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg} -v error -y -hide_banner" RATE=22050 # Mono: a tone plus a chirp (the chirp exercises the SBR patch range), with pink noise above it. diff --git a/scripts/aac-tables/make-heaac-fixtures.sh b/scripts/aac-tables/make-heaac-fixtures.sh deleted file mode 100755 index 279aebee..00000000 --- a/scripts/aac-tables/make-heaac-fixtures.sh +++ /dev/null @@ -1,67 +0,0 @@ -#!/usr/bin/env bash -# Deterministic HE-AAC v1 fixture matrix for tests/sbr_real_library.rs's -# `synthetic_heaac_matrix`: two sample-rate families (48000, 44100) x four -# bitrates (32k/48k/64k/96k) x two profiles (aac_he, aac_low control) = 16 -# .m4a files, sweeping the SBR crossover (kx/k2) that bitrate controls -# without depending on any one real file's content. -# -# `ffmpeg`'s system libfdk_aac (the `fdk-aac-free` package) has SBR/PS -# encoding compiled out (patent-restricted tools) -- `-profile:a aac_he` -# fails with "Unable to set the AOT 5: Invalid config" against it. RPM -# Fusion's full `fdk-aac` package carries the SBR-capable encoder but -# installs to its OWN /usr/lib64/fdk-aac dir specifically so it doesn't -# clobber the system one; this script fetches (no root) and extracts just -# that .so into a local cache and points ffmpeg at it via -# LD_LIBRARY_PATH for the encode step only, never touching the system -# library. -set -euo pipefail - -SCRATCH="${EC_AAC_HEAAC_FIXTURES:-$(cd "$(dirname "$0")/../.." && pwd)/.cache/heaac-fixtures}" -mkdir -p "$SCRATCH" -CACHE="$SCRATCH/.fdk-aac-full" -mkdir -p "$CACHE" - -fdk_libdir="$CACHE/usr/lib64/fdk-aac" -if [ ! -f "$fdk_libdir/libfdk-aac.so.2" ]; then - echo "fetching SBR-capable libfdk-aac (no root, local cache only)..." - ( cd "$CACHE" && dnf download fdk-aac.x86_64 ) - rpm_file=$(find "$CACHE" -maxdepth 1 -name 'fdk-aac-*.rpm' | head -1) - ( cd "$CACHE" && rpm2cpio "$rpm_file" | cpio -idm --quiet ) -fi -export LD_LIBRARY_PATH="$fdk_libdir${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" - -# Three summed sweeps 100 Hz -> 18 kHz over the full 30 s (phase(t) = -# 2*pi*(f0*t + (f1-f0)/(2T)*t^2), f0=100 f1=18000 T=30 -> -# (f1-f0)/(2T)=298.333), offset in phase per partial and per channel so -# left/right are correlated but not identical -- plus low-level pink noise -# (seeded, so every run of this script reproduces bit-identical fixtures). -sweep() { echo "0.15*sin(2*PI*(100*t+298.333*t*t)+$1)+0.15*sin(2*PI*(100*t+298.333*t*t)+$2)+0.15*sin(2*PI*(100*t+298.333*t*t)+$3)"; } -L=$(sweep 0 1.047 2.094) -R=$(sweep 0.5 1.571 2.618) - -synth_source() { - local rate=$1 out=$2 - ffmpeg -y -hide_banner -loglevel error -filter_complex " - aevalsrc=exprs='${L}|${R}':channel_layout=stereo:sample_rate=${rate}:duration=30 [tone]; - anoisesrc=color=pink:amplitude=0.05:seed=42:sample_rate=${rate}:duration=30 [n0]; - anoisesrc=color=pink:amplitude=0.05:seed=43:sample_rate=${rate}:duration=30 [n1]; - [n0][n1] amerge=inputs=2 [noise]; - [tone][noise] amix=inputs=2:normalize=0 [out] - " -map "[out]" -ar "$rate" -sample_fmt s16 -f wav "$out" -} - -for rate in 48000 44100; do - src="$SCRATCH/src_${rate}.wav" - [ -f "$src" ] || synth_source "$rate" "$src" - for br in 32k 48k 64k 96k; do - he="$SCRATCH/heaac_${rate}_${br}.m4a" - lc="$SCRATCH/lc_${rate}_${br}.m4a" - [ -f "$he" ] || ffmpeg -y -hide_banner -loglevel error -i "$src" \ - -c:a libfdk_aac -profile:a aac_he -b:a "$br" "$he" - [ -f "$lc" ] || ffmpeg -y -hide_banner -loglevel error -i "$src" \ - -c:a libfdk_aac -profile:a aac_low -b:a "$br" "$lc" - done -done - -echo "fixtures in $SCRATCH:" -ls "$SCRATCH"/*.m4a diff --git a/scripts/aac-tables/make-ps-fixtures.sh b/scripts/aac-tables/make-ps-fixtures.sh index 5b7749a2..22a2b4fd 100755 --- a/scripts/aac-tables/make-ps-fixtures.sh +++ b/scripts/aac-tables/make-ps-fixtures.sh @@ -8,7 +8,7 @@ set -euo pipefail LIBDIR=$1; OUT=$2; mkdir -p "$OUT" export LD_LIBRARY_PATH="$LIBDIR${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" -FF="ffmpeg -v error -y -hide_banner" +FF="${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg} -v error -y -hide_banner" for rate in 44100 48000; do # Sine pair: distinct tones per channel (strong, simple PS content). $FF -f lavfi -i "sine=440:d=2:r=$rate" -f lavfi -i "sine=660:d=2:r=$rate" \