forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'simplify/w0-m1' into simplify/w0

Browse files at this commit

f3c77ef05404c601c7f09815a6a6ca930b7b1ec0Ahmet Kaan GümüşParent: b8a94610221876

39 changed files +330 -2057

Cargo.lockmodified+4 -0
@@ -330,6 +330,7 @@ dependencies = [
330330 "ec-dsp",
331331 "ec-matroska",
332332 "ec-mp4",
333+ "ec-testkit",
333334 ]
334335
335336 [[package]]
@@ -338,6 +339,7 @@ version = "0.1.0"
338339 dependencies = [
339340 "ec-core",
340341 "ec-dsp",
342+ "ec-testkit",
341343 ]
342344
343345 [[package]]
@@ -347,6 +349,7 @@ dependencies = [
347349 "ec-core",
348350 "ec-mp4",
349351 "ec-riff",
352+ "ec-testkit",
350353 ]
351354
352355 [[package]]
@@ -356,6 +359,7 @@ dependencies = [
356359 "ec-core",
357360 "ec-mp4",
358361 "ec-riff",
362+ "ec-testkit",
359363 ]
360364
361365 [[package]]
crates/ec-aac/Cargo.tomlmodified+1 -0
@@ -13,3 +13,4 @@ ec-dsp = { workspace = true }
1313 [dev-dependencies]
1414 ec-mp4 = { workspace = true }
1515 ec-matroska = { workspace = true }
16+ec-testkit.workspace = true
crates/ec-aac/fuzz/seed.shmodified+2 -2
@@ -18,8 +18,8 @@ mkdir -p "$HE_CORPUS"
1818 for f in "$HE_DIR"/*.aac; do cp -f "$f" "$HE_CORPUS/"; done
1919 echo "seeded $(ls "$HE_CORPUS" | wc -l) decode_he seeds"
2020
21-FIXTURES=$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures/audio
22-[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/link-fixtures.sh (decode_he is seeded)" >&2; exit 0; }
21+FIXTURES=${EC_FIXTURES:-$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures}/audio
22+[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/fixtures.sh" >&2; exit 2; }
2323
2424 ADTS=("$FIXTURES"/aac-adts-*.aac)
2525 [ -e "${ADTS[0]}" ] || { echo "seed.sh: no aac-adts-*.aac fixtures in $FIXTURES" >&2; exit 2; }
crates/ec-aac/tests/common/mod.rsdeleted+0 -18
@@ -1,18 +0,0 @@
1-//! Helpers shared by the ec-aac test binaries that need them: `oracle`,
2-//! `obs_real_content`, `sbr_real_library` and the merged `it` binary.
3-
4-use std::path::{Path, PathBuf};
5-use std::process::Command;
6-
7-pub fn have_ffmpeg() -> bool {
8- Command::new("ffmpeg")
9- .arg("-version")
10- .output()
11- .map(|o| o.status.success())
12- .unwrap_or(false)
13-}
14-
15-#[allow(dead_code)] // not used by the sbr_real_library binary
16-pub fn fixtures() -> PathBuf {
17- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
18-}
crates/ec-aac/tests/it/implicit_sbr.rsmodified+2 -40
@@ -2,28 +2,10 @@
22 //! ADTS header says plain AAC-LC, but whose frames carry an SBR extension
33 //! payload, is decoded as HE-AAC at twice the core rate, as ffmpeg does.
44
5-use crate::shared::fixtures;
6-use crate::shared::have_ffmpeg;
75 use std::path::{Path, PathBuf};
8-use std::process::Command;
96
107 use ec_aac::{AacDecoder, SbrSupport};
118
12-/// Same contract as `oracle.rs`: an absent fixture skips loudly, and under
13-/// `EC_REQUIRE_FIXTURES=1` it is a hard failure instead.
14-fn require_fixture(path: &Path) -> bool {
15- let present = path.exists();
16- assert!(
17- present || std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
18- "EC_REQUIRE_FIXTURES=1 but fixture {} is absent",
19- path.display()
20- );
21- if !present {
22- eprintln!("SKIP: fixture {} absent", path.display());
23- }
24- present
25-}
26-
279 /// The implicit-signalling HE-AAC fixture: 2 s of `heaac_44100_48k.m4a` remuxed to
2810 /// bare ADTS with `ffmpeg -c copy -f adts`. Its headers say AAC-LC at 22050 Hz.
2911 fn implicit_fixture() -> PathBuf {
@@ -32,7 +14,7 @@ fn implicit_fixture() -> PathBuf {
3214
3315 /// ffmpeg's decode of a file, as planar-by-channel `f32`.
3416 fn ffmpeg_decode(path: &Path) -> Vec<Vec<f32>> {
35- let out = Command::new("ffmpeg")
17+ let out = ec_testkit::ffmpeg()
3618 .args(["-v", "error", "-i"])
3719 .arg(path)
3820 .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])
@@ -112,9 +94,6 @@ fn decode_adts(path: &Path) -> (Vec<Vec<f32>>, Option<u32>, Vec<u32>, AacDecoder
11294 #[test]
11395 fn implicit_he_aac_adts_switches_to_double_rate() {
11496 let path = implicit_fixture();
115- if !require_fixture(&path) {
116- return;
117- }
11897 let (ours, before, rates, decoder) = decode_adts(&path);
11998
12099 // 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() {
139118
140119 #[test]
141120 fn implicit_he_aac_adts_matches_ffmpeg_per_channel() {
142- if !have_ffmpeg() {
143- eprintln!("SKIP: ffmpeg not on PATH");
144- return;
145- }
146121 let path = implicit_fixture();
147- if !require_fixture(&path) {
148- return;
149- }
150122 let (ours, _, _, _) = decode_adts(&path);
151123 let theirs = ffmpeg_decode(&path);
152124 assert_eq!(theirs.len(), ours.len());
@@ -158,14 +130,7 @@ fn implicit_he_aac_adts_matches_ffmpeg_per_channel() {
158130
159131 #[test]
160132 fn plain_aac_lc_adts_is_unchanged_by_implicit_detection() {
161- if !have_ffmpeg() {
162- eprintln!("SKIP: ffmpeg not on PATH");
163- return;
164- }
165- let path = fixtures().join("audio/aac-adts-stereo-44100.aac");
166- if !require_fixture(&path) {
167- return;
168- }
133+ let path = ec_testkit::fixture("audio/aac-adts-stereo-44100.aac");
169134 let (ours, _, rates, decoder) = decode_adts(&path);
170135
171136 // 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() {
189154 #[test]
190155 fn core_only_decode_of_implicit_he_aac_stays_at_core_rate() {
191156 let path = implicit_fixture();
192- if !require_fixture(&path) {
193- return;
194- }
195157 let data = std::fs::read(&path).expect("fixture readable");
196158 let mut decoder = AacDecoder::new().core_only();
197159 let mut frames = 0usize;
crates/ec-aac/tests/it/main.rsmodified+0 -2
@@ -1,8 +1,6 @@
11 #![forbid(unsafe_code)]
22 //! Merged integration tests for ec-aac: one module per former `tests/*.rs` file.
33
4-#[path = "../common/mod.rs"]
5-mod shared;
64 mod common;
75
86 mod he_parity;
crates/ec-aac/tests/it/multichannel_parity.rsmodified+6 -51
@@ -11,13 +11,10 @@
1111 //! then each channel's correlation must reach 0.999. For 5.1 and 7.1 the channel
1212 //! order is also checked: our channel k must correlate best with FFmpeg's channel k.
1313 //!
14-//! Fixtures are generated at test time, so no media is committed. Without ffmpeg
15-//! the test skips loudly; with `EC_REQUIRE_FIXTURES=1` a missing ffmpeg is a failure.
1614
1715 use std::fs::File;
1816 use std::io::BufReader;
1917 use std::path::{Path, PathBuf};
20-use std::process::Command;
2118
2219 use ec_aac::{AacDecoder, is_adts, parse_adts};
2320 use ec_core::{CodecId, Demuxer, Packet};
@@ -74,41 +71,13 @@ const LAYOUTS: &[Layout] = &[
7471 Layout { name: "7.1", channels: 8, freqs: &[300, 450, 620, 780, 960, 1130, 1310, 1500] },
7572 ];
7673
77-/// The encoders under test. Native `aac` is always present; `libfdk_aac` is used
78-/// only when the local ffmpeg lists it.
7974 const ENCODERS: &[&str] = &["aac", "libfdk_aac"];
8075
8176 fn fixtures_dir() -> PathBuf {
8277 PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("aac_multichannel")
8378 }
8479
85-fn ffmpeg_ok(args: &[&str]) -> bool {
86- Command::new("ffmpeg")
87- .args(args)
88- .output()
89- .map(|o| o.status.success())
90- .unwrap_or(false)
91-}
92-
93-fn have_ffmpeg() -> bool {
94- ffmpeg_ok(&["-version"])
95-}
96-
97-fn have_encoder(name: &str) -> bool {
98- let out = Command::new("ffmpeg")
99- .args(["-hide_banner", "-encoders"])
100- .output();
101- match out {
102- Ok(o) => String::from_utf8_lossy(&o.stdout)
103- .lines()
104- .any(|l| l.split_whitespace().nth(1) == Some(name)),
105- Err(_) => false,
106- }
107-}
108-
109-/// Encodes a multitone of `layout` with `encoder` into `container`. Returns the path,
110-/// or `None` when the encoder refuses the configuration.
111-fn encode(layout: &Layout, encoder: &str, container: Container) -> Option<PathBuf> {
80+fn encode(layout: &Layout, encoder: &str, container: Container) -> PathBuf {
11281 let dir = fixtures_dir();
11382 std::fs::create_dir_all(&dir).expect("fixture dir");
11483 let out = dir.join(format!(
@@ -130,19 +99,20 @@ fn encode(layout: &Layout, encoder: &str, container: Container) -> Option<PathBu
13099 );
131100 // 48 kbit/s per channel keeps every layout in a comfortable quality range.
132101 let bitrate = format!("{}k", 48 * layout.channels);
133- let status = Command::new("ffmpeg")
102+ let status = ec_testkit::ffmpeg()
134103 .args(["-v", "error", "-y", "-f", "lavfi", "-i", &source])
135104 .args(["-c:a", encoder, "-profile:a", "aac_low", "-b:a", &bitrate])
136105 .args(["-ac", &layout.channels.to_string(), "-f", container.muxer()])
137106 .arg(&out)
138107 .status()
139108 .expect("ffmpeg runs");
140- status.success().then_some(out)
109+ assert!(status.success(), "{encoder} refused the {} layout", layout.name);
110+ out
141111 }
142112
143113 /// FFmpeg's decode of `path` as planar-by-channel `f32`, in its own channel order.
144114 fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<Vec<f32>> {
145- let out = Command::new("ffmpeg")
115+ let out = ec_testkit::ffmpeg()
146116 .args(["-v", "error", "-i"])
147117 .arg(path)
148118 .args(["-f", "f32le", "-acodec", "pcm_f32le", "-ac"])
@@ -310,10 +280,7 @@ fn matrix(ours: &[Vec<f32>], theirs: &[Vec<f32>], lag: i64) -> Vec<Vec<f64>> {
310280
311281 fn check_case(layout: &Layout, encoder: &str, container: Container, failures: &mut Vec<String>) {
312282 let label = format!("{:<6} {:<5} {:<10}", layout.name, container.label(), encoder);
313- let Some(path) = encode(layout, encoder, container) else {
314- println!("SKIP {label}: encoder refused the configuration");
315- return;
316- };
283+ let path = encode(layout, encoder, container);
317284 let theirs = ffmpeg_decode(&path, layout.channels);
318285 let (ours, channels, rate) = match container {
319286 Container::Adts => ours_adts(&path),
@@ -369,20 +336,8 @@ fn check_case(layout: &Layout, encoder: &str, container: Container, failures: &m
369336
370337 #[test]
371338 fn multichannel_matches_ffmpeg_per_channel() {
372- if !have_ffmpeg() {
373- assert!(
374- std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
375- "EC_REQUIRE_FIXTURES=1 but ffmpeg is not installed"
376- );
377- eprintln!("SKIP: ffmpeg not installed");
378- return;
379- }
380339 let mut failures = Vec::new();
381340 for encoder in ENCODERS {
382- if *encoder != "aac" && !have_encoder(encoder) {
383- println!("SKIP encoder {encoder}: not built into this ffmpeg");
384- continue;
385- }
386341 for layout in LAYOUTS {
387342 for container in [Container::Adts, Container::Mp4] {
388343 check_case(layout, encoder, container, &mut failures);
crates/ec-aac/tests/it/no_panic.rsmodified+1 -28
@@ -6,7 +6,6 @@
66 //! produced it instead of aborting the whole run.
77
88 use std::panic::{catch_unwind, AssertUnwindSafe};
9-use std::path::{Path, PathBuf};
109
1110 use ec_aac::AacDecoder;
1211
@@ -40,10 +39,6 @@ impl Rng {
4039 }
4140 }
4241
43-fn audio_dir() -> PathBuf {
44- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio")
45-}
46-
4742 /// Decodes one packet with a fresh decoder. Returns false if it panicked.
4843 fn decode_no_panic(label: &str, packet: &[u8]) -> bool {
4944 let outcome = catch_unwind(AssertUnwindSafe(|| {
@@ -76,27 +71,11 @@ fn adts_frame_starts(data: &[u8]) -> Vec<usize> {
7671
7772 #[test]
7873 fn fixtures_truncated_and_corrupted_never_panic() {
79- let dir = audio_dir();
80- let mut found = 0usize;
8174 let mut failures: Vec<String> = Vec::new();
8275 let mut rng = Rng(SEED);
8376
8477 for name in ADTS_FIXTURES {
85- let path = dir.join(name);
86- let data = match std::fs::read(&path) {
87- Ok(d) => d,
88- Err(_) => {
89- if std::env::var_os("EC_REQUIRE_FIXTURES").is_some() {
90- panic!(
91- "EC_REQUIRE_FIXTURES=1 but fixture {} is absent -- regenerate with: scripts/gen-fixtures.sh",
92- path.display()
93- );
94- }
95- eprintln!("SKIP: fixture {} absent", path.display());
96- continue;
97- }
98- };
99- found += 1;
78+ let data = std::fs::read(ec_testkit::fixture(&format!("audio/{name}"))).expect("fixture");
10079 assert!(!adts_frame_starts(&data).is_empty(), "{name} is not an ADTS stream");
10180
10281 // Ten truncation points spread across the file (never the full length).
@@ -124,12 +103,6 @@ fn fixtures_truncated_and_corrupted_never_panic() {
124103 }
125104 }
126105
127- if found == 0 {
128- if std::env::var_os("EC_REQUIRE_FIXTURES").is_some() {
129- panic!("no ADTS fixtures found under {}", dir.display());
130- }
131- eprintln!("SKIP: no ADTS fixtures under {}", dir.display());
132- }
133106 assert!(failures.is_empty(), "{} inputs panicked: {:?}", failures.len(), failures);
134107 }
135108
crates/ec-aac/tests/it/ps_mp4.rsmodified+2 -9
@@ -7,12 +7,10 @@
77 //! produce two channels at the extension rate, matching FFmpeg's own decode of
88 //! the same mp4.
99
10-use crate::shared::have_ffmpeg;
1110 use crate::common::fixture;
1211 use std::fs::File;
1312 use std::io::BufReader;
1413 use std::path::{Path, PathBuf};
15-use std::process::Command;
1614
1715 use ec_aac::AacDecoder;
1816 use ec_core::{CodecId, Demuxer, Packet};
@@ -23,7 +21,7 @@ const RATE: u32 = 48_000;
2321
2422 /// FFmpeg's decode of `path` as interleaved f32, two channels at `RATE`.
2523 fn ffmpeg_stereo(path: &Path) -> Vec<f32> {
26- let out = Command::new("ffmpeg")
24+ let out = ec_testkit::ffmpeg()
2725 .args(["-v", "error", "-i"])
2826 .arg(path)
2927 .args(["-f", "f32le", "-ac", "2", "-ar", "48000", "-"])
@@ -50,16 +48,11 @@ fn correlation(a: &[f32], b: &[f32]) -> f64 {
5048
5149 #[test]
5250 fn ps_in_mp4_decodes_to_stereo_like_ffmpeg() {
53- if !have_ffmpeg() {
54- eprintln!("SKIP: ffmpeg not installed");
55- return;
56- }
5751 let src = fixture(FIXTURE);
58- assert!(src.exists(), "fixture {} is absent", src.display());
5952 let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR"));
6053 std::fs::create_dir_all(&dir).expect("temp dir");
6154 let mp4 = dir.join("ps_48000_music.m4a");
62- let status = Command::new("ffmpeg")
55+ let status = ec_testkit::ffmpeg()
6356 .args(["-v", "error", "-y", "-i"])
6457 .arg(&src)
6558 .args(["-c", "copy", "-f", "mp4"])
crates/ec-aac/tests/it/ps_oracle.rsmodified+1 -18
@@ -6,13 +6,11 @@
66 //! at least 0.999 after a bounded lag search, which absorbs decoder priming
77 //! delay, as `sbr_real_library.rs` does for HE-AAC v1.
88
9-use crate::shared::have_ffmpeg;
109 use crate::common::fixture;
1110 use crate::common::deinterleave;
1211 use crate::common::correlation;
1312 use ec_aac::AacDecoder;
1413 use std::path::Path;
15-use std::process::Command;
1614
1715 /// Per-channel correlation the reconstruction must reach against FFmpeg.
1816 const MIN_CORR: f64 = 0.999;
@@ -39,7 +37,7 @@ const FIXTURES: &[(&str, u32)] = &[
3937
4038 /// FFmpeg's decode of `path` as planar stereo `f32`.
4139 fn ffmpeg_reference(path: &Path) -> Vec<Vec<f32>> {
42- let out = Command::new("ffmpeg")
40+ let out = ec_testkit::ffmpeg()
4341 .args(["-v", "error", "-i"])
4442 .arg(path)
4543 .args(["-ac", "2", "-f", "f32le", "-acodec", "pcm_f32le", "-"])
@@ -97,24 +95,9 @@ fn best_lag(ours: &[f32], theirs: &[f32]) -> (i64, f64) {
9795
9896 #[test]
9997 fn ps_fixtures_decode_to_stereo_matching_ffmpeg() {
100- let require = std::env::var_os("EC_REQUIRE_FIXTURES").is_some();
101- if !have_ffmpeg() {
102- assert!(!require, "EC_REQUIRE_FIXTURES=1 but ffmpeg is not installed");
103- eprintln!("SKIP: ffmpeg not installed");
104- return;
105- }
10698 let mut failures = Vec::new();
10799 for &(name, rate) in FIXTURES {
108100 let path = fixture(name);
109- assert!(
110- path.exists() || !require,
111- "EC_REQUIRE_FIXTURES=1 but fixture {} is absent",
112- path.display()
113- );
114- if !path.exists() {
115- eprintln!("SKIP: fixture {} absent", path.display());
116- continue;
117- }
118101 let bytes = std::fs::read(&path).expect("fixture reads");
119102 let audio = AacDecoder::new()
120103 .decode(&bytes, None)
crates/ec-aac/tests/it/reelh_per_frame.rsmodified+4 -15
@@ -3,11 +3,8 @@
33 //! collapses mid-stream, sequentially, with no seek/reset. Finds the first
44 //! bad frame and its side info, to compare with the frame before.
55
6-use crate::shared::have_ffmpeg;
76 use std::fs::File;
87 use std::io::BufReader;
9-use std::path::Path;
10-use std::process::Command;
118
129 use ec_aac::AacDecoder;
1310 use ec_core::{CodecId, Demuxer, Packet};
@@ -15,21 +12,13 @@ use ec_mp4::Mp4Demuxer;
1512
1613 #[test]
1714 fn reelh_per_frame_scan() {
18- if !have_ffmpeg() {
19- eprintln!("skip: no ffmpeg");
20- return;
21- }
22- let path = Path::new("/home/user/Downloads/reelh.mp4");
23- if !path.exists() {
24- eprintln!("skip: file not present");
25- return;
26- }
15+ let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4");
2716 let _knob = ec_aac::knobs::set_tool_sideinfo_debug(Some(true));
2817
2918 // ffmpeg's channel-0-only decode (pan, not -ac, per the repro).
30- let out = Command::new("ffmpeg")
19+ let out = ec_testkit::ffmpeg()
3120 .args(["-v", "error", "-i"])
32- .arg(path)
21+ .arg(&path)
3322 .args([
3423 "-map", "0:a:0", "-af", "pan=1c|c0=c0", "-f", "f32le", "-acodec", "pcm_f32le", "-",
3524 ])
@@ -43,7 +32,7 @@ fn reelh_per_frame_scan() {
4332 .collect();
4433
4534 // Our sequential decode: one decoder, no reset, packet 0 onward.
46- let f = File::open(path).unwrap();
35+ let f = File::open(&path).unwrap();
4736 let mut d = Mp4Demuxer::new(BufReader::new(f)).unwrap();
4837 let aac = d
4938 .streams()
crates/ec-aac/tests/obs_real_content.rsdeleted+0 -249
@@ -1,249 +0,0 @@
1-//! Table over every screen recording under `~/Videos/OBS`, diagnosing the
2-//! PNS/M/S decorrelation the consumer sweep found in that encoder's output
3-//! (see repo ledger). Real files, read-only, absent directory skips loudly.
4-
5-mod common;
6-
7-use common::have_ffmpeg;
8-use std::path::{Path, PathBuf};
9-use std::process::Command;
10-
11-use ec_aac::AacDecoder;
12-use ec_core::{CodecId, Demuxer, Packet};
13-use ec_mp4::Mp4Demuxer;
14-use std::fs::File;
15-use std::io::BufReader;
16-
17-const MAX_SAMPLES: usize = 480_000; // 10s @ 48kHz
18-const LAG_MAX: usize = 4_000;
19-const WINDOW: usize = 200_000;
20-
21-fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<Vec<f32>> {
22- let out = Command::new("ffmpeg")
23- .args(["-v", "error", "-i"])
24- .arg(path)
25- .args([
26- "-map",
27- "0:a:0",
28- "-t",
29- "10",
30- "-f",
31- "f32le",
32- "-acodec",
33- "pcm_f32le",
34- "-",
35- ])
36- .output()
37- .expect("ffmpeg runs");
38- assert!(
39- out.status.success(),
40- "{}",
41- String::from_utf8_lossy(&out.stderr)
42- );
43- let samples: Vec<f32> = out
44- .stdout
45- .as_chunks::<4>().0.iter()
46- .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
47- .collect();
48- let mut planes = vec![Vec::with_capacity(samples.len() / channels.max(1)); channels];
49- for (i, &v) in samples.iter().enumerate() {
50- planes[i % channels].push(v);
51- }
52- planes
53-}
54-
55-fn extract_aac_track(path: &Path) -> Option<(Vec<u8>, Vec<Vec<u8>>)> {
56- let f = File::open(path).ok()?;
57- let mut d = Mp4Demuxer::new(BufReader::new(f)).ok()?;
58- let aac = d
59- .streams()
60- .iter()
61- .find(|s| s.params.codec == CodecId::Aac)?;
62- let idx = aac.index;
63- let asc = aac.params.extradata.as_ref()?.to_vec();
64- let mut aus = Vec::new();
65- while aus.len() < 1_500 {
66- match d.next_packet() {
67- Ok(Packet { stream, data, .. }) if stream == idx => aus.push(data.to_vec()),
68- Ok(_) => continue,
69- Err(_) => break,
70- }
71- }
72- Some((asc, aus))
73-}
74-
75-fn our_decode(path: &Path) -> Option<Vec<Vec<f32>>> {
76- let (asc, aus) = extract_aac_track(path)?;
77- let mut decoder = AacDecoder::with_config_bytes(&asc).ok()?;
78- let mut planes: Vec<Vec<f32>> = Vec::new();
79- let mut failed = 0usize;
80- for au in &aus {
81- let frame = match decoder.decode(au, None) {
82- Ok(f) => f,
83- Err(_) => {
84- failed += 1;
85- continue;
86- }
87- };
88- let ch = usize::from(frame.channels);
89- if ch == 0 {
90- continue;
91- }
92- if planes.is_empty() {
93- planes = vec![Vec::new(); ch];
94- }
95- for (i, v) in frame.samples.iter().enumerate() {
96- planes[i % ch].push(*v);
97- }
98- if planes[0].len() >= MAX_SAMPLES {
99- break;
100- }
101- }
102- eprintln!(" {failed}/{} AUs failed", aus.len());
103- if planes.is_empty() {
104- None
105- } else {
106- Some(planes)
107- }
108-}
109-
110-fn dot(a: &[f32], b: &[f32]) -> f64 {
111- a.iter()
112- .zip(b)
113- .map(|(x, y)| f64::from(*x) * f64::from(*y))
114- .sum()
115-}
116-
117-fn correlation(a: &[f32], b: &[f32]) -> f64 {
118- let n = a.len().min(b.len());
119- if n < 1024 {
120- return 0.0;
121- }
122- let (a, b) = (&a[..n], &b[..n]);
123- let ma = a.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
124- let mb = b.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
125- let ac: Vec<f32> = a.iter().map(|v| (f64::from(*v) - ma) as f32).collect();
126- let bc: Vec<f32> = b.iter().map(|v| (f64::from(*v) - mb) as f32).collect();
127- let num = dot(&ac, &bc);
128- let den = (dot(&ac, &ac) * dot(&bc, &bc)).sqrt();
129- if den == 0.0 { 0.0 } else { num / den }
130-}
131-
132-fn best_lag_correlation(ours: &[f32], theirs: &[f32]) -> (i64, f64) {
133- const COARSE: usize = 4_096;
134- let start = ours
135- .len()
136- .min(theirs.len())
137- .saturating_sub(WINDOW)
138- .min(ours.len() / 4);
139- let slice_at = |lag: i64, len: usize| -> Option<(usize, usize)> {
140- let (oa, ob) = if lag >= 0 {
141- (start, start + lag as usize)
142- } else {
143- (start + (-lag) as usize, start)
144- };
145- if oa + len > ours.len() || ob + len > theirs.len() {
146- None
147- } else {
148- Some((oa, ob))
149- }
150- };
151- let mut coarse_best = (0i64, -1.0f64, 0.0f64);
152- for lag in -(LAG_MAX as i64)..=(LAG_MAX as i64) {
153- let Some((oa, ob)) = slice_at(lag, COARSE) else {
154- continue;
155- };
156- let c = correlation(&ours[oa..oa + COARSE], &theirs[ob..ob + COARSE]);
157- if c.abs() > coarse_best.1 {
158- coarse_best = (lag, c.abs(), c);
159- }
160- }
161- let mut best = (coarse_best.0, -1.0f64, 0.0f64);
162- for lag in (coarse_best.0 - 8)..=(coarse_best.0 + 8) {
163- let Some((oa, ob)) = slice_at(lag, WINDOW) else {
164- continue;
165- };
166- let c = correlation(&ours[oa..oa + WINDOW], &theirs[ob..ob + WINDOW]);
167- if c.abs() > best.1 {
168- best = (lag, c.abs(), c);
169- }
170- }
171- (best.0, best.2)
172-}
173-
174-fn rms(a: &[f32]) -> f64 {
175- (a.iter().map(|v| f64::from(*v) * f64::from(*v)).sum::<f64>() / a.len().max(1) as f64).sqrt()
176-}
177-
178-#[test]
179-fn obs_content_table() {
180- if !have_ffmpeg() {
181- eprintln!("skip: no ffmpeg");
182- return;
183- }
184- // lane-h264reallib: `unwrap_or_default()` rather than a bare `unwrap()`.
185- // A host with no HOME -- a fleet runner -- panicked here before reaching
186- // the `read_dir` guard one line down, which already reports an absent
187- // directory correctly. With an empty HOME the guard simply reports
188- // `skip: no ./Videos/OBS`, so the test degrades to the silent skip its
189- // own guard was written for instead of a red that says nothing about AAC.
190- let dir = PathBuf::from(std::env::var("HOME").unwrap_or_default()).join("Videos/OBS");
191- let Ok(rd) = std::fs::read_dir(&dir) else {
192- eprintln!("skip: no {}", dir.display());
193- return;
194- };
195- let mut files: Vec<PathBuf> = rd
196- .filter_map(|e| e.ok())
197- .map(|e| e.path())
198- .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("mp4"))
199- .collect();
200- files.sort();
201- let _knob = ec_aac::knobs::set_tool_sideinfo_debug(Some(true));
202- for path in files {
203- eprintln!("== {}", path.display());
204- let before = ec_aac::tool_sideinfo_log().len();
205- let Some(ours) = our_decode(&path) else {
206- eprintln!(" our_decode: None");
207- continue;
208- };
209- let theirs = ffmpeg_decode(&path, ours.len());
210- for (ch, (o, t)) in ours.iter().zip(theirs.iter()).enumerate() {
211- let (lag, corr) = best_lag_correlation(o, t);
212- // Also the direct, un-windowed corr from t=0 (no lag search) --
213- // this is what the consumer sweep that found this regression
214- // measured, and can disagree with the windowed/lag-searched
215- // number above if only part of the file is corrupted.
216- let corr0 = correlation(o, t);
217- let non_finite = o.iter().filter(|v| !v.is_finite()).count();
218- eprintln!(
219- " ch{ch}: corr={corr:.4} corr@lag0={corr0:.4} lag={lag} rms_ours={:.5} rms_ffmpeg={:.5} non_finite={non_finite}",
220- rms(o),
221- rms(t)
222- );
223- }
224- let all_rows = ec_aac::tool_sideinfo_log();
225- let rows = &all_rows[before..];
226- let (mut pns, mut is_, mut ms, mut tns, mut cpe) = (0usize, 0usize, 0usize, 0usize, 0usize);
227- for r in rows {
228- if r.pns_bands > 0 {
229- pns += 1;
230- }
231- if r.is_bands > 0 {
232- is_ += 1;
233- }
234- if r.ms_bands > 0 {
235- ms += 1;
236- }
237- if r.tns_present {
238- tns += 1;
239- }
240- if r.is_cpe {
241- cpe += 1;
242- }
243- }
244- eprintln!(
245- " tools over {} AUs: cpe={cpe} pns_aus={pns} is_aus={is_} ms_aus={ms} tns_aus={tns}",
246- rows.len()
247- );
248- }
249-}
crates/ec-aac/tests/oracle.rsmodified+13 -403
@@ -1,42 +1,11 @@
1-//! Decoder and encoder against ffmpeg, on the generated fixtures and on the
2-//! real library. Every test that needs a fixture or ffmpeg skips loudly when it
3-//! is absent rather than passing quietly.
41
5-mod common;
6-
7-use common::{fixtures, have_ffmpeg};
82 use std::path::{Path, PathBuf};
9-use std::process::Command;
103
114 use ec_aac::{AacDecoder, AacEncoder, AacEncoderConfig};
125
13-/// Fixture-presence probe for the committed `fixtures/audio` media this file
14-/// decodes. Returns whether the fixture is present, but never silently: under
15-/// `EC_REQUIRE_FIXTURES=1` an absent fixture is a hard failure naming the path
16-/// and the script that regenerates it, so a host whose fixture library drifted
17-/// reports RED instead of a green SKIP (class: gate-skips-on-its-own-failure;
18-/// model `have_ffmpeg` in crates/ec-av1/src/stream.rs, which was silently
19-/// short-circuited because the probe ran first in a compound `if`).
20-///
21-/// Order is load-bearing: probe, assert, return. Never merge the probe into
22-/// the same `if` as the escape.
23-fn require_fixture(path: &Path, generator: &str) -> bool {
24- let present = path.exists();
25- assert!(
26- present || std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
27- "EC_REQUIRE_FIXTURES=1 but fixture {} is absent -- regenerate with: {}",
28- path.display(),
29- generator
30- );
31- if !present {
32- eprintln!("SKIP: fixture {} absent", path.display());
33- }
34- present
35-}
36-
376 /// ffmpeg's decode of a file, as planar-by-channel `f32`.
387 fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<Vec<f32>> {
39- let out = Command::new("ffmpeg")
8+ let out = ec_testkit::ffmpeg()
409 .args(["-v", "error", "-i"])
4110 .arg(path)
4211 .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])
@@ -128,11 +97,6 @@ fn compare(path: &Path) -> Vec<f64> {
12897
12998 #[test]
13099 fn adts_fixtures_match_ffmpeg_per_channel() {
131- if !have_ffmpeg() {
132- eprintln!("SKIP: ffmpeg not on PATH");
133- return;
134- }
135- let dir = fixtures().join("audio");
136100 let mut checked = 0;
137101 for name in [
138102 "aac-adts-mono-44100.aac",
@@ -142,10 +106,7 @@ fn adts_fixtures_match_ffmpeg_per_channel() {
142106 "aac-adts-5.1-44100.aac",
143107 "aac-adts-5.1-48000.aac",
144108 ] {
145- let path = dir.join(name);
146- if !require_fixture(&path, "scripts/gen-fixtures.sh") {
147- continue;
148- }
109+ let path = ec_testkit::fixture(&format!("audio/{name}"));
149110 let corr = compare(&path);
150111 println!("{name}: {corr:?}");
151112 for (ch, c) in corr.iter().enumerate() {
@@ -164,11 +125,6 @@ fn adts_fixtures_match_ffmpeg_per_channel() {
164125
165126 #[test]
166127 fn mp4_fixtures_match_ffmpeg_per_channel() {
167- if !have_ffmpeg() {
168- eprintln!("SKIP: ffmpeg not on PATH");
169- return;
170- }
171- let dir = fixtures().join("audio");
172128 let tmp = std::env::temp_dir().join("ec-aac-mp4-oracle");
173129 std::fs::create_dir_all(&tmp).expect("temp dir");
174130 let mut checked = 0;
@@ -177,14 +133,11 @@ fn mp4_fixtures_match_ffmpeg_per_channel() {
177133 "aac-mp4-stereo-48000.mp4",
178134 "aac-mp4-5.1-48000.mp4",
179135 ] {
180- let path = dir.join(name);
181- if !require_fixture(&path, "scripts/gen-fixtures.sh") {
182- continue;
183- }
136+ let path = ec_testkit::fixture(&format!("audio/{name}"));
184137 // The mp4 side of the family is another slice; the elementary stream
185138 // comes out with a stream copy so this test stays about AAC.
186139 let adts = tmp.join(format!("{name}.aac"));
187- let out = Command::new("ffmpeg")
140+ let out = ec_testkit::ffmpeg()
188141 .args(["-v", "error", "-y", "-i"])
189142 .arg(&path)
190143 .args(["-c:a", "copy", "-f", "adts"])
@@ -211,22 +164,14 @@ fn mp4_fixtures_match_ffmpeg_per_channel() {
211164 /// its bands before M/S and intensity stereo combine them.
212165 #[test]
213166 fn aac_coding_tools_match_ffmpeg_in_isolation() {
214- if !have_ffmpeg() {
215- eprintln!("SKIP: ffmpeg not on PATH");
216- return;
217- }
218- let dir = fixtures().join("audio");
219167 let tmp = std::env::temp_dir().join("ec-aac-tools-oracle");
220168 std::fs::create_dir_all(&tmp).expect("temp dir");
221169 let mut checked = 0;
222170 for tool in ["pns", "is", "ms", "tns", "all"] {
223171 let name = format!("aac-tool-{tool}-mp4-stereo-48000.m4a");
224- let path = dir.join(&name);
225- if !require_fixture(&path, "scripts/gen-fixtures.sh") {
226- continue;
227- }
172+ let path = ec_testkit::fixture(&format!("audio/{name}"));
228173 let adts = tmp.join(format!("{name}.aac"));
229- let out = Command::new("ffmpeg")
174+ let out = ec_testkit::ffmpeg()
230175 .args(["-v", "error", "-y", "-i"])
231176 .arg(&path)
232177 .args(["-c:a", "copy", "-f", "adts"])
@@ -258,17 +203,13 @@ fn aac_coding_tools_match_ffmpeg_in_isolation() {
258203 /// wrong element order shows up as the wrong tone on the wrong channel.
259204 #[test]
260205 fn five_one_comes_out_in_film_order() {
261- if !have_ffmpeg() {
262- eprintln!("SKIP: ffmpeg not on PATH");
263- return;
264- }
265206 let tmp = std::env::temp_dir().join("ec-aac-order");
266207 std::fs::create_dir_all(&tmp).expect("temp dir");
267208 let src = tmp.join("order.aac");
268209 // The LFE tone stays low: the reference encoder band-limits that channel,
269210 // and a 1.5 kHz tone would simply not survive the trip.
270211 let tones = [300.0, 700.0, 1100.0, 60.0, 1900.0, 2300.0];
271- let mut cmd = Command::new("ffmpeg");
212+ let mut cmd = ec_testkit::ffmpeg();
272213 cmd.args(["-v", "error", "-y"]);
273214 for f in tones {
274215 cmd.args([
@@ -424,19 +365,11 @@ fn best_correlation(source: &[f32], decoded: &[f32]) -> f64 {
424365 /// lossless fixtures at the same bitrates.
425366 #[test]
426367 fn encoder_beats_the_incumbent_bar() {
427- if !have_ffmpeg() {
428- eprintln!("SKIP: ffmpeg not on PATH");
429- return;
430- }
431- let dir = fixtures().join("audio");
432368 let tmp = std::env::temp_dir().join("ec-aac-bar");
433369 std::fs::create_dir_all(&tmp).expect("temp dir");
434370 let mut checked = 0;
435371 for (name, channels, kbps, bar) in INCUMBENT_BAR {
436- let src = dir.join(format!("flac-{name}-48000.flac"));
437- if !require_fixture(&src, "scripts/gen-fixtures.sh") {
438- continue;
439- }
372+ let src = ec_testkit::fixture(&format!("audio/flac-{name}-48000.flac"));
440373 let source = ffmpeg_decode(&src, *channels);
441374 let mut interleaved = Vec::with_capacity(source[0].len() * channels);
442375 for i in 0..source[0].len() {
@@ -493,20 +426,12 @@ const LAYOUT_BAR: &[(&str, usize, u32, f64, &str)] = &[
493426 /// ADTS rate within 5% of the target.
494427 #[test]
495428 fn encoder_meets_every_layout_bar() {
496- if !have_ffmpeg() {
497- eprintln!("SKIP: ffmpeg not on PATH");
498- return;
499- }
500- let dir = fixtures().join("audio");
501429 let tmp = std::env::temp_dir().join("ec-aac-layout-bar");
502430 std::fs::create_dir_all(&tmp).expect("temp dir");
503431 let mut checked = 0;
504432 let mut failed = Vec::new();
505433 for (name, channels, kbps, bar, incumbent) in LAYOUT_BAR {
506- let src = dir.join(format!("flac-{name}-48000.flac"));
507- if !require_fixture(&src, "scripts/gen-aac-layouts.sh OUTDIR (3.0, 4.0, 5.0, 7.1)") {
508- continue;
509- }
434+ let src = ec_testkit::fixture(&format!("audio/flac-{name}-48000.flac"));
510435 let source = ffmpeg_decode(&src, *channels);
511436 let mut interleaved = Vec::with_capacity(source[0].len() * channels);
512437 for i in 0..source[0].len() {
@@ -622,7 +547,7 @@ fn noisy_clip(name: &str, dir: &Path) -> PathBuf {
622547 .iter()
623548 .find(|(n, _, _)| *n == name)
624549 .expect("a NOISY_CLIPS entry");
625- let mut cmd = Command::new("ffmpeg");
550+ let mut cmd = ec_testkit::ffmpeg();
626551 cmd.args(["-v", "error", "-y"]);
627552 for input in *inputs {
628553 cmd.args(["-f", "lavfi", "-i", input]);
@@ -642,10 +567,6 @@ fn noisy_clip(name: &str, dir: &Path) -> PathBuf {
642567 /// correlation against the incumbent's bar, and the ADTS rate within 5% of the target.
643568 #[test]
644569 fn encoder_meets_noisy_bar() {
645- if !have_ffmpeg() {
646- eprintln!("SKIP: ffmpeg not on PATH");
647- return;
648- }
649570 let tmp = std::env::temp_dir().join("ec-aac-noisy-bar");
650571 std::fs::create_dir_all(&tmp).expect("temp dir");
651572 let mut failed = Vec::new();
@@ -706,10 +627,6 @@ fn tone_pcm(rate: u32, channels: usize, secs: f64) -> Vec<f32> {
706627
707628 #[test]
708629 fn encoder_output_decodes_in_ffmpeg_without_warnings() {
709- if !have_ffmpeg() {
710- eprintln!("SKIP: ffmpeg not on PATH");
711- return;
712- }
713630 let tmp = std::env::temp_dir().join("ec-aac-enc");
714631 std::fs::create_dir_all(&tmp).expect("temp dir");
715632 for (channels, kbps) in [(1u16, 96u32), (2, 128), (2, 192), (6, 384)] {
@@ -719,7 +636,7 @@ fn encoder_output_decodes_in_ffmpeg_without_warnings() {
719636 assert!(!adts.is_empty(), "{channels}ch encode produced nothing");
720637 let path = tmp.join(format!("enc-{channels}ch-{kbps}k.aac"));
721638 std::fs::write(&path, &adts).expect("write");
722- let out = Command::new("ffmpeg")
639+ let out = ec_testkit::ffmpeg()
723640 .args(["-v", "warning", "-i"])
724641 .arg(&path)
725642 .args(["-f", "null", "-"])
@@ -816,10 +733,6 @@ fn band_tables_span_the_window() {
816733 /// means in practice.
817734 #[test]
818735 fn asc_matches_the_one_ffmpeg_writes() {
819- if !have_ffmpeg() {
820- eprintln!("SKIP: ffmpeg not on PATH");
821- return;
822- }
823736 let tmp = std::env::temp_dir().join("ec-aac-esds");
824737 std::fs::create_dir_all(&tmp).expect("temp dir");
825738 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() {
828741 let src = tmp.join(format!("asc-{channels}-{rate}.aac"));
829742 std::fs::write(&src, &adts).expect("write");
830743 let mp4 = tmp.join(format!("asc-{channels}-{rate}.mp4"));
831- let out = Command::new("ffmpeg")
744+ let out = ec_testkit::ffmpeg()
832745 .args(["-v", "error", "-y", "-i"])
833746 .arg(&src)
834747 .args(["-c:a", "copy"])
@@ -903,146 +816,10 @@ fn esds_asc(mp4: &[u8]) -> Option<Vec<u8>> {
903816 None
904817 }
905818
906-/// AAC tracks from the machine's own library, not just generated fixtures: the
907-/// elementary stream is copied out to ADTS and decoded both ways.
908-// lane-h264reallib: same shape as the ec-h264 `real_library_streams_match_ffmpeg`
909-// fix, same reason. The manifest is generated by `scripts/scan-real-library.sh`
910-// from `~/Videos ~/Downloads ~/Music` and is gitignored because it is
911-// machine-local. The guard below makes a host with NO manifest print green
912-// (nothing was checked), and a host that ran the scan but has since moved or
913-// deleted files falls through to `checked >= 3` and goes red for a reason that
914-// has nothing to do with the decoder. An ignore is visible in `--list` and
915-// cannot go green silently, which an env gate would.
916-// Run on the workstation: cargo test -p ec-aac --test oracle real_library_tracks_match_ffmpeg -- --ignored
917-#[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."]
918-#[test]
919-fn real_library_tracks_match_ffmpeg() {
920- if !have_ffmpeg() {
921- eprintln!("SKIP: ffmpeg not on PATH");
922- return;
923- }
924- let manifest = fixtures().join("real-library-manifest.tsv");
925- let Ok(text) = std::fs::read_to_string(&manifest) else {
926- eprintln!("SKIP: no real-library manifest; run scripts/scan-real-library.sh");
927- return;
928- };
929- let tmp = std::env::temp_dir().join("ec-aac-real");
930- std::fs::create_dir_all(&tmp).expect("temp dir");
931- let mut stereo = 0;
932- let mut wide = 0;
933- let mut checked = 0;
934- for line in text.lines().skip(1) {
935- if stereo >= 3 && wide >= 2 {
936- break;
937- }
938- let path = line.split('\t').next().unwrap_or_default();
939- if path.is_empty() || !line.to_lowercase().contains("aac") {
940- continue;
941- }
942- let file = Path::new(path);
943- if !file.exists() {
944- continue;
945- }
946- let Some((index, channels, profile)) = aac_stream(file) else {
947- continue;
948- };
949- // HE-AAC is reported, not decoded: see `sbr_is_reported_not_silently_upsampled`.
950- if profile.contains("HE-AAC") {
951- continue;
952- }
953- if channels <= 2 {
954- if stereo >= 3 {
955- continue;
956- }
957- stereo += 1;
958- } else {
959- if wide >= 2 {
960- continue;
961- }
962- wide += 1;
963- }
964- let adts = tmp.join(format!("real-{checked}.aac"));
965- let out = Command::new("ffmpeg")
966- .args(["-v", "error", "-y", "-t", "20", "-i"])
967- .arg(file)
968- .args(["-map", &format!("0:{index}"), "-c:a", "copy", "-f", "adts"])
969- .arg(&adts)
970- .output()
971- .expect("ffmpeg runs");
972- if !out.status.success() {
973- eprintln!("SKIP {path}: stream copy failed");
974- continue;
975- }
976- let corr = compare(&adts);
977- let worst = corr.iter().copied().fold(f64::MAX, f64::min);
978- println!(
979- "real {channels}ch {profile} worst {worst:.6} -- {}",
980- file.file_name().unwrap_or_default().to_string_lossy()
981- );
982- for (ch, c) in corr.iter().enumerate() {
983- assert!(
984- *c >= 0.999,
985- "channel {ch} correlation {c:.6} < 0.999 for {path}"
986- );
987- }
988- checked += 1;
989- }
990- assert!(
991- checked >= 3,
992- "wanted at least three library tracks, swept {checked}"
993- );
994- assert!(wide >= 1, "no multichannel AAC track was swept");
995-}
996-
997-/// The first AAC audio stream of a file: `(stream index, channels, profile)`.
998-fn aac_stream(path: &Path) -> Option<(usize, usize, String)> {
999- let out = Command::new("ffprobe")
1000- .args([
1001- "-v",
1002- "error",
1003- "-select_streams",
1004- "a",
1005- "-show_entries",
1006- "stream=index,codec_name,channels,profile",
1007- "-of",
1008- "default=noprint_wrappers=1",
1009- ])
1010- .arg(path)
1011- .output()
1012- .ok()?;
1013- let text = String::from_utf8_lossy(&out.stdout);
1014- let (mut index, mut channels, mut codec, mut profile) =
1015- (None, None, String::new(), String::new());
1016- for line in text.lines() {
1017- let (key, value) = line.split_once('=')?;
1018- match key {
1019- "index" => {
1020- if codec == "aac" {
1021- return Some((index?, channels?, profile));
1022- }
1023- index = value.parse().ok();
1024- codec.clear();
1025- profile.clear();
1026- }
1027- "codec_name" => codec = value.to_string(),
1028- "channels" => channels = value.parse().ok(),
1029- "profile" => profile = value.to_string(),
1030- _ => {}
1031- }
1032- }
1033- if codec == "aac" {
1034- return Some((index?, channels?, profile));
1035- }
1036- None
1037-}
1038-
1039819 /// Decode speed on 5.1, the shape a film soundtrack has.
1040820 #[test]
1041821 fn five_one_decodes_faster_than_realtime() {
1042- let path = fixtures().join("audio/aac-adts-5.1-48000.aac");
1043- if !require_fixture(&path, "scripts/gen-fixtures.sh") {
1044- return;
1045- }
822+ let path = ec_testkit::fixture("audio/aac-adts-5.1-48000.aac");
1046823 let data = std::fs::read(&path).expect("fixture readable");
1047824 let rounds = 8;
1048825 let start = std::time::Instant::now();
@@ -1078,170 +855,3 @@ fn five_one_decodes_faster_than_realtime() {
1078855 );
1079856 }
1080857 }
1081-
1082-/// The one HE-AAC track in this machine's library, decoded to its AAC-LC core.
1083-/// The claim under test is the honest one: the core comes out, at the core
1084-/// rate, matching what a reference decoder makes of the same core band.
1085-#[test]
1086-fn he_aac_library_track_decodes_to_its_core() {
1087- if !have_ffmpeg() {
1088- eprintln!("SKIP: ffmpeg not on PATH");
1089- return;
1090- }
1091- let manifest = fixtures().join("real-library-manifest.tsv");
1092- let Ok(text) = std::fs::read_to_string(&manifest) else {
1093- eprintln!("SKIP: no real-library manifest");
1094- return;
1095- };
1096- let tmp = std::env::temp_dir().join("ec-aac-he");
1097- std::fs::create_dir_all(&tmp).expect("temp dir");
1098- for line in text.lines().skip(1) {
1099- let path = line.split('\t').next().unwrap_or_default();
1100- let file = Path::new(path);
1101- if path.is_empty() || !file.exists() {
1102- continue;
1103- }
1104- let Some((index, _, profile)) = aac_stream_matching(file, "HE-AAC") else {
1105- continue;
1106- };
1107- let _ = profile;
1108- let adts = tmp.join("he.aac");
1109- let out = Command::new("ffmpeg")
1110- .args(["-v", "error", "-y", "-t", "10", "-i"])
1111- .arg(file)
1112- .args(["-map", &format!("0:{index}"), "-c:a", "copy", "-f", "adts"])
1113- .arg(&adts)
1114- .output()
1115- .expect("ffmpeg runs");
1116- if !out.status.success() {
1117- continue;
1118- }
1119- let (ours, rate) = our_decode(&adts);
1120- assert!(!ours.is_empty(), "the HE-AAC core decoded to nothing");
1121- // The reference decode carries SBR, so it runs at twice this rate;
1122- // resampling it down to the core rate low-passes exactly the band the
1123- // core carries, which is the part we are claiming to reproduce.
1124- let core = tmp.join("he-core.f32");
1125- let out = Command::new("ffmpeg")
1126- .args(["-v", "error", "-y", "-i"])
1127- .arg(&adts)
1128- .args(["-ar", &rate.to_string(), "-f", "f32le"])
1129- .arg(&core)
1130- .output()
1131- .expect("ffmpeg runs");
1132- assert!(
1133- out.status.success(),
1134- "reference decode of the HE-AAC track failed"
1135- );
1136- let theirs = deinterleave(
1137- &bytes_to_f32(&std::fs::read(&core).expect("read")),
1138- ours.len(),
1139- );
1140- // Sample-by-sample comparison would need the reference resampler's own
1141- // delay; the claim here is about *content*, so it is checked on the
1142- // long-term band energies, which no delay moves.
1143- let corr: Vec<f64> = ours
1144- .iter()
1145- .zip(&theirs)
1146- .map(|(a, b)| pearson(&band_energies(a, rate), &band_energies(b, rate)))
1147- .collect();
1148- let worst = corr.iter().copied().fold(f64::MAX, f64::min);
1149- println!("HE-AAC core at {rate} Hz: band-energy match, worst channel {worst:.4} {corr:?}");
1150- assert!(
1151- worst >= 0.95,
1152- "the AAC-LC core of an HE-AAC track should carry the reference's \
1153- core band; worst channel {worst:.4}"
1154- );
1155- return;
1156- }
1157- eprintln!("SKIP: no HE-AAC track in the library manifest");
1158-}
1159-
1160-/// Pearson correlation with no minimum length: for short feature vectors.
1161-fn pearson(a: &[f32], b: &[f32]) -> f64 {
1162- let n = a.len().min(b.len());
1163- let ma = a[..n].iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
1164- let mb = b[..n].iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
1165- let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
1166- for i in 0..n {
1167- let (x, y) = (f64::from(a[i]) - ma, f64::from(b[i]) - mb);
1168- num += x * y;
1169- da += x * x;
1170- db += y * y;
1171- }
1172- if da == 0.0 || db == 0.0 {
1173- return 1.0;
1174- }
1175- num / (da * db).sqrt()
1176-}
1177-
1178-/// Long-term energy in 32 logarithmic bands: a spectral fingerprint that a
1179-/// resampler's delay cannot shift.
1180-fn band_energies(samples: &[f32], rate: u32) -> Vec<f32> {
1181- let bands = 32usize;
1182- let mut out = vec![0.0f64; bands];
1183- let n = 1024usize;
1184- let mut blocks = 0usize;
1185- for chunk in samples.chunks_exact(n).take(400) {
1186- blocks += 1;
1187- for (b, slot) in out.iter_mut().enumerate() {
1188- // Geometric spacing from 100 Hz to the Nyquist limit.
1189- let lo = 100.0 * (f64::from(rate) / 2.0 / 100.0).powf(b as f64 / bands as f64);
1190- let hi = 100.0 * (f64::from(rate) / 2.0 / 100.0).powf((b + 1) as f64 / bands as f64);
1191- let (mut re, mut im) = (0.0f64, 0.0f64);
1192- let f = (lo * hi).sqrt();
1193- let w = 2.0 * std::f64::consts::PI * f / f64::from(rate);
1194- for (i, &v) in chunk.iter().enumerate() {
1195- re += f64::from(v) * (w * i as f64).cos();
1196- im += f64::from(v) * (w * i as f64).sin();
1197- }
1198- *slot += (re * re + im * im).sqrt();
1199- }
1200- }
1201- out.iter()
1202- .map(|v| ((v / blocks.max(1) as f64) + 1e-9).ln() as f32)
1203- .collect()
1204-}
1205-
1206-fn aac_stream_matching(path: &Path, want: &str) -> Option<(usize, usize, String)> {
1207- let out = Command::new("ffprobe")
1208- .args([
1209- "-v",
1210- "error",
1211- "-select_streams",
1212- "a",
1213- "-show_entries",
1214- "stream=index,codec_name,channels,profile",
1215- "-of",
1216- "default=noprint_wrappers=1",
1217- ])
1218- .arg(path)
1219- .output()
1220- .ok()?;
1221- let text = String::from_utf8_lossy(&out.stdout);
1222- let mut index = None;
1223- let mut channels = None;
1224- let mut codec = String::new();
1225- let mut profile = String::new();
1226- for line in text.lines() {
1227- let (key, value) = line.split_once('=')?;
1228- match key {
1229- "index" => {
1230- if codec == "aac" && profile.contains(want) {
1231- return Some((index?, channels?, profile));
1232- }
1233- index = value.parse().ok();
1234- codec.clear();
1235- profile.clear();
1236- }
1237- "codec_name" => codec = value.to_string(),
1238- "channels" => channels = value.parse().ok(),
1239- "profile" => profile = value.to_string(),
1240- _ => {}
1241- }
1242- }
1243- if codec == "aac" && profile.contains(want) {
1244- return Some((index?, channels?, profile));
1245- }
1246- None
1247-}
crates/ec-aac/tests/sbr_real_library/chunk_a.rsmodified+128 -345
@@ -25,15 +25,8 @@ use super::*;
2525 #[test]
2626 pub(super) fn core_only_matches_reference() {
2727 let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
28- if !have_ffmpeg() {
29- eprintln!("SKIP: ffmpeg not on PATH");
30- return;
31- }
3228 for c in &candidates() {
33- let Some((ours, core_rate)) = our_decode_core_only(&c.path, c.aac_stream) else {
34- eprintln!("SKIP {}: could not core-decode", c.path.display());
35- continue;
36- };
29+ let (ours, core_rate) = our_decode_core_only(&c.path, c.aac_stream).expect("core decode");
3730 let theirs = ffmpeg_decode_at_rate(&c.path, c.ffmpeg_stream, ours.len(), core_rate);
3831 println!(
3932 "{} core-only ({} ch, {} Hz):",
@@ -101,10 +94,6 @@ pub(super) fn dump_sideinfo_kx() {
10194 #[test]
10295 pub(super) fn wide_lag_search_full_chain() {
10396 let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
104- if !have_ffmpeg() {
105- eprintln!("SKIP: ffmpeg not on PATH");
106- return;
107- }
10897 for c in &candidates() {
10998 let Some((ours, sbr, rate)) = our_decode(&c.path, c.aac_stream) else {
11099 continue;
@@ -227,42 +216,12 @@ pub(super) fn full_chain_low_band_matches_own_core() {
227216 }
228217 }
229218
230-/// Round-52: a controlled fixture matrix -- unlike reeln/FMJ (one real
231-/// file each, whose sample rate, bitrate and content all differ at once),
232-/// every row here decodes the SAME synthesized source (three summed sine
233-/// sweeps 100 Hz-18 kHz + seeded pink noise, per-channel phase offset),
234-/// varying only sample rate (44100/48000) and bitrate (32k/48k/64k/96k,
235-/// which sweeps the SBR crossover `kx`/`k2`), so a break tied to a rate
236-/// FAMILY or to `kx` GEOMETRY shows as a pattern across the table instead
237-/// of being confounded with one file's own content. `aac_low` control rows
238-/// (no SBR at all) prove the harness itself -- container extraction,
239-/// decode, correlation -- is sound before the HE-AAC rows next to them are
240-/// trusted; those are the only asserted numbers here, everything else is
241-/// instrumentation for the ledger, not a regression gate yet.
242-///
243-/// Env-gated on `EC_AAC_HEAAC_FIXTURES` (defaults to the same
244-/// `<repo>/.cache/heaac-fixtures` `scripts/aac-tables/make-heaac-fixtures.sh`
245-/// writes to) -- skips loudly, generates nothing itself, when that
246-/// directory is absent.
247219 #[test]
248220 pub(super) fn synthetic_heaac_matrix() {
249221 let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
250- if !have_ffmpeg() {
251- eprintln!("SKIP: ffmpeg not on PATH");
252- return;
253- }
254- let dir = std::env::var("EC_AAC_HEAAC_FIXTURES")
255- .unwrap_or_else(|_| format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR")));
256- let dir = PathBuf::from(dir);
257- if !require_fixture(&dir, "scripts/aac-tables/make-heaac-fixtures.sh") {
258- return;
259- }
260222 let _knob = ec_aac::knobs::set_sbr_sideinfo_debug(Some(true));
261223 println!(
262- "{:>5} {:>6} {:>4} {:>4} {:>4} {:>8} {:>8} {:>8} {:>6} {:>11} {:>8} {:>10} {:>8} {:>9} {:>9}",
263- "rate",
264- "kbps",
265- "prof",
224+ "{:>4} {:>4} {:>8} {:>8} {:>8} {:>6} {:>11} {:>8} {:>10} {:>8} {:>9} {:>9}",
266225 "kx",
267226 "k2",
268227 "full",
@@ -281,295 +240,137 @@ pub(super) fn synthetic_heaac_matrix() {
281240 // samples at the doubled/full output rate) both land well inside it,
282241 // not right at the edge the way the plain (LAG_MAX=4000) search did.
283242 const WIDE_LAG_MAX: i64 = 20_000;
284- // Floor: the matrix is 2 rates x 4 bitrates x 2 profiles. Without a count
285- // the whole test is green having probed nothing, which is the same
286- // false-green this file's `require_fixture` exists to kill.
287- let mut probed = 0usize;
288- for rate in [48_000u32, 44_100] {
289- for br in ["32k", "48k", "64k", "96k"] {
290- // LC first: its winning lag is the pure container/decoder
291- // priming delay with no SBR chain involved, and is reused below
292- // as the anchor for the HE row's own delay-candidate probe.
293- let mut lc_lag: Option<i64> = None;
294- for (profile, prefix) in [("LC", "lc"), ("HE", "heaac")] {
295- let path = dir.join(format!("{prefix}_{rate}_{br}.m4a"));
296- if !require_fixture(&path, "scripts/aac-tables/make-heaac-fixtures.sh") {
297- continue;
298- }
299- probed += 1;
300- let before = ec_aac::sbr_sideinfo_log().len();
301- let Some((ours, _sbr, our_rate)) = our_decode(&path, 0) else {
302- eprintln!("SKIP {}: could not decode", path.display());
303- continue;
304- };
305- let rows = ec_aac::sbr_sideinfo_log();
306- let (kx, k2) = rows[before..]
307- .iter()
308- .find(|r| r.ch == 0)
309- .map(|r| (r.kx, r.k2))
310- .unwrap_or((-1, -1));
311- let theirs = ffmpeg_decode(&path, 0, ours.len());
312- let o = &ours[0];
313- let t = &theirs[0];
314- const TOPK: usize = 5;
315- let (mut lag, mut full, edge) = robust_lag_topk(o, t, WIDE_LAG_MAX, our_rate, TOPK);
316- assert!(
317- !edge,
318- "{}: {profile} row's refined winning lag {lag} sits at the \
319- +/-{WIDE_LAG_MAX} search's own edge",
320- path.display()
321- );
322- if profile == "LC" {
323- lc_lag = Some(lag);
324- }
325- // HE rows: a per-channel free lag search on periodic/tonal
326- // content is unreliable (coupled_cpe_channel_swap_probe
327- // proved this file's ref L vs ref R itself mis-searches --
328- // lag=-24 corr=0.213 vs the fixed lag=0 corr=0.873 -- and
329- // the same coarse search can land two channels of the SAME
330- // stream on DIFFERENT, individually-wrong lags, faking a
331- // channel swap that a fixed-lag check rules out). Derive
332- // ONE lag per stream from the summed (mono) signal instead,
333- // and reuse it for both channels -- more robust than
334- // trusting a single, possibly-periodic channel's own search
335- // -- via the same top-K/refine-on-first-10s robust method.
336- if profile == "HE" && ours.len() >= 2 && theirs.len() >= 2 {
337- let mono_o: Vec<f32> =
338- ours[0].iter().zip(&ours[1]).map(|(a, b)| a + b).collect();
339- let mono_t: Vec<f32> = theirs[0]
340- .iter()
341- .zip(&theirs[1])
342- .map(|(a, b)| a + b)
343- .collect();
344- let (mono_lag, _, mono_edge) =
345- robust_lag_topk(&mono_o, &mono_t, WIDE_LAG_MAX, our_rate, TOPK);
346- assert!(
347- !mono_edge,
348- "{}: HE row's mono-derived refined lag {mono_lag} sits at the \
349- +/-{WIDE_LAG_MAX} search's own edge",
350- path.display()
351- );
352- lag = mono_lag;
353- full = correlation_at_lag(o, t, lag);
354- }
355- // Crossover in Hz from the actual parsed kx (band width
356- // rate/128, same domain `sbr_chain.rs`'s own doc comment
357- // gives `kx`/`k2` in) when SBR engaged; a fixed quarter-Nyquist
358- // split for the LC controls, which carry no kx at all.
359- let crossover_hz = if kx > 0 {
360- f64::from(our_rate) * (kx as f64) / 128.0
361- } else {
362- f64::from(our_rate) * 0.25
363- };
364- // Same single robust `lag` the full/above bands use, not an
365- // independent search: a narrowband low-passed signal's
366- // correlation surface is broad and flat across nearby lags,
367- // which used to let an independent search here silently
368- // report a different (and unvalidated) alignment than the
369- // one everything else in the row is anchored at.
370- let below = correlation_at_lag(
371- &lowpass(o, our_rate, crossover_hz),
372- &lowpass(t, our_rate, crossover_hz),
373- lag,
374- );
375- // `above` re-slices at the FULL-band winning `lag` before
376- // splitting, same convention `sbr_real_library_matches_reference`
377- // uses -- round-52's first cut of this row measured `o[..n]`
378- // against `t[..n]` with no lag offset at all, which is only
379- // valid by accident at lag 0 and was silently wrong for
380- // every other winning lag in that table.
381- let (oa, ob) = if lag >= 0 {
382- (0usize, lag as usize)
383- } else {
384- ((-lag) as usize, 0usize)
385- };
386- let n = WINDOW
387- .min(o.len().saturating_sub(oa))
388- .min(t.len().saturating_sub(ob));
389- let above = if n >= 1024 {
390- correlation(
391- &highpass(&o[oa..oa + n], our_rate, crossover_hz),
392- &highpass(&t[ob..ob + n], our_rate, crossover_hz),
243+ for path in fate_aac() {
244+ let before = ec_aac::sbr_sideinfo_log().len();
245+ let (ours, _sbr, our_rate) = our_decode(&path, 0).expect("decodes");
246+ let rows = ec_aac::sbr_sideinfo_log();
247+ let (kx, k2) = rows[before..]
248+ .iter()
249+ .find(|r| r.ch == 0)
250+ .map(|r| (r.kx, r.k2))
251+ .unwrap_or((-1, -1));
252+ let theirs = ffmpeg_decode(&path, 0, ours.len());
253+ let o = &ours[0];
254+ let t = &theirs[0];
255+ const TOPK: usize = 5;
256+ let (mut lag, mut full, edge) = robust_lag_topk(o, t, WIDE_LAG_MAX, our_rate, TOPK);
257+ assert!(
258+ !edge,
259+ "{}: HE row's refined winning lag {lag} sits at the \
260+ +/-{WIDE_LAG_MAX} search's own edge",
261+ path.display()
262+ );
263+ if ours.len() >= 2 && theirs.len() >= 2 {
264+ let mono_o: Vec<f32> =
265+ ours[0].iter().zip(&ours[1]).map(|(a, b)| a + b).collect();
266+ let mono_t: Vec<f32> = theirs[0]
267+ .iter()
268+ .zip(&theirs[1])
269+ .map(|(a, b)| a + b)
270+ .collect();
271+ let (mono_lag, _, mono_edge) =
272+ robust_lag_topk(&mono_o, &mono_t, WIDE_LAG_MAX, our_rate, TOPK);
273+ assert!(
274+ !mono_edge,
275+ "{}: HE row's mono-derived refined lag {mono_lag} sits at the \
276+ +/-{WIDE_LAG_MAX} search's own edge",
277+ path.display()
278+ );
279+ lag = mono_lag;
280+ full = correlation_at_lag(o, t, lag);
281+ }
282+ let crossover_hz = if kx > 0 {
283+ f64::from(our_rate) * (kx as f64) / 128.0
284+ } else {
285+ f64::from(our_rate) * 0.25
286+ };
287+ let below = correlation_at_lag(
288+ &lowpass(o, our_rate, crossover_hz),
289+ &lowpass(t, our_rate, crossover_hz),
290+ lag,
291+ );
292+ let (oa, ob) = if lag >= 0 {
293+ (0usize, lag as usize)
294+ } else {
295+ ((-lag) as usize, 0usize)
296+ };
297+ let n = WINDOW
298+ .min(o.len().saturating_sub(oa))
299+ .min(t.len().saturating_sub(ob));
300+ let above = if n >= 1024 {
301+ correlation(
302+ &highpass(&o[oa..oa + n], our_rate, crossover_hz),
303+ &highpass(&t[ob..ob + n], our_rate, crossover_hz),
304+ )
305+ } else {
306+ 0.0
307+ };
308+ let decimate = |s: &[f32], from_rate: u32, to_rate: u32| -> Vec<f32> {
309+ let cutoff = f64::from(to_rate) * 0.45;
310+ lowpass(s, from_rate, cutoff)
311+ .iter()
312+ .step_by((from_rate / to_rate.max(1)).max(1) as usize)
313+ .copied()
314+ .collect()
315+ };
316+ let core_lag_max = WIDE_LAG_MAX / 2;
317+ let ours_v_core = if kx > 0 {
318+ our_decode_core_only(&path, 0).map(|(core, core_rate)| {
319+ let full_at_core_rate = decimate(o, our_rate, core_rate);
320+ best_lag_correlation_wide(&full_at_core_rate, &core[0], core_lag_max)
321+ })
322+ } else {
323+ None
324+ };
325+ let (core_v_ref, core_rate_str) = if kx > 0 {
326+ match our_decode_core_only(&path, 0) {
327+ Some((core, core_rate)) => {
328+ let ref_at_core_rate =
329+ ffmpeg_decode_at_rate(&path, 0, core.len(), core_rate);
330+ (
331+ Some(best_lag_correlation_wide(
332+ &core[0],
333+ &ref_at_core_rate[0],
334+ core_lag_max,
335+ )),
336+ core_rate.to_string(),
393337 )
394- } else {
395- 0.0
396- };
397- // Round-51's self-consistency probe (our full chain's low
398- // band vs our own core-only decode), run per-row so a
399- // rate/kx-specific self-inconsistency shows in the same
400- // table instead of needing a second pass.
401- //
402- // Fixed (this round): the original convention naively
403- // nearest-neighbor UPSAMPLED the core 2x and compared it
404- // against the full-rate signal, low-passed at
405- // `core_rate*0.4` -- that stairstep-and-lowpass round trip
406- // is lossy enough on its own to sink a genuinely-correct
407- // pair's correlation (measured flat ~-0.12 here even on
408- // rows whose `full`/`below` columns read 0.999+ against the
409- // real reference). `core_only_matches_reference` already
410- // proved a clean pattern for this exact comparison: stay in
411- // the CORE's own native rate (DECIMATE the full/reference
412- // signal down instead of upsampling the core up) and use a
413- // wide lag search there. `decimate` below is a lowpass
414- // (well under the core Nyquist) followed by a plain
415- // every-other-sample drop -- the inverse of the old
416- // `[s, s]` upsample, at the same information cost but
417- // without its stairstep artifact.
418- let decimate = |s: &[f32], from_rate: u32, to_rate: u32| -> Vec<f32> {
419- let cutoff = f64::from(to_rate) * 0.45;
420- lowpass(s, from_rate, cutoff)
421- .iter()
422- .step_by((from_rate / to_rate.max(1)).max(1) as usize)
423- .copied()
424- .collect()
425- };
426- let core_lag_max = WIDE_LAG_MAX / 2;
427- let ours_v_core = if kx > 0 {
428- our_decode_core_only(&path, 0).map(|(core, core_rate)| {
429- let full_at_core_rate = decimate(o, our_rate, core_rate);
430- best_lag_correlation_wide(&full_at_core_rate, &core[0], core_lag_max)
431- })
432- } else {
433- None
434- };
435- // Coordinator follow-up 2: splits "our core decode of THIS
436- // fixture is wrong" (core_v_ref ~0) from "the SBR chain
437- // scrambles a good core" (core_v_ref >= ~0.99 while `below`/
438- // `above` stays ~0/negative) -- OUR core-only decode, same
439- // native-core-rate convention `ours_v_core` now uses, against
440- // the REFERENCE decoder's own decode resampled to that same
441- // core rate (`ffmpeg_decode_at_rate`, the same helper
442- // `core_only_matches_reference` already trusts) -- wide lag
443- // search since this is an independent alignment from
444- // `full`/`below`'s (core-only carries no SBR delay).
445- let (core_v_ref, core_rate_str) = if kx > 0 {
446- match our_decode_core_only(&path, 0) {
447- Some((core, core_rate)) => {
448- let ref_at_core_rate =
449- ffmpeg_decode_at_rate(&path, 0, core.len(), core_rate);
450- (
451- Some(best_lag_correlation_wide(
452- &core[0],
453- &ref_at_core_rate[0],
454- core_lag_max,
455- )),
456- core_rate.to_string(),
457- )
458- }
459- None => (None, "n/a".into()),
460- }
461- } else {
462- (None, "n/a".into())
463- };
464- println!(
465- "{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}",
466- ours_v_core
467- .map(|(_, c)| format!("{c:.4}"))
468- .unwrap_or_else(|| "n/a".into()),
469- ours_v_core
470- .map(|(l, _)| l.to_string())
471- .unwrap_or_else(|| "n/a".into()),
472- core_v_ref
473- .map(|(_, c)| format!("{c:.4}"))
474- .unwrap_or_else(|| "n/a".into()),
475- core_v_ref
476- .map(|(l, _)| l.to_string())
477- .unwrap_or_else(|| "n/a".into()),
478- core_rate_str,
479- our_rate,
480- );
481- // 44.1k-family HE rows: print per-second full-band corr at
482- // the row's own robust `lag` over 30s, so a content-
483- // dependent HF-reconstruction dip (real, not an alignment
484- // artifact -- `sbr441_family_sample_drift_probe` isolated
485- // one at t=13-27s on heaac_44100_48k.m4a) is visible per
486- // second instead of averaged away by the single `full`
487- // column above.
488- if profile == "HE" && rate == 44_100 {
489- println!(" per-second full-band corr @ lag {lag} (t, corr):");
490- let step = our_rate.max(1) as usize;
491- for sec in 0..30usize {
492- let oa0 = sec * step;
493- if oa0 + step > o.len() {
494- break;
495- }
496- let ob0 = oa0 as i64 + lag;
497- if ob0 < 0 {
498- continue;
499- }
500- let ob0 = ob0 as usize;
501- if ob0 + step > t.len() {
502- continue;
503- }
504- let c = correlation(&o[oa0..oa0 + step], &t[ob0..ob0 + step]);
505- println!(" t={sec:>2}s corr={c:.6}");
506- }
507- }
508- // Coordinator follow-up (4): on the two named rows, probe
509- // candidate total HE-vs-reference delays built from LC's own
510- // priming lag plus a guessed SBR-chain contribution, to see
511- // which (if any) actually lands near 1.0 -- and whether that
512- // offset is constant across the two rows.
513- if profile == "HE"
514- && ((rate == 44_100 && br == "48k") || (rate == 48_000 && br == "64k"))
515- {
516- let lc = lc_lag.unwrap_or(-2048);
517- println!(" ch0 delay probe (LC lag {lc}):");
518- for (label, extra) in [
519- ("2990", 2990i64),
520- ("3010", 3010),
521- ("3020", 3020),
522- ("1505x2", 1505 * 2),
523- ("962x2", 962 * 2),
524- ] {
525- let candidate = (lc - 2048) + extra;
526- println!(
527- " offset={label:>6} -> lag={candidate:>6} corr={:.6}",
528- correlation_at_lag(o, t, candidate)
529- );
530- }
531- }
532- if profile == "LC" {
533- assert!(
534- full >= 0.999,
535- "{}: LC control full-band corr {full:.6} < 0.999 -- the \
536- harness itself (extraction/decode/correlation) is broken, \
537- not the SBR chain this fixture matrix is meant to isolate",
538- path.display()
539- );
540338 }
339+ None => (None, "n/a".into()),
541340 }
542- }
341+ } else {
342+ (None, "n/a".into())
343+ };
344+ println!(
345+ "{kx:>4} {k2:>4} {full:>8.4} {below:>8.4} {above:>8.4} {lag:>6} {:>11} {:>8} {:>10} {:>8} {:>9} {:>9}",
346+ ours_v_core
347+ .map(|(_, c)| format!("{c:.4}"))
348+ .unwrap_or_else(|| "n/a".into()),
349+ ours_v_core
350+ .map(|(l, _)| l.to_string())
351+ .unwrap_or_else(|| "n/a".into()),
352+ core_v_ref
353+ .map(|(_, c)| format!("{c:.4}"))
354+ .unwrap_or_else(|| "n/a".into()),
355+ core_v_ref
356+ .map(|(l, _)| l.to_string())
357+ .unwrap_or_else(|| "n/a".into()),
358+ core_rate_str,
359+ our_rate,
360+ );
543361 }
544- assert!(
545- probed >= 16,
546- "only {probed} of 16 HE-AAC matrix fixtures were present -- rerun \
547- scripts/aac-tables/make-heaac-fixtures.sh"
548- );
549362 }
550363
551364 pub(super) fn candidates() -> Vec<Candidate> {
552- let home = std::env::var("HOME").unwrap_or_default();
553- [
554- (format!("{home}/Music/reeln.mp4"), 0, 0, 5_000.0),
555- (
556- format!(
557- "{home}/Downloads/reelp/reelp.mkv"
558- ),
559- 1,
560- 3,
561- 5_000.0,
562- ),
563- ]
564- .into_iter()
565- .map(|(p, aac_stream, ffmpeg_stream, crossover_hz)| Candidate {
566- path: PathBuf::from(p),
567- aac_stream,
568- ffmpeg_stream,
569- crossover_hz,
570- })
571- .filter(|c| c.path.exists())
572- .collect()
365+ fate_aac()
366+ .into_iter()
367+ .map(|path| Candidate {
368+ path,
369+ aac_stream: 0,
370+ ffmpeg_stream: 0,
371+ crossover_hz: 5_000.0,
372+ })
373+ .collect()
573374 }
574375
575376 /// The SBR chain against the reference decoder on every real HE-AAC file this
@@ -581,29 +382,14 @@ pub(super) fn candidates() -> Vec<Candidate> {
581382 #[test]
582383 pub(super) fn sbr_real_library_matches_reference() {
583384 let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
584- if !have_ffmpeg() {
585- eprintln!("SKIP: ffmpeg not on PATH");
586- return;
587- }
588385 let list = candidates();
589- if list.is_empty() {
590- eprintln!("SKIP: no HE-AAC files found under ~/Music, ~/Downloads, ~/Videos");
591- return;
592- }
593386 let mut checked = 0;
594387 let mut worst_full = 1.0f64;
595388 let mut worst_low = 1.0f64;
596389 let mut any_at_edge: Option<String> = None;
597390 for c in &list {
598- let Some((ours, sbr, rate)) = our_decode(&c.path, c.aac_stream) else {
599- eprintln!("SKIP {}: could not decode", c.path.display());
600- continue;
601- };
391+ let (ours, sbr, rate) = our_decode(&c.path, c.aac_stream).expect("decode");
602392 if sbr != ec_aac::SbrSupport::V1 {
603- eprintln!(
604- "SKIP {}: sbr_support() is {sbr:?}, not a plain-SBR (v1) stream this chain reconstructs",
605- c.path.display()
606- );
607393 continue;
608394 }
609395 let theirs = ffmpeg_decode(&c.path, c.ffmpeg_stream, ours.len());
@@ -1163,10 +949,7 @@ pub(super) fn sbr_real_library_matches_reference() {
1163949 }
1164950 checked += 1;
1165951 }
1166- if checked == 0 {
1167- eprintln!("SKIP: no plain-SBR real files decoded");
1168- return;
1169- }
952+ assert!(checked > 0, "no plain-SBR real files decoded");
1170953 assert!(
1171954 any_at_edge.is_none(),
1172955 "lag search hit its bound: {} -- the reported correlations are noise \
crates/ec-aac/tests/sbr_real_library/chunk_b.rsmodified+25 -181
@@ -23,23 +23,7 @@ use super::*;
2323 #[test]
2424 pub(super) fn sbr_instrument_anchor_controls() {
2525 let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
26- if std::env::var("EC_AAC_SBR_INSTRUMENT_ANCHOR").is_err() {
27- eprintln!(
28- "SKIP (round-41 Task 1): EC_AAC_SBR_INSTRUMENT_ANCHOR=1 cargo test -p ec-aac \
29- --release --test sbr_real_library sbr_instrument_anchor_controls -- --nocapture"
30- );
31- return;
32- }
33- if !have_ffmpeg() {
34- eprintln!("SKIP: ffmpeg not on PATH");
35- return;
36- }
37- let home = std::env::var("HOME").unwrap_or_default();
38- let path = PathBuf::from(format!("{home}/Music/reeln.mp4"));
39- if !path.exists() {
40- eprintln!("SKIP: {} not found", path.display());
41- return;
42- }
26+ let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4");
4327 const MIN_BAND: usize = 14;
4428 const TOP_N: usize = 128; // larger than any real band count -- keeps every HF band
4529
@@ -103,25 +87,7 @@ pub(super) fn sbr_instrument_anchor_controls() {
10387 #[test]
10488 pub(super) fn sbr_actual_noise_fraction() {
10589 let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
106- if std::env::var("EC_AAC_SBR_NOISE_ANCHOR").is_err() {
107- eprintln!(
108- "SKIP (round-41 Task 2): EC_AAC_SBR_NOISE_ANCHOR=1 cargo test -p ec-aac \
109- --release --test sbr_real_library sbr_actual_noise_fraction -- \
110- --nocapture --test-threads=1 (env-gated because it sets process \
111- env vars mid-run, which is unsound alongside parallel tests)"
112- );
113- return;
114- }
115- if !have_ffmpeg() {
116- eprintln!("SKIP: ffmpeg not on PATH");
117- return;
118- }
119- let home = std::env::var("HOME").unwrap_or_default();
120- let path = PathBuf::from(format!("{home}/Music/reeln.mp4"));
121- if !path.exists() {
122- eprintln!("SKIP: {} not found", path.display());
123- return;
124- }
90+ let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4");
12591 const MIN_BAND: usize = 14;
12692 const TOP_N: usize = 128;
12793
@@ -295,17 +261,13 @@ pub(super) fn sbr_actual_noise_fraction() {
295261 #[test]
296262 pub(super) fn sbr_header_feature_table() {
297263 let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
298- if !have_ffmpeg() {
299- eprintln!("SKIP: ffmpeg not on PATH");
300- return;
301- }
302264 struct Row {
303265 label: String,
304266 path: PathBuf,
305267 aac_stream: usize,
306268 ffmpeg_stream: usize,
307269 }
308- let mut rows: Vec<Row> = candidates()
270+ let rows: Vec<Row> = candidates()
309271 .into_iter()
310272 .map(|c| Row {
311273 label: c
@@ -318,28 +280,6 @@ pub(super) fn sbr_header_feature_table() {
318280 ffmpeg_stream: c.ffmpeg_stream,
319281 })
320282 .collect();
321- let fixtures = std::env::var("EC_AAC_HEAAC_FIXTURES")
322- .unwrap_or_else(|_| format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR")));
323- let fixtures = PathBuf::from(fixtures);
324- if require_fixture(&fixtures, "scripts/aac-tables/make-heaac-fixtures.sh") {
325- for rate in [48_000u32, 44_100] {
326- for br in ["32k", "48k", "64k", "96k"] {
327- let p = fixtures.join(format!("heaac_{rate}_{br}.m4a"));
328- if require_fixture(&p, "scripts/aac-tables/make-heaac-fixtures.sh") {
329- rows.push(Row {
330- label: format!("synth-{rate}-{br}"),
331- path: p,
332- aac_stream: 0,
333- ffmpeg_stream: 0,
334- });
335- }
336- }
337- }
338- }
339- if rows.is_empty() {
340- eprintln!("SKIP: no real HE-AAC files and no synthetic fixtures found");
341- return;
342- }
343283 let _knob = ec_aac::knobs::set_sbr_sideinfo_debug(Some(true));
344284 const WIDE_LAG_MAX: i64 = 20_000;
345285 println!(
@@ -366,12 +306,8 @@ pub(super) fn sbr_header_feature_table() {
366306 );
367307 for r in &rows {
368308 let before = ec_aac::sbr_sideinfo_log().len();
369- let Some((ours, sbr, our_rate)) = our_decode(&r.path, r.aac_stream) else {
370- eprintln!("SKIP {}: could not decode", r.label);
371- continue;
372- };
309+ let (ours, sbr, our_rate) = our_decode(&r.path, r.aac_stream).expect("decode");
373310 if sbr != ec_aac::SbrSupport::V1 {
374- eprintln!("SKIP {}: not SBR v1", r.label);
375311 continue;
376312 }
377313 let log = ec_aac::sbr_sideinfo_log();
@@ -380,10 +316,7 @@ pub(super) fn sbr_header_feature_table() {
380316 .filter(|row| row.ch == 0)
381317 .take(20)
382318 .collect();
383- if frames.is_empty() {
384- eprintln!("SKIP {}: no sideinfo rows captured", r.label);
385- continue;
386- }
319+ assert!(!frames.is_empty(), "{}: no sideinfo rows captured", r.label);
387320 let f0 = &frames[0];
388321 let mut env_counts: std::collections::BTreeMap<usize, usize> = Default::default();
389322 let mut invf_seen: std::collections::BTreeSet<u8> = Default::default();
@@ -467,18 +400,9 @@ pub(super) fn sbr_header_feature_table() {
467400 /// -- divergence from the very first AU means a per-stream setup mismatch,
468401 /// not a per-frame trigger.
469402 pub(super) fn per_au_low_band_probe(label: &str, path: &Path, aac_stream: usize) {
470- let Some((asc, aus)) = extract_aac_track(path, aac_stream) else {
471- eprintln!("SKIP {label}: extract_aac_track failed");
472- return;
473- };
474- let Ok(full_cfg) = parse_audio_specific_config(&asc) else {
475- eprintln!("SKIP {label}: asc parse failed");
476- return;
477- };
478- if !full_cfg.sbr_present {
479- eprintln!("SKIP {label}: no SBR");
480- return;
481- }
403+ let (asc, aus) = extract_aac_track(path, aac_stream).expect("extract_aac_track");
404+ let full_cfg = parse_audio_specific_config(&asc).expect("asc parse");
405+ assert!(full_cfg.sbr_present, "{label}: no SBR");
482406 let mut core_cfg = full_cfg.clone();
483407 core_cfg.sbr_present = false;
484408 core_cfg.ps_present = false;
@@ -519,14 +443,12 @@ pub(super) fn per_au_low_band_probe(label: &str, path: &Path, aac_stream: usize)
519443 break;
520444 }
521445 }
522- if core_ch0.is_empty() || full_ch0.is_empty() {
523- eprintln!(
524- "SKIP {label}: empty decode (core {} full {})",
525- core_ch0.len(),
526- full_ch0.len()
527- );
528- return;
529- }
446+ assert!(
447+ !core_ch0.is_empty() && !full_ch0.is_empty(),
448+ "{label}: empty decode (core {} full {})",
449+ core_ch0.len(),
450+ full_ch0.len()
451+ );
530452
531453 // Same convention `full_chain_low_band_matches_own_core` already
532454 // 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)
589511 #[test]
590512 pub(super) fn per_au_low_band_divergence() {
591513 let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
592- if !have_ffmpeg() {
593- eprintln!("SKIP: ffmpeg not on PATH");
594- return;
595- }
596514 let _knob = ec_aac::knobs::set_sbr_sideinfo_debug(Some(true));
597515 for c in &candidates() {
598516 per_au_low_band_probe(&c.path.display().to_string(), &c.path, c.aac_stream);
599517 }
600- let dir = std::env::var("EC_AAC_HEAAC_FIXTURES")
601- .unwrap_or_else(|_| format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR")));
602- let failing = PathBuf::from(&dir).join("heaac_44100_48k.m4a");
603- if require_fixture(&failing, "scripts/aac-tables/make-heaac-fixtures.sh") {
604- per_au_low_band_probe("synthetic 44100 48k (failing)", &failing, 0);
605- }
606518 }
607519
608520 /// Coordinator follow-up: prints what `parse_audio_specific_config` actually
@@ -618,10 +530,6 @@ pub(super) fn per_au_low_band_divergence() {
618530 #[test]
619531 pub(super) fn probe_explicit_config_and_wide_lag() {
620532 let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
621- if !have_ffmpeg() {
622- eprintln!("SKIP: ffmpeg not on PATH");
623- return;
624- }
625533 fn decode_with(cfg: ec_aac::AudioSpecificConfig, aus: &[Vec<u8>]) -> (Vec<Vec<f32>>, u32) {
626534 let rate = match (cfg.sbr_present, cfg.ps_present) {
627535 (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() {
648556 (planes, rate)
649557 }
650558
651- // `synthetic` marks the case as coming from the committed fixture library
652- // (`scripts/aac-tables/make-heaac-fixtures.sh`); the FMJ row is a
653- // `~/Downloads` host corpus and keeps its plain skip.
654- for (
655- label,
656- path,
657- aac_stream,
658- ffmpeg_stream,
659- core_sf_index,
660- core_rate,
661- ext_rate,
662- channels,
663- synthetic,
664- ) in [
665- (
666- "FMJ",
667- format!(
668- "{}/Downloads/reelp/reelp.mkv",
669- std::env::var("HOME").unwrap_or_default()
670- ),
671- 1usize,
672- 3usize,
673- 6u8,
674- 24_000u32,
675- 48_000u32,
676- 2u16,
677- false,
678- ),
679- (
680- "heaac_44100_48k",
681- format!(
682- "{}/heaac_44100_48k.m4a",
683- std::env::var("EC_AAC_HEAAC_FIXTURES").unwrap_or_else(|_| format!(
684- "{}/../../.cache/heaac-fixtures",
685- env!("CARGO_MANIFEST_DIR")
686- ))
687- ),
688- 0,
689- 0,
690- 4,
691- 44_100,
692- 0, // filled below from parsed cfg's own extension_sample_rate
693- 2,
694- true,
695- ),
696- ] {
697- let path = PathBuf::from(path);
698- if synthetic {
699- if !require_fixture(&path, "scripts/aac-tables/make-heaac-fixtures.sh") {
700- continue;
701- }
702- } else if !path.exists() {
703- eprintln!("SKIP {label}: {} absent", path.display());
704- continue;
705- }
706- let Some((asc, aus)) = extract_aac_track(&path, aac_stream) else {
707- eprintln!("SKIP {label}: extract failed");
708- continue;
709- };
559+ let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4");
560+ let (label, aac_stream, ffmpeg_stream, core_sf_index, core_rate, ext_rate, channels) =
561+ ("al_sbr_cm_48_2", 0usize, 0usize, 6u8, 24_000u32, 0u32, 2u16);
562+ {
563+ let (asc, aus) = extract_aac_track(&path, aac_stream).expect("extract");
710564 let parsed = parse_audio_specific_config(&asc);
711565 println!("{label}: asc={asc:02x?} parsed={parsed:?}");
712- let Ok(parsed_cfg) = parsed else {
713- eprintln!("SKIP {label}: parse failed");
714- continue;
715- };
566+ let parsed_cfg = parsed.expect("asc parse");
716567 let d = AacDecoder::with_config(parsed_cfg.clone());
717568 println!(
718569 " runtime: sbr_support={:?} output_sample_rate={:?}",
@@ -740,10 +591,7 @@ pub(super) fn probe_explicit_config_and_wide_lag() {
740591 pce: Vec::new(),
741592 };
742593 let (hand_planes, hand_rate) = decode_with(hand_cfg.clone(), &aus);
743- if hand_planes.is_empty() {
744- eprintln!(" hand-built config: no channels decoded");
745- continue;
746- }
594+ assert!(!hand_planes.is_empty(), "{label}: hand-built config decoded no channels");
747595 // Own-core self-consistency (upsample+lowpass convention).
748596 let core_cfg = ec_aac::AudioSpecificConfig {
749597 sbr_present: false,
@@ -777,13 +625,9 @@ pub(super) fn probe_explicit_config_and_wide_lag() {
777625 // tests use) -- the coarse search in `full_chain_low_band_matches_own_
778626 // core` landed right at that bound's edge (20005), so this checks
779627 // whether FMJ's true delay simply lies further out.
780- let home = std::env::var("HOME").unwrap_or_default();
781- let fmj = PathBuf::from(format!(
782- "{home}/Downloads/reelp/reelp.mkv"
783- ));
784- if fmj.exists()
785- && let (Some((core, core_rate)), Some((full, sbr, full_rate))) =
786- (our_decode_core_only(&fmj, 1), our_decode(&fmj, 1))
628+ let fmj = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4");
629+ if let (Some((core, core_rate)), Some((full, sbr, full_rate))) =
630+ (our_decode_core_only(&fmj, 0), our_decode(&fmj, 0))
787631 && sbr == ec_aac::SbrSupport::V1
788632 {
789633 let up: Vec<f32> = core[0].iter().flat_map(|&s| [s, s]).collect();
@@ -800,7 +644,7 @@ pub(super) fn probe_explicit_config_and_wide_lag() {
800644 /// rule (see `ffmpeg_decode`'s doc and the ledger's "never use -ac 1", which
801645 /// applies just as much to picking one of N channels as to downmixing).
802646 pub(super) fn ffmpeg_decode_pan_channel(path: &Path, absolute_stream: usize, channel: usize) -> Vec<f32> {
803- let out = Command::new("ffmpeg")
647+ let out = ec_testkit::ffmpeg()
804648 .args(["-v", "error", "-i"])
805649 .arg(path)
806650 .args([
crates/ec-aac/tests/sbr_real_library/chunk_c.rsmodified+17 -112
@@ -16,26 +16,15 @@ use super::*;
1616 #[test]
1717 pub(super) fn reelq_multichannel_lc_matches_reference() {
1818 let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
19- if !have_ffmpeg() {
20- eprintln!("SKIP: ffmpeg not on PATH");
21- return;
22- }
23- let home = std::env::var("HOME").unwrap_or_default();
24- let path = PathBuf::from(format!(
25- "{home}/Downloads/reelq/reelq.mp4"
26- ));
27- if !path.exists() {
28- eprintln!("SKIP: {} not present", path.display());
29- return;
30- }
19+ let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_5.1.mp4");
3120 let Some((ours, _sbr, rate)) = our_decode(&path, 0) else {
32- panic!("ReelQ AAC track failed to decode at all");
21+ panic!("AAC track failed to decode at all");
3322 };
34- assert_eq!(ours.len(), 8, "expected 7.1 (8 channels)");
23+ assert_eq!(ours.len(), 6, "expected 5.1 (6 channels)");
3524 let want = (rate as usize) * 10; // 10s per the charter
3625 for (ch, o) in ours.iter().enumerate() {
3726 let o = &o[..o.len().min(want)];
38- let t = ffmpeg_decode_pan_channel(&path, 2, ch);
27+ let t = ffmpeg_decode_pan_channel(&path, 0, ch);
3928 let t = &t[..t.len().min(want)];
4029 let (lag, corr) = best_lag_correlation(o, t);
4130 println!("ReelQ ch{ch}: lag {lag}, corr {corr:.6}");
@@ -76,18 +65,9 @@ pub(super) fn reelq_multichannel_lc_matches_reference() {
7665 #[test]
7766 pub(super) fn coupled_cpe_channel_swap_probe() {
7867 let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
79- if !have_ffmpeg() {
80- eprintln!("SKIP: ffmpeg not on PATH");
81- return;
82- }
83- let dir = std::env::var("EC_AAC_HEAAC_FIXTURES")
84- .unwrap_or_else(|_| format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR")));
85- let path = PathBuf::from(&dir).join("heaac_44100_48k.m4a");
86- if !require_fixture(&path, "scripts/aac-tables/make-heaac-fixtures.sh") {
87- return;
88- }
68+ let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4");
8969 let Some((ours, sbr, out_rate)) = our_decode(&path, 0) else {
90- panic!("heaac_44100_48k failed to decode");
70+ panic!("al_sbr_cm_48_2 failed to decode");
9171 };
9272 assert_eq!(sbr, ec_aac::SbrSupport::V1);
9373 assert_eq!(ours.len(), 2, "expect stereo");
@@ -337,7 +317,7 @@ pub(super) fn our_decode_uncapped(path: &Path, stream_index: usize) -> Option<(V
337317 /// AAC stream, interleaved-`f32` byte count / 4 -- i.e. `channels *
338318 /// per_channel_samples`, not capped at 30s the way `ffmpeg_decode` is.
339319 pub(super) fn ffmpeg_total_interleaved_samples(path: &Path, absolute_stream: usize) -> u64 {
340- let out = Command::new("ffmpeg")
320+ let out = ec_testkit::ffmpeg()
341321 .args(["-v", "error", "-i"])
342322 .arg(path)
343323 .args([
@@ -364,7 +344,7 @@ pub(super) fn ffmpeg_total_interleaved_samples(path: &Path, absolute_stream: usi
364344 /// `duration` against what our decoder derives and what ffmpeg actually
365345 /// produces.
366346 pub(super) fn ffprobe_field(path: &Path, entry: &str) -> String {
367- let out = Command::new("ffprobe")
347+ let out = ec_testkit::ffprobe()
368348 .args([
369349 "-v",
370350 "error",
@@ -423,58 +403,14 @@ pub(super) fn narrow_lag_at(
423403 #[test]
424404 pub(super) fn sbr441_family_sample_drift_probe() {
425405 let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
426- if !have_ffmpeg() {
427- eprintln!("SKIP: ffmpeg not on PATH");
428- return;
429- }
430- let dir = std::env::var("EC_AAC_HEAAC_FIXTURES")
431- .unwrap_or_else(|_| format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR")));
432- let home = std::env::var("HOME").unwrap_or_default();
433- // `synthetic` marks the rows served by the committed fixture library
434- // (`scripts/aac-tables/make-heaac-fixtures.sh`); the reeln control is
435- // a `~/Music` host corpus and keeps its plain skip.
436- let cases: [(&str, PathBuf, i64, bool); 3] = [
437- (
438- "heaac_44100_48k (FAIL family)",
439- PathBuf::from(&dir).join("heaac_44100_48k.m4a"),
440- -4674,
441- true,
442- ),
443- (
444- "heaac_48000_48k (48k control)",
445- PathBuf::from(&dir).join("heaac_48000_48k.m4a"),
446- // corrected via this test's own wide free-search cross-check
447- // (below) -- 0 was a bad guess, true fixed lag is -4673, same
448- // as the failing family's.
449- -4673,
450- true,
451- ),
452- (
453- "reeln (44.1k control)",
454- PathBuf::from(format!("{home}/Music/reeln.mp4")),
455- // corrected via this test's own wide free-search cross-check
456- // (below) -- -576 was this file's CORE-vs-FULL-chain delay
457- // from an earlier probe, not its full-chain-vs-ffmpeg-reference
458- // lag, which is +385.
459- 385,
460- false,
461- ),
406+ let cases: [(&str, PathBuf, i64); 2] = [
407+ ("al_sbr_cm_48_2", ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4"), 0),
408+ ("al_sbr_sr_48_2_fsaac48", ec_testkit::fixture("open/fate/aac/al_sbr_sr_48_2_fsaac48.mp4"), 0),
462409 ];
463- for (label, path, seed_lag, synthetic) in cases {
410+ for (label, path, seed_lag) in cases {
464411 println!("\n=== {label}: {} ===", path.display());
465- if synthetic {
466- if !require_fixture(&path, "scripts/aac-tables/make-heaac-fixtures.sh") {
467- continue;
468- }
469- } else if !path.exists() {
470- eprintln!("SKIP {label}: {} absent", path.display());
471- continue;
472- }
473412 let holds_before = ec_aac::hold_call_count();
474- let Some((ours, out_rate, au_count)) = our_decode_uncapped(&path, 0) else {
475- eprintln!("SKIP {label}: our_decode_uncapped failed");
476- continue;
477- };
413+ let (ours, out_rate, au_count) = our_decode_uncapped(&path, 0).expect("our_decode_uncapped");
478414 // `ffmpeg_decode_pan_channel` caps at 10s (per its own charter,
479415 // shared with `reelq_multichannel_lc_matches_reference`);
480416 // 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() {
553489 #[test]
554490 pub(super) fn sbr_hf_window_band_probe() {
555491 let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
556- if !have_ffmpeg() {
557- eprintln!("SKIP: ffmpeg not on PATH");
558- return;
559- }
560- let dir = std::env::var("EC_AAC_HEAAC_FIXTURES")
561- .unwrap_or_else(|_| format!("{}/../../.cache/heaac-fixtures", env!("CARGO_MANIFEST_DIR")));
562- let path = PathBuf::from(&dir).join("heaac_48000_64k.m4a");
563- if !require_fixture(&path, "scripts/aac-tables/make-heaac-fixtures.sh") {
564- return;
565- }
492+ let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4");
566493 const LAG: i64 = -4673;
567494
568- let Some((ours, out_rate, _au_count)) = our_decode_uncapped(&path, 0) else {
569- eprintln!("SKIP: our_decode_uncapped failed");
570- return;
571- };
495+ let (ours, out_rate, _au_count) = our_decode_uncapped(&path, 0).expect("our_decode_uncapped");
572496 let ref_l = ffmpeg_decode(&path, 0, 2).swap_remove(0);
573497 let ch0 = &ours[0];
574498
@@ -661,27 +585,8 @@ pub(super) fn sbr_hf_window_band_probe() {
661585 #[test]
662586 pub(super) fn sbr_residual_locator() {
663587 let _guard = DECODE_SERIAL.lock().unwrap_or_else(|e| e.into_inner());
664- if !have_ffmpeg() {
665- return;
666- }
667- // lane-h264reallib: `unwrap_or_default()`, the shape this file's five
668- // other HOME reads already use (:2710, :3426, :4109, :4182, :4575). A bare
669- // `unwrap()` panicked on any host with no HOME -- a fleet runner -- which
670- // is a red with no bearing on the decoder. The `path.exists()` guard below
671- // already handles the absent-file case, so an empty HOME just makes the
672- // fallback path relative-and-nonexistent and the test returns.
673- let home = std::env::var("HOME").unwrap_or_default();
674- // `EC_AAC_SBR_LOCATOR_FILE` points the same instrument at any other
675- // HE-AAC file (e.g. a mono, uncoupled, noise-only probe encode).
676- let path = std::env::var("EC_AAC_SBR_LOCATOR_FILE")
677- .map(PathBuf::from)
678- .unwrap_or_else(|_| PathBuf::from(format!("{home}/Music/reeln.mp4")));
679- if !path.exists() {
680- return;
681- }
682- let Some((ours, _, rate)) = our_decode(&path, 0) else {
683- return;
684- };
588+ let path = ec_testkit::fixture("open/fate/aac/al_sbr_cm_48_2.mp4");
589+ let (ours, _, rate) = our_decode(&path, 0).expect("decode");
685590 let theirs = ffmpeg_decode(&path, 0, ours.len());
686591 const W: usize = 2048;
687592 const FFT_LEN: usize = 2048;
crates/ec-aac/tests/sbr_real_library/helpers.rsmodified+13 -29
@@ -1,33 +1,17 @@
1-//! Shared analysis helpers for the SBR real-library probes.
21
32 use super::*;
43
5-pub(super) use crate::common::have_ffmpeg;
6-/// Fixture-presence probe for the generated HE-AAC matrix under
7-/// `<repo>/.cache/heaac-fixtures` (`scripts/aac-tables/make-heaac-fixtures.sh`).
8-/// Returns whether the fixture is present, but never silently: under
9-/// `EC_REQUIRE_FIXTURES=1` an absent fixture is a hard failure naming the path
10-/// and the script that regenerates it, so a host whose fixture library drifted
11-/// reports RED instead of a green SKIP (class: gate-skips-on-its-own-failure;
12-/// model `have_ffmpeg` in crates/ec-av1/src/stream.rs, which was silently
13-/// short-circuited because the probe ran first in a compound `if`).
14-///
15-/// Order is load-bearing: probe, assert, return. Never merge the probe into
16-/// the same `if` as the escape. The `~/Music` / `~/Downloads` / `~/Videos`
17-/// scans in this file are host corpora, not the committed fixture library, and
18-/// keep their plain skip.
19-pub(super) fn require_fixture(path: &Path, generator: &str) -> bool {
20- let present = path.exists();
21- assert!(
22- present || std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
23- "EC_REQUIRE_FIXTURES=1 but fixture {} is absent -- regenerate with: {}",
24- path.display(),
25- generator
26- );
27- if !present {
28- eprintln!("SKIP: fixture {} absent", path.display());
29- }
30- present
4+pub(super) fn fate_aac() -> Vec<PathBuf> {
5+ [
6+ "open/fate/aac/al_sbr_cm_48_2.mp4",
7+ "open/fate/aac/al_sbr_cm_48_5.1.mp4",
8+ "open/fate/aac/al_sbr_ps_04_new.mp4",
9+ "open/fate/aac/al_sbr_ps_06_new.mp4",
10+ "open/fate/aac/al_sbr_sr_48_2_fsaac48.mp4",
11+ ]
12+ .iter()
13+ .map(|rel| ec_testkit::fixture(rel))
14+ .collect()
3115 }
3216
3317 /// 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;
3721 /// ffmpeg's decode of a file's given absolute stream index, as
3822 /// planar-by-channel `f32`.
3923 pub(super) fn ffmpeg_decode(path: &Path, absolute_stream: usize, channels: usize) -> Vec<Vec<f32>> {
40- let out = Command::new("ffmpeg")
24+ let out = ec_testkit::ffmpeg()
4125 .args(["-v", "error", "-i"])
4226 .arg(path)
4327 .args([
@@ -2149,7 +2133,7 @@ pub(super) fn ffmpeg_decode_at_rate(
21492133 channels: usize,
21502134 target_rate: u32,
21512135 ) -> Vec<Vec<f32>> {
2152- let out = Command::new("ffmpeg")
2136+ let out = ec_testkit::ffmpeg()
21532137 .args(["-v", "error", "-i"])
21542138 .arg(path)
21552139 .args([
crates/ec-aac/tests/sbr_real_library/main.rsmodified+0 -10
@@ -1,15 +1,7 @@
1-//! The SBR chain, against real HE-AAC files pulled from the user's own media
2-//! directories, decoded through their real container (mp4 `esds` / Matroska
3-//! `CodecPrivate`) so `AacDecoder::with_config_bytes` actually arms the SBR
4-//! path -- `tests/oracle.rs` remuxes everything to bare ADTS first, and an
5-//! ADTS stream carries no AudioSpecificConfig, so its SBR chain never sees a
6-//! frame. Every file here is a live discovery over `~/Music`, `~/Downloads`,
7-//! `~/Videos`: absent files skip loudly, nothing is generated or bundled.
81
92 use std::fs::File;
103 use std::io::{BufReader, Read};
114 use std::path::{Path, PathBuf};
12-use std::process::Command;
135
146 use ec_aac::{AacDecoder, parse_audio_specific_config};
157 use ec_core::{CodecId, Demuxer, Packet};
@@ -28,8 +20,6 @@ use ec_mp4::Mp4Demuxer;
2820 /// each test.
2921 static DECODE_SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
3022
31-#[path = "../common/mod.rs"]
32-mod common;
3323 mod helpers;
3424 mod chunk_a;
3525 mod chunk_b;
crates/ec-ac3/Cargo.tomlmodified+3 -0
@@ -9,3 +9,6 @@ authors.workspace = true
99 [dependencies]
1010 ec-core.workspace = true
1111 ec-dsp.workspace = true
12+
13+[dev-dependencies]
14+ec-testkit.workspace = true
crates/ec-ac3/fuzz/seed.shmodified+2 -2
@@ -11,8 +11,8 @@
1111 set -euo pipefail
1212
1313 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
14-FIXTURES=$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures/audio
15-[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/link-fixtures.sh" >&2; exit 2; }
14+FIXTURES=${EC_FIXTURES:-$(cd -- "$FUZZ_DIR/../../.." && pwd)/fixtures}/audio
15+[ -d "$FIXTURES" ] || { echo "seed.sh: $FIXTURES missing; run scripts/fixtures.sh" >&2; exit 2; }
1616
1717 FILES=("$FIXTURES"/ac3-*.ac3 "$FIXTURES"/eac3-*.eac3 "$FIXTURES"/ac3dep-*.eac3)
1818 [ -e "${FILES[0]}" ] || { echo "seed.sh: no ac3-*.ac3 or eac3-*.eac3 fixtures in $FIXTURES" >&2; exit 2; }
crates/ec-ac3/tests/it/common.rsdeleted+0 -9
@@ -1,9 +0,0 @@
1-use std::process::Command;
2-
3-/// Whether `ffmpeg -version` runs successfully.
4-pub fn have_ffmpeg() -> bool {
5- Command::new("ffmpeg")
6- .arg("-version")
7- .output()
8- .is_ok_and(|o| o.status.success())
9-}
crates/ec-ac3/tests/it/decode_matrix.rsmodified+11 -53
@@ -2,16 +2,10 @@
22 //! compared against ffmpeg, plus the header surface a container reads and the
33 //! no-panic contract on damaged input.
44 //!
5-//! ffmpeg is test tooling — it is driven through `std::process` so the crate
6-//! itself never gains a media dependency. Missing fixtures or a missing ffmpeg
7-//! skip the comparison rather than fail it; `scripts/gen-fixtures.sh` writes
8-//! the fixtures.
95
10-use std::path::{Path, PathBuf};
11-use std::process::Command;
6+use std::path::Path;
127
138 use ec_ac3::{Ac3Decoder, Downmix, Options, Syntax, bsi, eac3, syncinfo};
14-use crate::common::have_ffmpeg;
159
1610 /// Per-channel correlation floor (rubric: audio-ac3 MUST).
1711 const MIN_CORR: f64 = 0.999;
@@ -19,16 +13,9 @@ const MIN_CORR: f64 = 0.999;
1913 /// synthetic material.
2014 const MAX_RMS: f64 = 1e-3;
2115
22-fn fixtures() -> PathBuf {
23- Path::new(env!("CARGO_MANIFEST_DIR"))
24- .join("../../fixtures/audio")
25- .canonicalize()
26- .unwrap_or_else(|_| PathBuf::from("../../fixtures/audio"))
27-}
28-
2916 /// ffmpeg's decode of `path` as interleaved `f32`.
3017 fn reference(path: &Path) -> Vec<f32> {
31- let out = Command::new("ffmpeg")
18+ let out = ec_testkit::ffmpeg()
3219 .args(["-v", "error", "-i"])
3320 .arg(path)
3421 .args(["-f", "f32le", "-"])
@@ -96,13 +83,8 @@ fn correlation(a: &[f32], b: &[f32]) -> (f64, f64) {
9683
9784 #[test]
9885 fn fixture_matrix_matches_ffmpeg() {
99- let dir = fixtures();
100- if !dir.exists() || !have_ffmpeg() {
101- eprintln!("skipping: no fixtures or no ffmpeg");
102- return;
103- }
10486 let mut checked = 0;
105- for entry in std::fs::read_dir(&dir).expect("fixtures dir") {
87+ for entry in std::fs::read_dir(ec_testkit::root().join("audio")).expect("audio fixtures") {
10688 let path = entry.expect("entry").path();
10789 let name = path.file_name().unwrap_or_default().to_string_lossy();
10890 if !(name.starts_with("ac3-") || name.starts_with("eac3-")) {
@@ -140,10 +122,7 @@ fn fixture_matrix_matches_ffmpeg() {
140122
141123 #[test]
142124 fn dither_only_adds_noise_below_the_signal() {
143- let path = fixtures().join("ac3-5.1-48000.ac3");
144- if !path.exists() {
145- return;
146- }
125+ let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3");
147126 let (with, channels) = decode(&path, Options::default());
148127 let (without, _) = decode(
149128 &path,
@@ -160,10 +139,7 @@ fn dither_only_adds_noise_below_the_signal() {
160139
161140 #[test]
162141 fn headers_state_what_the_container_needs() {
163- let path = fixtures().join("ac3-5.1-48000.ac3");
164- if !path.exists() {
165- return;
166- }
142+ let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3");
167143 let data = std::fs::read(&path).expect("fixture");
168144 // The exact call shape a container makes: syncinfo from the frame start,
169145 // bsi from five bytes in.
@@ -176,7 +152,7 @@ fn headers_state_what_the_container_needs() {
176152 assert_eq!(bsi.channels, 6);
177153 assert!((1..=31).contains(&bsi.dialnorm));
178154
179- let eac3_path = fixtures().join("eac3-5.1-48000.eac3");
155+ let eac3_path = ec_testkit::fixture("audio/eac3-5.1-48000.eac3");
180156 let data = std::fs::read(&eac3_path).expect("fixture");
181157 let hdr = eac3::bsi::parse(&data[2..]).expect("eac3 bsi");
182158 assert_eq!(hdr.sample_rate, 48_000);
@@ -190,10 +166,7 @@ fn headers_state_what_the_container_needs() {
190166
191167 #[test]
192168 fn frame_info_surfaces_the_metadata_the_rubric_asks_for() {
193- let path = fixtures().join("ac3-5.1-48000.ac3");
194- if !path.exists() {
195- return;
196- }
169+ let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3");
197170 let data = std::fs::read(&path).expect("fixture");
198171 let size = ec_ac3::frame_size(&data).expect("frame size");
199172 let mut decoder = Ac3Decoder::new();
@@ -210,10 +183,7 @@ fn frame_info_surfaces_the_metadata_the_rubric_asks_for() {
210183
211184 #[test]
212185 fn stereo_downmix_folds_five_one_without_clipping() {
213- let path = fixtures().join("ac3-5.1-48000.ac3");
214- if !path.exists() {
215- return;
216- }
186+ let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3");
217187 let (stereo, channels) = decode(
218188 &path,
219189 Options {
@@ -240,10 +210,7 @@ fn stereo_downmix_folds_five_one_without_clipping() {
240210
241211 #[test]
242212 fn damaged_input_never_panics() {
243- let path = fixtures().join("ac3-stereo-48000.ac3");
244- if !path.exists() {
245- return;
246- }
213+ let path = ec_testkit::fixture("audio/ac3-stereo-48000.ac3");
247214 let data = std::fs::read(&path).expect("fixture");
248215 let size = ec_ac3::frame_size(&data).expect("frame size");
249216 let frame = &data[..size];
@@ -281,13 +248,8 @@ fn damaged_input_never_panics() {
281248 /// answers the same way for an AC-3 tail.
282249 #[test]
283250 fn a_concatenated_tail_is_refused_by_name_not_dropped() {
284- let dir = fixtures();
285- if !dir.join("eac3-5.1-48000.eac3").exists() {
286- eprintln!("skipping: no fixtures");
287- return;
288- }
289251 for name in ["ac3-5.1-48000.ac3", "eac3-5.1-48000.eac3"] {
290- let data = std::fs::read(dir.join(name)).expect("fixture");
252+ let data = std::fs::read(ec_testkit::fixture(&format!("audio/{name}"))).expect("fixture");
291253 let first = ec_ac3::frame_size(&data).expect("first frame size");
292254 let second = ec_ac3::frame_size(&data[first..]).expect("second frame size");
293255 let mut packet = data[..first].to_vec();
@@ -328,11 +290,7 @@ fn a_concatenated_tail_is_refused_by_name_not_dropped() {
328290 /// frame — sample for sample, whatever its length.
329291 #[test]
330292 fn padding_that_is_not_a_syncframe_still_decodes() {
331- let path = fixtures().join("ac3-5.1-48000.ac3");
332- if !path.exists() {
333- eprintln!("skipping: no fixtures");
334- return;
335- }
293+ let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3");
336294 let data = std::fs::read(&path).expect("fixture");
337295 let first = ec_ac3::frame_size(&data).expect("frame size");
338296 let frame = &data[..first];
crates/ec-ac3/tests/it/dependent.rsmodified+10 -77
@@ -2,12 +2,8 @@
22 //! spliced stream: its channel placement (the replace-or-add rule of Table E2.5)
33 //! and its channel order, which ffprobe names in `channel_layout`.
44 //!
5-//! The fixtures come from `scripts/gen-ac3dep-fixtures.sh`. Missing fixtures or
6-//! a missing ffmpeg skip the comparison, as in `decode_matrix.rs`, unless
7-//! `EC_REQUIRE_FIXTURES=1`, which makes an absent fixture a failure.
85
9-use std::path::{Path, PathBuf};
10-use std::process::Command;
6+use std::path::Path;
117
128 use ec_ac3::{Ac3Decoder, Error, Options, eac3, frame_size};
139 use ec_core::{ChannelLayout, ChannelPosition};
@@ -16,48 +12,9 @@ use ec_core::{ChannelLayout, ChannelPosition};
1612 const MIN_CORR: f64 = 0.999;
1713 const MAX_RMS: f64 = 1e-3;
1814
19-fn fixtures() -> PathBuf {
20- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio")
21-}
22-
23-/// Whether every path is present. A missing one skips the test, or fails it
24-/// under `EC_REQUIRE_FIXTURES=1`.
25-fn present(name: &str, paths: &[PathBuf]) -> bool {
26- let missing: Vec<_> = paths.iter().filter(|p| !p.exists()).collect();
27- if missing.is_empty() {
28- return true;
29- }
30- assert!(
31- std::env::var("EC_REQUIRE_FIXTURES").as_deref() != Ok("1"),
32- "{name}: fixture missing: {missing:?}"
33- );
34- eprintln!("skipping {name}: fixture missing: {missing:?}");
35- false
36-}
37-
38-/// Whether ffmpeg and ffprobe run. Missing tools skip, or fail under
39-/// `EC_REQUIRE_FIXTURES=1`.
40-fn have_ffmpeg(name: &str) -> bool {
41- let ok = |tool: &str| {
42- Command::new(tool)
43- .arg("-version")
44- .output()
45- .is_ok_and(|o| o.status.success())
46- };
47- if ok("ffmpeg") && ok("ffprobe") {
48- return true;
49- }
50- assert!(
51- std::env::var("EC_REQUIRE_FIXTURES").as_deref() != Ok("1"),
52- "{name}: ffmpeg and ffprobe are required"
53- );
54- eprintln!("skipping {name}: ffmpeg or ffprobe missing");
55- false
56-}
57-
5815 /// ffprobe's `channel_layout` name for the first audio stream of `path`.
5916 fn ffprobe_layout(path: &Path) -> String {
60- let out = Command::new("ffprobe")
17+ let out = ec_testkit::ffprobe()
6118 .args(["-v", "error", "-f", "eac3", "-select_streams", "a:0"])
6219 .args(["-show_entries", "stream=channel_layout", "-of", "csv=p=0"])
6320 .arg(path)
@@ -68,7 +25,7 @@ fn ffprobe_layout(path: &Path) -> String {
6825
6926 /// ffmpeg's decode of `path` as interleaved `f32`, in ffmpeg's channel order.
7027 fn reference(path: &Path, channels: usize) -> Vec<Vec<f32>> {
71- let out = Command::new("ffmpeg")
28+ let out = ec_testkit::ffmpeg()
7229 .args(["-v", "error", "-f", "eac3", "-i"])
7330 .arg(path)
7431 .args(["-f", "f32le", "-"])
@@ -170,15 +127,8 @@ fn correlation(a: &[f32], b: &[f32]) -> (f64, f64, f64) {
170127 /// repeats the dependent's left channel. The core decode is ffmpeg's own
171128 /// unchanged 5.1 path, so it is the reference that ffmpeg itself gets right.
172129 fn check_against_ffmpeg(name: &str, ffprobe_name: &str, layout: &ChannelLayout, side_from_core: bool) {
173- let stream = fixtures().join(name);
174- let core = fixtures().join("ac3dep-src-5.1.eac3");
175- let mut paths = vec![stream.clone()];
176- if side_from_core {
177- paths.push(core.clone());
178- }
179- if !present(name, &paths) || !have_ffmpeg(name) {
180- return;
181- }
130+ let stream = ec_testkit::fixture(&format!("audio/{name}"));
131+ let core_side = side_from_core.then(|| reference(&ec_testkit::fixture("audio/ac3dep-src-5.1.eac3"), 6));
182132 assert_eq!(ffprobe_layout(&stream), ffprobe_name, "{name}: ffprobe channel_layout");
183133 let data = std::fs::read(&stream).expect("fixture");
184134 let (ours, channels, ours_layout) = decode(&data);
@@ -186,7 +136,6 @@ fn check_against_ffmpeg(name: &str, ffprobe_name: &str, layout: &ChannelLayout,
186136 assert_eq!(channels, layout.channel_count(), "{name}: channels");
187137
188138 let theirs = reference(&stream, channels);
189- let core_side = side_from_core.then(|| reference(&core, 6));
190139 let frames = ours.len() / channels;
191140 assert_eq!(frames, theirs[0].len(), "{name}: frame count vs ffmpeg");
192141
@@ -246,12 +195,8 @@ fn side_pair_replacement_carries_the_dependent_signal() {
246195 // The replaced pair is the dependent stereo source (880 Hz and 1320 Hz
247196 // sines), not the core's: compare the side channels with ffmpeg's decode
248197 // of that source on its own.
249- let dir = fixtures();
250- let repl = dir.join("ac3dep-repl-48000.eac3");
251- let src20 = dir.join("ac3dep-src-2.0.eac3");
252- if !present("ac3dep-repl-48000.eac3", &[repl.clone(), src20.clone()]) || !have_ffmpeg("replacement signal") {
253- return;
254- }
198+ let repl = ec_testkit::fixture("audio/ac3dep-repl-48000.eac3");
199+ let src20 = ec_testkit::fixture("audio/ac3dep-src-2.0.eac3");
255200 let data = std::fs::read(&repl).expect("fixture");
256201 let (ours, channels, _) = decode(&data);
257202 assert_eq!(channels, 6, "replacement keeps the 5.1 channel count");
@@ -266,11 +211,7 @@ fn side_pair_replacement_carries_the_dependent_signal() {
266211
267212 #[test]
268213 fn dependent_without_an_independent_is_named_not_decoded() {
269- let dir = fixtures();
270- let stream = dir.join("ac3dep-7.1-48000.eac3");
271- if !present("ac3dep-7.1-48000.eac3", std::slice::from_ref(&stream)) {
272- return;
273- }
214+ let stream = ec_testkit::fixture("audio/ac3dep-7.1-48000.eac3");
274215 let data = std::fs::read(&stream).expect("fixture");
275216 let packet = packets(&data)[0];
276217 // The dependent frame alone, as a first substream.
@@ -285,11 +226,7 @@ fn dependent_without_an_independent_is_named_not_decoded() {
285226
286227 #[test]
287228 fn truncated_dependent_substream_is_an_error_not_a_panic() {
288- let dir = fixtures();
289- let stream = dir.join("ac3dep-7.1-48000.eac3");
290- if !present("ac3dep-7.1-48000.eac3", std::slice::from_ref(&stream)) {
291- return;
292- }
229+ let stream = ec_testkit::fixture("audio/ac3dep-7.1-48000.eac3");
293230 let data = std::fs::read(&stream).expect("fixture");
294231 let packet = packets(&data)[0];
295232 for cut in [1, 2, 8, 100, 500] {
@@ -300,11 +237,7 @@ fn truncated_dependent_substream_is_an_error_not_a_panic() {
300237
301238 #[test]
302239 fn a_second_independent_substream_in_the_packet_is_still_refused() {
303- let dir = fixtures();
304- let src20 = dir.join("ac3dep-src-2.0.eac3");
305- if !present("ac3dep-src-2.0.eac3", std::slice::from_ref(&src20)) {
306- return;
307- }
240+ let src20 = ec_testkit::fixture("audio/ac3dep-src-2.0.eac3");
308241 let data = std::fs::read(&src20).expect("fixture");
309242 let first = packets(&data)[0];
310243 let mut two = first.to_vec();
crates/ec-ac3/tests/it/encode_matrix.rsmodified+24 -43
@@ -1,13 +1,10 @@
11 //! Encoder coverage: frames our own decoder round-trips, and that ffmpeg
2-//! (when present) accepts as valid AC-3 and decodes to the same audio — on
32 //! synthetic signals and on the real 16-bit fixtures, at every rate and
43 //! layout the encoder offers.
54
65 use std::path::Path;
7-use std::process::Command;
86
97 use ec_ac3::{Ac3Decoder, Ac3Encoder, EncoderConfig};
10-use crate::common::have_ffmpeg;
118
129 /// 440 Hz tone for 1 s, then 0.5 s of silence, interleaved across `channels`.
1310 fn tone_then_silence(sample_rate: u32, channels: usize) -> Vec<f32> {
@@ -80,18 +77,14 @@ fn take_channel(interleaved: &[f32], channels: usize, ch: usize) -> Vec<f32> {
8077 .collect()
8178 }
8279
83-/// The fixture's PCM decoded by ffmpeg, with its rate and channel count; None
84-/// without ffmpeg.
85-fn read_wav(path: &Path) -> Option<(Vec<f32>, u32, usize)> {
86- let out = Command::new("ffmpeg")
80+fn read_wav(path: &Path) -> (Vec<f32>, u32, usize) {
81+ let out = ec_testkit::ffmpeg()
8782 .args(["-v", "error", "-i"])
8883 .arg(path)
8984 .args(["-f", "f32le", "-"])
9085 .output()
91- .ok()?;
92- if !out.status.success() {
93- return None;
94- }
86+ .expect("ffmpeg");
87+ assert!(out.status.success(), "ffmpeg cannot read {}", path.display());
9588 let samples = out
9689 .stdout
9790 .as_chunks::<4>().0.iter()
@@ -99,11 +92,11 @@ fn read_wav(path: &Path) -> Option<(Vec<f32>, u32, usize)> {
9992 .collect();
10093 let probe = ffprobe(path, "channels,sample_rate");
10194 let field = |key: &str| probe_field(&probe, key).and_then(|v| v.parse::<u32>().ok());
102- Some((samples, field("sample_rate")?, field("channels")? as usize))
95+ (samples, field("sample_rate").unwrap(), field("channels").unwrap() as usize)
10396 }
10497
10598 fn ffprobe(path: &Path, entries: &str) -> String {
106- let out = Command::new("ffprobe")
99+ let out = ec_testkit::ffprobe()
107100 .args(["-v", "error", "-select_streams", "a:0", "-show_entries"])
108101 .arg(format!("stream={entries}"))
109102 .args(["-of", "default=noprint_wrappers=1"])
@@ -121,7 +114,7 @@ fn probe_field(text: &str, key: &str) -> Option<String> {
121114
122115 /// ffmpeg's decode of an AC-3 file, asserting it voiced no complaint.
123116 fn oracle_decode(path: &Path) -> Vec<f32> {
124- let out = Command::new("ffmpeg")
117+ let out = ec_testkit::ffmpeg()
125118 .args(["-v", "warning", "-i"])
126119 .arg(path)
127120 .args(["-f", "f32le", "-"])
@@ -227,10 +220,6 @@ fn silence_and_tone_frames_decode_in_our_decoder() {
227220
228221 #[test]
229222 fn oracle_accepts_our_frames() {
230- if !have_ffmpeg() {
231- eprintln!("skipping: ffmpeg not found");
232- return;
233- }
234223 let config = EncoderConfig {
235224 sample_rate: 48_000,
236225 channels: 2,
@@ -242,7 +231,7 @@ fn oracle_accepts_our_frames() {
242231 let path = dir.join("ec_ac3_encode_matrix_oracle.ac3");
243232 std::fs::write(&path, &data).unwrap();
244233
245- let out = Command::new("ffmpeg")
234+ let out = ec_testkit::ffmpeg()
246235 .args(["-v", "warning", "-i"])
247236 .arg(&path)
248237 .args(["-f", "f32le", "-"])
@@ -278,16 +267,12 @@ fn oracle_accepts_our_frames() {
278267 /// asked for. Prints the per-file numbers and the stereo strategy shares.
279268 #[test]
280269 fn real_fixtures_round_trip_through_our_decoder_and_the_oracle() {
281- if !have_ffmpeg() {
282- eprintln!("skipping: ffmpeg not found");
283- return;
284- }
285- let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio");
270+ let root = ec_testkit::root().join("audio");
286271 let mut failures = Vec::new();
287272 for layout in ["mono", "stereo", "5.1"] {
288273 for rate in [48_000u32, 44_100] {
289274 let path = root.join(format!("wav16-{layout}-{rate}.wav"));
290- let (pcm, sample_rate, channels) = read_wav(&path).unwrap_or_else(|| panic!("{}", path.display()));
275+ let (pcm, sample_rate, channels) = read_wav(&path);
291276 assert_eq!(sample_rate, rate);
292277 let bitrate_kbps = match channels { 1 => 96, 2 => 192, _ => 448 };
293278 let config = EncoderConfig { sample_rate, channels: channels as u16, bitrate_kbps };
@@ -356,14 +341,12 @@ fn click_train_switches_blocks_and_still_round_trips() {
356341 let corr = worst_corr(&pcm, &decode_all(&data, channels), channels);
357342 eprintln!("click train: ours {corr:.4}, {stats:?}");
358343 assert!(corr >= 0.95, "click train corr {corr}");
359- if have_ffmpeg() {
360- let out = std::env::temp_dir().join("ec_ac3_encode_matrix_clicks.ac3");
361- std::fs::write(&out, &data).unwrap();
362- let corr = worst_corr(&pcm, &oracle_decode(&out), channels);
363- let _ = std::fs::remove_file(&out);
364- eprintln!("click train: oracle {corr:.4}");
365- assert!(corr >= 0.95, "click train oracle corr {corr}");
366- }
344+ let out = std::env::temp_dir().join("ec_ac3_encode_matrix_clicks.ac3");
345+ std::fs::write(&out, &data).unwrap();
346+ let corr = worst_corr(&pcm, &oracle_decode(&out), channels);
347+ let _ = std::fs::remove_file(&out);
348+ eprintln!("click train: oracle {corr:.4}");
349+ assert!(corr >= 0.95, "click train oracle corr {corr}");
367350 }
368351
369352 #[test]
@@ -380,16 +363,14 @@ fn tone_at_32khz_round_trips() {
380363 let data = encode(config, &pcm);
381364 let corr = worst_corr(&pcm, &decode_all(&data, 2), 2);
382365 assert!(corr >= 0.99, "32 kHz ours corr {corr}");
383- if have_ffmpeg() {
384- let out = std::env::temp_dir().join("ec_ac3_encode_matrix_32k.ac3");
385- std::fs::write(&out, &data).unwrap();
386- let corr = worst_corr(&pcm, &oracle_decode(&out), 2);
387- let probe = ffprobe(&out, "sample_rate,bit_rate");
388- let _ = std::fs::remove_file(&out);
389- assert!(corr >= 0.99, "32 kHz oracle corr {corr}");
390- assert_eq!(probe_field(&probe, "sample_rate").as_deref(), Some("32000"), "{probe}");
391- assert_eq!(probe_field(&probe, "bit_rate").as_deref(), Some("96000"), "{probe}");
392- }
366+ let out = std::env::temp_dir().join("ec_ac3_encode_matrix_32k.ac3");
367+ std::fs::write(&out, &data).unwrap();
368+ let corr = worst_corr(&pcm, &oracle_decode(&out), 2);
369+ let probe = ffprobe(&out, "sample_rate,bit_rate");
370+ let _ = std::fs::remove_file(&out);
371+ assert!(corr >= 0.99, "32 kHz oracle corr {corr}");
372+ assert_eq!(probe_field(&probe, "sample_rate").as_deref(), Some("32000"), "{probe}");
373+ assert_eq!(probe_field(&probe, "bit_rate").as_deref(), Some("96000"), "{probe}");
393374 }
394375
395376 /// 200 random (rate, channels, bit rate) configurations, two frames of
crates/ec-ac3/tests/it/ffmpeg_parity.rsmodified+2 -9
@@ -11,13 +11,10 @@
1111 //! with the LFE (which carries only rounding-level content here) also held to
1212 //! the same correlation since it is not silent.
1313 //!
14-//! Needs ffmpeg on PATH; without it the test skips loudly.
1514
1615 use std::path::{Path, PathBuf};
17-use std::process::Command;
1816
1917 use ec_ac3::{Ac3Decoder, Options};
20-use crate::common::have_ffmpeg;
2118
2219 const MIN_CORR: f64 = 0.999;
2320 /// 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 {
5956 "ac3".into(),
6057 ]);
6158 args.push(out.display().to_string());
62- let status = Command::new("ffmpeg").args(&args).status().expect("ffmpeg");
59+ let status = ec_testkit::ffmpeg().args(&args).status().expect("ffmpeg");
6360 assert!(status.success(), "ffmpeg encode of {name} failed");
6461 out
6562 }
6663
6764 /// ffmpeg's decode of the stream as interleaved `f32`.
6865 fn reference(path: &Path, channels: usize) -> Vec<f32> {
69- let out = Command::new("ffmpeg")
66+ let out = ec_testkit::ffmpeg()
7067 .args(["-v", "error", "-nostdin", "-i"])
7168 .arg(path)
7269 .args(["-f", "f32le", "-acodec", "pcm_f32le", "-ac"])
@@ -136,10 +133,6 @@ fn correlation(ours: &[f32], theirs: &[f32], channels: usize, ch: usize) -> f64
136133 }
137134
138135 fn check(name: &str, channels: usize, bitrate: &str) {
139- if !have_ffmpeg() {
140- eprintln!("skip {name}: ffmpeg not on PATH");
141- return;
142- }
143136 let work = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("ffmpeg-parity");
144137 std::fs::create_dir_all(&work).expect("work dir");
145138 let stream = encode(&work, name, channels, bitrate);
crates/ec-ac3/tests/it/main.rsmodified+0 -1
@@ -1,7 +1,6 @@
11 //! One integration-test binary for ec-ac3; each module is one former `tests/*.rs` file.
22 #![forbid(unsafe_code)]
33
4-mod common;
54 mod decode_matrix;
65 mod dependent;
76 mod encode_matrix;
crates/ec-ac3/tests/it/packet_walk.rsmodified+7 -47
@@ -5,32 +5,10 @@
55 //! syncframe in the packet against one decoder state. The reference is the
66 //! same bytes decoded one frame at a time on a fresh decoder, which the
77 //! per-frame matrix already holds to ffmpeg, so equality here is exact.
8-//!
9-//! Missing fixtures skip, or fail under `EC_REQUIRE_FIXTURES=1`.
10-
11-use std::path::{Path, PathBuf};
128
139 use ec_ac3::{Ac3Decoder, Error, eac3, frame_size};
1410 use ec_core::{Decoder, Frame, Packet, TimeBase};
1511
16-fn fixtures() -> PathBuf {
17- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio")
18-}
19-
20-/// Whether the fixture is present. A missing one skips the test, or fails it
21-/// under `EC_REQUIRE_FIXTURES=1`.
22-fn present(path: &Path) -> bool {
23- if path.exists() {
24- return true;
25- }
26- assert!(
27- std::env::var("EC_REQUIRE_FIXTURES").as_deref() != Ok("1"),
28- "fixture missing: {path:?}"
29- );
30- eprintln!("skipping: fixture missing: {path:?}");
31- false
32-}
33-
3412 /// Every syncframe of an AC-3 or E-AC-3 stream without dependent substreams.
3513 fn frames(data: &[u8]) -> Vec<&[u8]> {
3614 let mut out = Vec::new();
@@ -95,10 +73,7 @@ fn decode_packet_bytes(packets: &[&[u8]]) -> (Vec<u8>, u64) {
9573
9674 #[test]
9775 fn ac3_packets_of_two_and_three_syncframes_decode_to_their_frames() {
98- let path = fixtures().join("ac3-5.1-48000.ac3");
99- if !present(&path) {
100- return;
101- }
76+ let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3");
10277 let data = std::fs::read(&path).expect("fixture");
10378 let all = frames(&data);
10479 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() {
11287
11388 #[test]
11489 fn eac3_packets_of_two_and_three_syncframes_decode_to_their_frames() {
115- let path = fixtures().join("eac3-5.1-48000.eac3");
116- if !present(&path) {
117- return;
118- }
90+ let path = ec_testkit::fixture("audio/eac3-5.1-48000.eac3");
11991 let data = std::fs::read(&path).expect("fixture");
12092 let all = frames(&data);
12193 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() {
130102 /// that carries several (7.1 DD+ assembled as 5.1 plus a dependent).
131103 #[test]
132104 fn e_ac3_dependent_packets_inside_a_multi_syncframe_packet_keep_their_channels() {
133- let path = fixtures().join("ac3dep-7.1-48000.eac3");
134- if !present(&path) {
135- return;
136- }
105+ let path = ec_testkit::fixture("audio/ac3dep-7.1-48000.eac3");
137106 let data = std::fs::read(&path).expect("fixture");
138107 let all = packets(&data);
139108 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()
150119 /// bare frames.
151120 #[test]
152121 fn padding_after_several_syncframes_is_ignored() {
153- let path = fixtures().join("ac3-5.1-48000.ac3");
154- if !present(&path) {
155- return;
156- }
122+ let path = ec_testkit::fixture("audio/ac3-5.1-48000.ac3");
157123 let data = std::fs::read(&path).expect("fixture");
158124 let all = frames(&data);
159125 let mut packet: Vec<u8> = all[..3].concat();
@@ -166,11 +132,8 @@ fn padding_after_several_syncframes_is_ignored() {
166132 /// A second frame of another channel layout cannot share one output frame.
167133 #[test]
168134 fn syncframes_of_different_layouts_in_one_packet_are_refused_by_name() {
169- let surround = fixtures().join("ac3-5.1-48000.ac3");
170- let stereo = fixtures().join("ac3-stereo-48000.ac3");
171- if !present(&surround) || !present(&stereo) {
172- return;
173- }
135+ let surround = ec_testkit::fixture("audio/ac3-5.1-48000.ac3");
136+ let stereo = ec_testkit::fixture("audio/ac3-stereo-48000.ac3");
174137 let a = std::fs::read(&surround).expect("fixture");
175138 let b = std::fs::read(&stereo).expect("fixture");
176139 let mut packet = frames(&a)[0].to_vec();
@@ -188,10 +151,7 @@ fn syncframes_of_different_layouts_in_one_packet_are_refused_by_name() {
188151 /// there and decoded by the packet call.
189152 #[test]
190153 fn decode_frame_still_takes_one_syncframe() {
191- let path = fixtures().join("ac3-stereo-48000.ac3");
192- if !present(&path) {
193- return;
194- }
154+ let path = ec_testkit::fixture("audio/ac3-stereo-48000.ac3");
195155 let data = std::fs::read(&path).expect("fixture");
196156 let all = frames(&data);
197157 let packet = [all[0], all[1]].concat();
crates/ec-ac3/tests/it/real_library.rsmodified+17 -120
@@ -1,23 +1,10 @@
1-//! AC-3 and E-AC-3 decode of the real files named in `real_library.toml`,
2-//! compared against ffmpeg.
3-//!
4-//! Local media only: the file list is the user's `real_library.toml` (path in
5-//! `EC_REAL_LIBRARY`, default `~/Documents/Code/Rust/edith/real_library.toml`).
6-//! Each entry whose first audio track is `ac3` or `eac3` has its first
7-//! `EC_REAL_SECONDS` seconds (default 20) of that track copied out as a raw
8-//! elementary stream (`-c copy`, no re-encode), decoded by `ec-ac3` and by
9-//! ffmpeg, and compared per channel. Entries that are missing on disk, or that
10-//! hold no AC-3 or E-AC-3 track, are skipped loudly. Without ffmpeg the whole
11-//! test skips.
121 //!
132 //! Gate: per-channel correlation >= 0.999 (the matrix floor), and the
143 //! exact-sample share and RMS delta are reported for each file.
154
165 use std::path::{Path, PathBuf};
17-use std::process::Command;
186
197 use ec_ac3::{Ac3Decoder, Options};
20-use crate::common::have_ffmpeg;
218
229 const MIN_CORR: f64 = 0.999;
2310 /// Reference RMS below which a channel counts as silent (-80 dBFS).
@@ -25,71 +12,8 @@ const SILENT_RMS: f64 = 1e-4;
2512 /// RMS delta ceiling on a silent channel: 1/30 of a 16-bit LSB.
2613 const SILENT_DELTA: f64 = 1e-6;
2714
28-fn library_toml() -> PathBuf {
29- if let Ok(p) = std::env::var("EC_REAL_LIBRARY") {
30- return PathBuf::from(p);
31- }
32- let home = std::env::var("HOME").unwrap_or_default();
33- PathBuf::from(home).join("Documents/Code/Rust/edith/real_library.toml")
34-}
35-
36-/// `key = "path"` lines of the TOML file, as (key, path). Only the flat form
37-/// the library file uses; comments and other lines are ignored.
38-fn entries(toml: &Path) -> Vec<(String, PathBuf)> {
39- let Ok(text) = std::fs::read_to_string(toml) else {
40- return Vec::new();
41- };
42- text.lines()
43- .filter_map(|line| {
44- let line = line.trim();
45- if line.starts_with('#') {
46- return None;
47- }
48- let (key, value) = line.split_once('=')?;
49- let value = value.trim().strip_prefix('"')?.strip_suffix('"')?;
50- Some((key.trim().to_string(), PathBuf::from(value)))
51- })
52- .collect()
53-}
54-
55-/// The codec and channel count of the file's first audio track.
56-fn first_audio(path: &Path) -> Option<(String, usize)> {
57- let out = Command::new("ffprobe")
58- .args([
59- "-v",
60- "error",
61- "-select_streams",
62- "a:0",
63- "-show_entries",
64- "stream=codec_name,channels",
65- "-of",
66- "csv=p=0",
67- ])
68- .arg(path)
69- .output()
70- .ok()?;
71- let text = String::from_utf8_lossy(&out.stdout);
72- let mut parts = text.trim().split(',');
73- Some((parts.next()?.to_string(), parts.next()?.parse().ok()?))
74-}
75-
76-/// Copies the first `seconds` of the first audio track to `out` as a raw
77-/// elementary stream of the same codec. Returns false when that fails.
78-fn extract(path: &Path, codec: &str, seconds: u32, out: &Path) -> bool {
79- let muxer = if codec == "eac3" { "eac3" } else { "ac3" };
80- Command::new("ffmpeg")
81- .args(["-v", "error", "-nostdin", "-y", "-i"])
82- .arg(path)
83- .args(["-map", "0:a:0", "-t", &seconds.to_string(), "-c", "copy", "-f", muxer])
84- .arg(out)
85- .status()
86- .map(|s| s.success())
87- .unwrap_or(false)
88-}
89-
90-/// ffmpeg's decode of the raw stream as interleaved `f32`.
9115 fn reference(path: &Path) -> Vec<f32> {
92- let out = Command::new("ffmpeg")
16+ let out = ec_testkit::ffmpeg()
9317 .args(["-v", "error", "-nostdin", "-i"])
9418 .arg(path)
9519 .args(["-f", "f32le", "-"])
@@ -103,10 +27,9 @@ fn reference(path: &Path) -> Vec<f32> {
10327 .collect()
10428 }
10529
106-/// Our decode of the raw stream (dither off, as in the matrix test) and the
10730 /// channel count.
10831 fn decode(path: &Path) -> (Vec<f32>, usize) {
109- let data = std::fs::read(path).expect("extracted stream");
32+ let data = std::fs::read(path).expect("fixture");
11033 let options = Options {
11134 dither: false,
11235 ..Options::default()
@@ -171,41 +94,17 @@ fn compare(a: &[f32], b: &[f32]) -> (f64, f64, usize, usize) {
17194 }
17295
17396 #[test]
174-fn real_library_ac3_and_eac3_match_ffmpeg() {
175- if !have_ffmpeg() {
176- eprintln!("skip: ffmpeg not on PATH");
177- return;
178- }
179- let toml = library_toml();
180- let seconds: u32 = std::env::var("EC_REAL_SECONDS")
181- .ok()
182- .and_then(|s| s.parse().ok())
183- .unwrap_or(20);
184- let work = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("real-library-ac3");
185- std::fs::create_dir_all(&work).expect("work dir");
186-
187- let mut checked = 0;
188- for (key, path) in entries(&toml) {
189- if !path.exists() {
190- eprintln!("skip {key}: {} not on disk", path.display());
191- continue;
192- }
193- let Some((codec, channels)) = first_audio(&path) else {
194- eprintln!("skip {key}: ffprobe found no audio track");
195- continue;
196- };
197- if codec != "ac3" && codec != "eac3" {
198- eprintln!("skip {key}: first audio track is {codec}, not AC-3 or E-AC-3");
199- continue;
200- }
201- let raw = work.join(format!("{key}.{codec}"));
202- assert!(extract(&path, &codec, seconds, &raw), "{key}: extract failed");
203-
204- let (ours, decoded_channels) = decode(&raw);
205- let theirs = reference(&raw);
206- assert_eq!(decoded_channels, channels, "{key}: channel count");
207- assert_eq!(ours.len(), theirs.len(), "{key}: sample count vs ffmpeg");
208- assert!(!ours.is_empty(), "{key}: nothing decoded");
97+fn fate_ac3_and_eac3_match_ffmpeg() {
98+ let files: Vec<PathBuf> = ec_testkit::fixtures("open/fate/ac3", "ac3")
99+ .into_iter()
100+ .chain(ec_testkit::fixtures("open/fate/eac3", "eac3"))
101+ .collect();
102+ for path in files {
103+ let name = path.file_name().unwrap().to_string_lossy().into_owned();
104+ let (ours, decoded_channels) = decode(&path);
105+ let theirs = reference(&path);
106+ assert_eq!(ours.len(), theirs.len(), "{name}: sample count vs ffmpeg");
107+ assert!(!ours.is_empty(), "{name}: nothing decoded");
209108
210109 let mut worst = 1.0f64;
211110 let mut worst_rms = 0.0f64;
@@ -215,7 +114,7 @@ fn real_library_ac3_and_eac3_match_ffmpeg() {
215114 let a: Vec<f32> = ours[ch..].iter().step_by(decoded_channels).copied().collect();
216115 let b: Vec<f32> = theirs[ch..].iter().step_by(decoded_channels).copied().collect();
217116 let (corr, rms, exact, n) = compare(&a, &b);
218- eprintln!("{key} {codec} ch{ch}: corr {corr:.6} rms {rms:.3e} exact {exact}/{n}");
117+ eprintln!("{name} ch{ch}: corr {corr:.6} rms {rms:.3e} exact {exact}/{n}");
219118 // A channel whose reference is numerically silent (an LFE that
220119 // carries nothing but rounding) has no meaningful correlation, so
221120 // it is gated on RMS against one 16-bit LSB / 30 instead.
@@ -223,9 +122,9 @@ fn real_library_ac3_and_eac3_match_ffmpeg() {
223122 / b.len().max(1) as f64)
224123 .sqrt();
225124 if ref_rms < SILENT_RMS {
226- assert!(rms <= SILENT_DELTA, "{key} ch{ch}: silent-channel RMS delta {rms:.3e}");
125+ assert!(rms <= SILENT_DELTA, "{name} ch{ch}: silent-channel RMS delta {rms:.3e}");
227126 } else {
228- assert!(corr >= MIN_CORR, "{key} ch{ch}: correlation {corr:.6}");
127+ assert!(corr >= MIN_CORR, "{name} ch{ch}: correlation {corr:.6}");
229128 }
230129 worst = worst.min(corr);
231130 worst_rms = worst_rms.max(rms);
@@ -233,10 +132,8 @@ fn real_library_ac3_and_eac3_match_ffmpeg() {
233132 total += n;
234133 }
235134 eprintln!(
236- "RESULT {key} {codec} {decoded_channels}ch {seconds}s: min corr {worst:.6}, max rms {worst_rms:.3e}, exact {:.4}%",
135+ "RESULT {name} {decoded_channels}ch: min corr {worst:.6}, max rms {worst_rms:.3e}, exact {:.4}%",
237136 100.0 * exact_total as f64 / total.max(1) as f64
238137 );
239- checked += 1;
240138 }
241- eprintln!("{checked} real-library AC-3/E-AC-3 entries checked");
242139 }
crates/ec-alac/Cargo.tomlmodified+1 -0
@@ -12,3 +12,4 @@ ec-core = { workspace = true }
1212 [dev-dependencies]
1313 ec-mp4 = { workspace = true }
1414 ec-riff = { workspace = true }
15+ec-testkit.workspace = true
crates/ec-alac/tests/encode.rsmodified+9 -37
@@ -1,20 +1,14 @@
11 //! Round-trip the encoder through the decoder it was written to feed, then
2-//! through a real mp4 mux and (when the oracle is present) ffmpeg/ffprobe.
32
43 use std::fs::File;
54 use std::io::{BufReader, Cursor};
65 use std::path::{Path, PathBuf};
7-use std::process::Command;
86
97 use ec_alac::{AlacDecoder, AlacEncoder};
108 use ec_core::registry::{CodecId, Demuxer, Encoder, Muxer, StreamInfo};
119 use ec_core::timebase::TimeBase;
1210 use ec_core::Packet;
1311
14-fn fixtures() -> PathBuf {
15- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio")
16-}
17-
1812 /// A small deterministic PRNG so a "random data" test does not depend on an
1913 /// external crate: xorshift32.
2014 struct Rng(u32);
@@ -80,17 +74,15 @@ fn mux_to_m4a(enc: &AlacEncoder, channels: usize, sample_rate: u32, samples: &[i
8074 (dir, out_path)
8175 }
8276
83-/// ffmpeg's decode of `path` in raw format `fmt`, or None when no oracle is
84-/// installed.
85-fn ffmpeg_decode(path: &Path, fmt: &str) -> Option<Vec<u8>> {
86- let decode = Command::new("ffmpeg")
77+fn ffmpeg_decode(path: &Path, fmt: &str) -> Vec<u8> {
78+ let decode = ec_testkit::ffmpeg()
8779 .args(["-nostdin", "-v", "error", "-i"])
8880 .arg(path)
8981 .args(["-f", fmt, "-"])
9082 .output()
91- .ok()?;
83+ .expect("ffmpeg");
9284 assert!(decode.status.success(), "{}", String::from_utf8_lossy(&decode.stderr));
93- Some(decode.stdout)
85+ decode.stdout
9486 }
9587
9688 #[test]
@@ -99,11 +91,7 @@ fn twenty_four_bit_uses_byte_shift_when_cheaper() {
9991 // byte: exactly the shape a 24-bit master of 16-bit source material has,
10092 // and exactly what bytes_shifted exists for — the high bits alone
10193 // predict well, but folded together with the dither's noise they do not.
102- let path = fixtures().join("wav16-stereo-48000.wav");
103- if !path.exists() {
104- eprintln!("fixtures/audio absent (gitignored) — skipping");
105- return;
106- }
94+ let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav");
10795 let mut reader = ec_riff::WavReader::open(&path).expect("open wav");
10896 let spec = reader.spec();
10997 let mut rng = Rng(0xdead_beef);
@@ -161,7 +149,6 @@ fn twenty_four_bit_tonal_content_round_trips_bit_exactly() {
161149 let (dir, out_path) = mux_to_m4a(&enc, channels as usize, 48_000, samples);
162150 let got = ffmpeg_decode(&out_path, "s32le");
163151 std::fs::remove_dir_all(&dir).ok();
164- let Some(got) = got else { continue };
165152 let want: Vec<u8> = samples.iter().flat_map(|&s| (s << 8).to_le_bytes()).collect();
166153 assert!(got == want, "{channels}ch 24-bit tone, shift={allow_shift}: reference decode differs");
167154 }
@@ -182,11 +169,7 @@ fn escape_frames_round_trip_random_data() {
182169
183170 #[test]
184171 fn real_audio_round_trips_and_compresses() {
185- let path = fixtures().join("wav16-stereo-48000.wav");
186- if !path.exists() {
187- eprintln!("fixtures/audio absent (gitignored) — skipping");
188- return;
189- }
172+ let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav");
190173 let mut reader = ec_riff::WavReader::open(&path).expect("open wav");
191174 let spec = reader.spec();
192175 let samples = reader.read_all_i32().expect("pcm");
@@ -207,11 +190,7 @@ fn real_audio_round_trips_and_compresses() {
207190
208191 #[test]
209192 fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() {
210- let path = fixtures().join("wav16-stereo-48000.wav");
211- if !path.exists() {
212- eprintln!("fixtures/audio absent (gitignored) — skipping");
213- return;
214- }
193+ let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav");
215194 let mut reader = ec_riff::WavReader::open(&path).expect("open wav");
216195 let spec = reader.spec();
217196 let samples = reader.read_all_i32().expect("pcm");
@@ -245,11 +224,7 @@ fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() {
245224
246225 // The oracle: ffprobe reads the track back as alac at the right rate and
247226 // channel count, and ffmpeg's own decode matches the source exactly.
248- if Command::new("ffprobe").arg("-version").output().is_err() {
249- eprintln!("ffprobe absent — skipping oracle checks");
250- return;
251- }
252- let probe = Command::new("ffprobe")
227+ let probe = ec_testkit::ffprobe()
253228 .args([
254229 "-v", "error", "-select_streams", "a:0", "-show_entries",
255230 "stream=codec_name,sample_rate,channels",
@@ -263,7 +238,7 @@ fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() {
263238 assert!(info.contains(&format!("sample_rate={}", spec.sample_rate)), "{info}");
264239 assert!(info.contains(&format!("channels={}", spec.channels)), "{info}");
265240
266- let Some(stdout) = ffmpeg_decode(&out_path, "s16le") else { return };
241+ let stdout = ffmpeg_decode(&out_path, "s16le");
267242 let want: Vec<i16> = samples.iter().map(|&s| s as i16).collect();
268243 let got: Vec<i16> = stdout
269244 .as_chunks::<2>().0.iter()
@@ -275,8 +250,6 @@ fn muxed_stream_is_alac_at_the_right_rate_and_ffmpeg_agrees() {
275250 }
276251
277252
278-/// Encode through our encoder, decode through ours and (when installed) the
279-/// reference decoder via a real m4a; both must hand back `samples` exactly.
280253 fn round_trip_both_decoders(channels: u8, samples: &[i32], allow_shift: bool, what: &str) {
281254 let mut enc = AlacEncoder::new(48_000, channels, 24, 4096).expect("encoder");
282255 enc.set_byte_shift(allow_shift);
@@ -291,7 +264,6 @@ fn round_trip_both_decoders(channels: u8, samples: &[i32], allow_shift: bool, wh
291264 let (dir, out_path) = mux_to_m4a(&enc, channels as usize, 48_000, samples);
292265 let got = ffmpeg_decode(&out_path, "s32le");
293266 std::fs::remove_dir_all(&dir).ok();
294- let Some(got) = got else { return };
295267 let want: Vec<u8> = samples.iter().flat_map(|&s| (s << 8).to_le_bytes()).collect();
296268 assert!(got == want, "{what}: {channels}ch 24-bit, shift={allow_shift}: reference decode differs");
297269 }
crates/ec-alac/tests/oracle.rsmodified+6 -23
@@ -2,21 +2,14 @@
22 //! same bytes ffmpeg's decoder produces, sample for sample, in the same channel
33 //! order.
44 //!
5-//! Fixtures come from `scripts/gen-fixtures.sh`; a missing one skips its row
6-//! rather than failing, so a checkout without generated fixtures still builds.
75
86 use std::fs::File;
97 use std::io::BufReader;
10-use std::path::{Path, PathBuf};
11-use std::process::Command;
8+use std::path::Path;
129
1310 use ec_alac::{AlacDecoder, MagicCookie};
1411 use ec_core::registry::{CodecId, Demuxer};
1512
16-fn fixtures() -> PathBuf {
17- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio")
18-}
19-
2013 /// Every sample of `path`'s ALAC track, interleaved, as this crate decodes it.
2114 fn decode(path: &Path) -> (MagicCookie, Vec<i32>) {
2215 let mut demuxer =
@@ -43,7 +36,7 @@ fn decode(path: &Path) -> (MagicCookie, Vec<i32>) {
4336
4437 /// ffmpeg's own decode of the same file, in the raw format `fmt` names.
4538 fn ffmpeg(path: &Path, fmt: &str) -> Vec<u8> {
46- let out = Command::new("ffmpeg")
39+ let out = ec_testkit::ffmpeg()
4740 .args(["-nostdin", "-v", "error", "-i"])
4841 .arg(path)
4942 .args(["-f", fmt, "-"])
@@ -71,10 +64,7 @@ fn every_alac_fixture_decodes_bit_exactly() {
7164 "alac24-mp4-stereo-48000.m4a",
7265 "alac24-mp4-5.1-48000.m4a",
7366 ] {
74- let path = fixtures().join(name);
75- if !path.exists() {
76- continue;
77- }
67+ let path = ec_testkit::fixture(&format!("audio/{name}"));
7868 let (cookie, got) = decode(&path);
7969 let (fmt, width) = match cookie.bit_depth <= 16 {
8070 true => ("s16le", 2),
@@ -102,17 +92,14 @@ fn every_alac_fixture_decodes_bit_exactly() {
10292 assert_eq!(bad, None, "{name}: first differing sample");
10393 checked += 1;
10494 }
105- assert!(checked > 0, "no ALAC fixtures found — run gen-fixtures.sh");
95+ assert!(checked > 0, "no ALAC fixtures found");
10696 eprintln!("alac oracle: {checked} fixtures bit-exact vs ffmpeg");
10797 }
10898
10999 /// A truncated frame is an error, not a panic — the fuzz floor in miniature.
110100 #[test]
111101 fn truncated_frames_are_refused_without_panicking() {
112- let path = fixtures().join("alac-mp4-stereo-44100.m4a");
113- if !path.exists() {
114- return;
115- }
102+ let path = ec_testkit::fixture("audio/alac-mp4-stereo-44100.m4a");
116103 let mut demuxer =
117104 ec_mp4::Mp4Demuxer::new(BufReader::new(File::open(&path).expect("open"))).expect("mp4");
118105 let stream = demuxer.streams()[0].clone();
@@ -135,10 +122,6 @@ fn truncated_frames_are_refused_without_panicking() {
135122 /// the checked-in fixtures (16-bit, or 24-bit with a shifted low byte) carry.
136123 #[test]
137124 fn reference_encoded_24_bit_tone_decodes_bit_exactly() {
138- if Command::new("ffmpeg").arg("-version").output().is_err() {
139- eprintln!("ffmpeg absent — skipping");
140- return;
141- }
142125 let dir = std::env::temp_dir().join(format!("ec-alac-tone-{}", std::process::id()));
143126 std::fs::create_dir_all(&dir).expect("tmp");
144127 let raw = dir.join("tone.raw");
@@ -154,7 +137,7 @@ fn reference_encoded_24_bit_tone_decodes_bit_exactly() {
154137 })
155138 .collect();
156139 std::fs::write(&raw, &pcm).expect("raw");
157- let enc = Command::new("ffmpeg")
140+ let enc = ec_testkit::ffmpeg()
158141 .args(["-nostdin", "-y", "-v", "error", "-f", "s32le", "-ar", "48000", "-ac", "2", "-i"])
159142 .arg(&raw)
160143 .args(["-c:a", "alac", "-sample_fmt", "s32p"])
crates/ec-amr/Cargo.tomlmodified+1 -0
@@ -12,3 +12,4 @@ ec-core = { workspace = true }
1212 [dev-dependencies]
1313 ec-mp4 = { workspace = true }
1414 ec-riff = { workspace = true }
15+ec-testkit.workspace = true
crates/ec-amr/fuzz/seed.shmodified+3 -2
@@ -1,6 +1,6 @@
11 #!/usr/bin/env bash
22 # seed.sh: fill fuzz/corpus/<target>/ with synthetic AMR-NB files, one per mode.
3-# Needs ffmpeg with libopencore_amrnb. fuzz_container gets each .amr as-is;
3+# Needs the pinned ffmpeg (EC_FFMPEG) with libopencore_amrnb. fuzz_container gets each .amr as-is;
44 # fuzz_nb_decode gets it with the 6-byte magic stripped (ToC + frames).
55 # Corpus lives under fuzz/corpus, which is git-ignored.
66 set -euo pipefail
@@ -9,13 +9,14 @@ FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
99 CONT="$FUZZ_DIR/corpus/fuzz_container"
1010 DEC="$FUZZ_DIR/corpus/fuzz_nb_decode"
1111 mkdir -p "$CONT" "$DEC"
12+FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg}
1213 TMP=$(mktemp -d)
1314 trap 'rm -rf "$TMP"' EXIT
1415
1516 i=0
1617 for rate in 4750 5150 5900 6700 7400 7950 10200 12200; do
1718 f="$TMP/m$i.amr"
18- ffmpeg -nostdin -v error -f lavfi -i "sine=frequency=$((300 + 150 * i)):duration=2" \
19+ "$FF" -nostdin -v error -f lavfi -i "sine=frequency=$((300 + 150 * i)):duration=2" \
1920 -ar 8000 -ac 1 -c:a libopencore_amrnb -b:a "$rate" -f amr "$f"
2021 cp -f "$f" "$CONT/mode$i.amr"
2122 tail -c +7 "$f" > "$DEC/mode$i"
crates/ec-amr/tests/container_roundtrip.rsmodified+3 -16
@@ -5,7 +5,6 @@
55
66 use std::fs::File;
77 use std::io::BufReader;
8-use std::process::Command;
98
109 use ec_amr::container::{AmrDemuxer, Kind, probe};
1110 use ec_core::registry::{CodecId, Demuxer, MediaParameters, SeekMode};
@@ -15,7 +14,7 @@ const RATES: [u32; 8] = [4750, 5150, 5900, 6700, 7400, 7950, 10200, 12200];
1514 const PAYLOAD: [usize; 8] = [12, 13, 15, 17, 19, 20, 26, 31];
1615
1716 fn ffmpeg(args: &[&str]) -> bool {
18- Command::new("ffmpeg")
17+ ec_testkit::ffmpeg()
1918 .args(["-nostdin", "-v", "error", "-y"])
2019 .args(args)
2120 .status()
@@ -23,15 +22,6 @@ fn ffmpeg(args: &[&str]) -> bool {
2322 .unwrap_or(false)
2423 }
2524
26-fn skip(why: &str) -> bool {
27- assert!(
28- std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
29- "EC_REQUIRE_FIXTURES=1 but {why}"
30- );
31- eprintln!("SKIP: {why}");
32- true
33-}
34-
3525 fn drain(d: &mut dyn Demuxer) -> Vec<Vec<u8>> {
3626 let mut out = Vec::new();
3727 loop {
@@ -54,10 +44,7 @@ fn amr_3gp_mp4_agree_for_all_modes() {
5444 "-c:a", "libopencore_amrnb", "-b:a", &rate.to_string(), "-f", "amr",
5545 amr.to_str().unwrap(),
5646 ]);
57- if !enc {
58- skip("ffmpeg with libopencore_amrnb is not available");
59- return;
60- }
47+ assert!(enc, "ffmpeg with libopencore_amrnb is required");
6148 let bytes = std::fs::read(&amr).unwrap();
6249 assert_eq!(probe(&bytes), Some(Kind::Nb));
6350
@@ -82,7 +69,7 @@ fn amr_3gp_mp4_agree_for_all_modes() {
8269 }
8370 // ffprobe's own packet count for the same file (75 frames of 20 ms plus
8471 // the encoder's flush frame).
85- let probed = Command::new("ffprobe")
72+ let probed = ec_testkit::ffprobe()
8673 .args(["-v", "error", "-count_packets", "-select_streams", "a:0"])
8774 .args(["-show_entries", "stream=nb_read_packets", "-of", "csv=p=0"])
8875 .arg(&amr)
crates/ec-amr/tests/oracle.rsmodified+7 -18
@@ -3,11 +3,8 @@
33 //! reference this port follows) the output must be bit-exact; against ffmpeg's native `amrnb`
44 //! decoder the SNR is reported and must stay high.
55 //!
6-//! The fixtures are generated on the fly with ffmpeg from lavfi sources. Without ffmpeg (or
7-//! without libopencore) the tests skip, unless `EC_REQUIRE_FIXTURES=1`, which makes that a failure.
86
97 use std::path::{Path, PathBuf};
10-use std::process::Command;
118
129 use ec_amr::nb::bitstream::frame_bytes;
1310 use ec_amr::nb::decoder::AmrNbDecoder;
@@ -39,10 +36,6 @@ fn sources() -> Vec<(&'static str, String)> {
3936 ]
4037 }
4138
42-fn require() -> bool {
43- std::env::var("EC_REQUIRE_FIXTURES").map(|v| v == "1").unwrap_or(false)
44-}
45-
4639 fn workdir() -> PathBuf {
4740 let d = std::env::temp_dir().join(format!("ec-amr-oracle-{}", std::process::id()));
4841 std::fs::create_dir_all(&d).unwrap();
@@ -50,7 +43,7 @@ fn workdir() -> PathBuf {
5043 }
5144
5245 fn ffmpeg_ok() -> bool {
53- Command::new("ffmpeg")
46+ ec_testkit::ffmpeg()
5447 .args(["-hide_banner", "-h", "decoder=libopencore_amrnb"])
5548 .output()
5649 .map(|o| String::from_utf8_lossy(&o.stdout).contains("libopencore_amrnb"))
@@ -58,7 +51,7 @@ fn ffmpeg_ok() -> bool {
5851 }
5952
6053 fn run(args: &[&str]) -> Option<Vec<u8>> {
61- let out = Command::new("ffmpeg").args(["-nostdin", "-v", "error", "-y"]).args(args).output().ok()?;
54+ let out = ec_testkit::ffmpeg().args(["-nostdin", "-v", "error", "-y"]).args(args).output().ok()?;
6255 out.status.success().then_some(out.stdout)
6356 }
6457
@@ -132,18 +125,14 @@ fn first_diff(a: &[i16], b: &[i16]) -> Option<usize> {
132125 (0..a.len().min(b.len())).find(|&i| a[i] != b[i]).or((a.len() != b.len()).then_some(a.len().min(b.len())))
133126 }
134127
135-fn setup() -> Option<PathBuf> {
136- if !ffmpeg_ok() {
137- assert!(!require(), "EC_REQUIRE_FIXTURES=1 but ffmpeg with libopencore_amrnb is unavailable");
138- eprintln!("skipping: ffmpeg/libopencore_amrnb not available");
139- return None;
140- }
141- Some(workdir())
128+fn setup() -> PathBuf {
129+ assert!(ffmpeg_ok(), "ffmpeg with libopencore_amrnb is required");
130+ workdir()
142131 }
143132
144133 #[test]
145134 fn all_modes_bit_exact_vs_libopencore() {
146- let Some(dir) = setup() else { return };
135+ let dir = setup();
147136 let mut checked = 0;
148137 for dtx in [false, true] {
149138 for (rate, label) in MODES {
@@ -192,7 +181,7 @@ fn rng(state: &mut u64) -> u64 {
192181
193182 #[test]
194183 fn lost_and_bit_flipped_frames_vs_libopencore() {
195- let Some(dir) = setup() else { return };
184+ let dir = setup();
196185 let mut seed = 0x1234_5678_9abc_def1u64;
197186 for (rate, label) in MODES {
198187 let (sname, src) = &sources()[2];
crates/ec-amr/tests/wb_oracle.rsmodified+3 -19
@@ -2,13 +2,10 @@
22 //! the 3GPP TS 26.173 reference code: the output must match it sample for sample.
33 //!
44 //! Fixtures are made here with ffmpeg's `libvo_amrwbenc` from a synthetic source, one file per
5-//! mode, as `.awb` and as mp4 (`sawb`). A machine without those ffmpeg codecs skips loudly; with
6-//! `EC_REQUIRE_FIXTURES=1` that is a failure.
75
86 use std::fs::File;
97 use std::io::{BufReader, Cursor};
108 use std::path::{Path, PathBuf};
11-use std::process::Command;
129
1310 use ec_amr::container::AmrDemuxer;
1411 use ec_amr::wb::AmrWbDecoder;
@@ -18,7 +15,7 @@ const RATES: [u32; 9] = [6600, 8850, 12650, 14250, 15850, 18250, 19850, 23050, 2
1815 const PAYLOAD: [usize; 10] = [17, 23, 32, 36, 40, 46, 50, 58, 60, 5];
1916
2017 fn ffmpeg(args: &[&str]) -> Option<Vec<u8>> {
21- let out = Command::new("ffmpeg")
18+ let out = ec_testkit::ffmpeg()
2219 .args(["-nostdin", "-v", "error", "-y"])
2320 .args(args)
2421 .output()
@@ -26,15 +23,6 @@ fn ffmpeg(args: &[&str]) -> Option<Vec<u8>> {
2623 out.status.success().then_some(out.stdout)
2724 }
2825
29-fn skip(why: &str) -> bool {
30- assert!(
31- std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
32- "EC_REQUIRE_FIXTURES=1 but {why}"
33- );
34- eprintln!("SKIP: {why}");
35- true
36-}
37-
3826 struct Dir(PathBuf);
3927 impl Dir {
4028 fn new(tag: &str) -> Dir {
@@ -136,9 +124,7 @@ fn have_tools() -> bool {
136124
137125 #[test]
138126 fn every_mode_matches_the_reference_decoder_in_awb_and_mp4() {
139- if !have_tools() && skip("ffmpeg lacks libvo_amrwbenc/libopencore_amrwb") {
140- return;
141- }
127+ assert!(have_tools(), "ffmpeg lacks libvo_amrwbenc/libopencore_amrwb");
142128 let dir = Dir::new("modes");
143129 for rate in RATES {
144130 let awb = dir.path(&format!("m{rate}.awb"));
@@ -183,9 +169,7 @@ fn lcg(state: &mut u64) -> u8 {
183169
184170 #[test]
185171 fn comfort_noise_lost_and_corrupted_frames_match_the_reference() {
186- if !have_tools() && skip("ffmpeg lacks libvo_amrwbenc/libopencore_amrwb") {
187- return;
188- }
172+ assert!(have_tools(), "ffmpeg lacks libvo_amrwbenc/libopencore_amrwb");
189173 let dir = Dir::new("chaos");
190174 // Real frames of three modes, mixed with SID, lost and corrupted ones (quality bit kept set:
191175 // the reference wrapper ignores it).
scripts/aac-tables/make-he-fixtures.shmodified+1 -1
@@ -12,7 +12,7 @@ LIBDIR=${1:-}; OUT=$2; mkdir -p "$OUT"
1212 if [ -n "$LIBDIR" ]; then
1313 export LD_LIBRARY_PATH="$LIBDIR${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
1414 fi
15-FF="ffmpeg -v error -y -hide_banner"
15+FF="${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg} -v error -y -hide_banner"
1616 RATE=22050
1717
1818 # Mono: a tone plus a chirp (the chirp exercises the SBR patch range), with pink noise above it.
scripts/aac-tables/make-heaac-fixtures.shdeleted+0 -67
@@ -1,67 +0,0 @@
1-#!/usr/bin/env bash
2-# Deterministic HE-AAC v1 fixture matrix for tests/sbr_real_library.rs's
3-# `synthetic_heaac_matrix`: two sample-rate families (48000, 44100) x four
4-# bitrates (32k/48k/64k/96k) x two profiles (aac_he, aac_low control) = 16
5-# .m4a files, sweeping the SBR crossover (kx/k2) that bitrate controls
6-# without depending on any one real file's content.
7-#
8-# `ffmpeg`'s system libfdk_aac (the `fdk-aac-free` package) has SBR/PS
9-# encoding compiled out (patent-restricted tools) -- `-profile:a aac_he`
10-# fails with "Unable to set the AOT 5: Invalid config" against it. RPM
11-# Fusion's full `fdk-aac` package carries the SBR-capable encoder but
12-# installs to its OWN /usr/lib64/fdk-aac dir specifically so it doesn't
13-# clobber the system one; this script fetches (no root) and extracts just
14-# that .so into a local cache and points ffmpeg at it via
15-# LD_LIBRARY_PATH for the encode step only, never touching the system
16-# library.
17-set -euo pipefail
18-
19-SCRATCH="${EC_AAC_HEAAC_FIXTURES:-$(cd "$(dirname "$0")/../.." && pwd)/.cache/heaac-fixtures}"
20-mkdir -p "$SCRATCH"
21-CACHE="$SCRATCH/.fdk-aac-full"
22-mkdir -p "$CACHE"
23-
24-fdk_libdir="$CACHE/usr/lib64/fdk-aac"
25-if [ ! -f "$fdk_libdir/libfdk-aac.so.2" ]; then
26- echo "fetching SBR-capable libfdk-aac (no root, local cache only)..."
27- ( cd "$CACHE" && dnf download fdk-aac.x86_64 )
28- rpm_file=$(find "$CACHE" -maxdepth 1 -name 'fdk-aac-*.rpm' | head -1)
29- ( cd "$CACHE" && rpm2cpio "$rpm_file" | cpio -idm --quiet )
30-fi
31-export LD_LIBRARY_PATH="$fdk_libdir${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
32-
33-# Three summed sweeps 100 Hz -> 18 kHz over the full 30 s (phase(t) =
34-# 2*pi*(f0*t + (f1-f0)/(2T)*t^2), f0=100 f1=18000 T=30 ->
35-# (f1-f0)/(2T)=298.333), offset in phase per partial and per channel so
36-# left/right are correlated but not identical -- plus low-level pink noise
37-# (seeded, so every run of this script reproduces bit-identical fixtures).
38-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)"; }
39-L=$(sweep 0 1.047 2.094)
40-R=$(sweep 0.5 1.571 2.618)
41-
42-synth_source() {
43- local rate=$1 out=$2
44- ffmpeg -y -hide_banner -loglevel error -filter_complex "
45- aevalsrc=exprs='${L}|${R}':channel_layout=stereo:sample_rate=${rate}:duration=30 [tone];
46- anoisesrc=color=pink:amplitude=0.05:seed=42:sample_rate=${rate}:duration=30 [n0];
47- anoisesrc=color=pink:amplitude=0.05:seed=43:sample_rate=${rate}:duration=30 [n1];
48- [n0][n1] amerge=inputs=2 [noise];
49- [tone][noise] amix=inputs=2:normalize=0 [out]
50- " -map "[out]" -ar "$rate" -sample_fmt s16 -f wav "$out"
51-}
52-
53-for rate in 48000 44100; do
54- src="$SCRATCH/src_${rate}.wav"
55- [ -f "$src" ] || synth_source "$rate" "$src"
56- for br in 32k 48k 64k 96k; do
57- he="$SCRATCH/heaac_${rate}_${br}.m4a"
58- lc="$SCRATCH/lc_${rate}_${br}.m4a"
59- [ -f "$he" ] || ffmpeg -y -hide_banner -loglevel error -i "$src" \
60- -c:a libfdk_aac -profile:a aac_he -b:a "$br" "$he"
61- [ -f "$lc" ] || ffmpeg -y -hide_banner -loglevel error -i "$src" \
62- -c:a libfdk_aac -profile:a aac_low -b:a "$br" "$lc"
63- done
64-done
65-
66-echo "fixtures in $SCRATCH:"
67-ls "$SCRATCH"/*.m4a
scripts/aac-tables/make-ps-fixtures.shmodified+1 -1
@@ -8,7 +8,7 @@
88 set -euo pipefail
99 LIBDIR=$1; OUT=$2; mkdir -p "$OUT"
1010 export LD_LIBRARY_PATH="$LIBDIR${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
11-FF="ffmpeg -v error -y -hide_banner"
11+FF="${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg} -v error -y -hide_banner"
1212 for rate in 44100 48000; do
1313 # Sine pair: distinct tones per channel (strong, simple PS content).
1414 $FF -f lavfi -i "sine=440:d=2:r=$rate" -f lavfi -i "sine=660:d=2:r=$rate" \