forge
Explore
Log in

Don't you dare go Hollow

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

Browse files at this commit

83a04bfcbd82196d46db166d43693b43d622cfffAhmet Kaan GümüşParent: f3c77ef3627f59

33 changed files +393 -4528

Cargo.lockmodified+7 -0
@@ -450,6 +450,7 @@ name = "ec-dts"
450 version = "0.1.0"450 version = "0.1.0"
451 dependencies = [451 dependencies = [
452 "ec-core",452 "ec-core",
453+ "ec-testkit",
453 ]454 ]
454 455
455 [[package]]456 [[package]]
@@ -485,6 +486,7 @@ name = "ec-flac"
485 version = "0.1.0"486 version = "0.1.0"
486 dependencies = [487 dependencies = [
487 "ec-core",488 "ec-core",
489+ "ec-testkit",
488 ]490 ]
489 491
490 [[package]]492 [[package]]
@@ -585,6 +587,7 @@ version = "0.1.0"
585 dependencies = [587 dependencies = [
586 "ec-core",588 "ec-core",
587 "ec-dsp",589 "ec-dsp",
590+ "ec-testkit",
588 "wide",591 "wide",
589 ]592 ]
590 593
@@ -638,6 +641,7 @@ dependencies = [
638 "ec-core",641 "ec-core",
639 "ec-dsp",642 "ec-dsp",
640 "ec-ogg",643 "ec-ogg",
644+ "ec-testkit",
641 "rustfft",645 "rustfft",
642 "tracking-allocator",646 "tracking-allocator",
643 "wide",647 "wide",
@@ -650,6 +654,7 @@ dependencies = [
650 "ec-core",654 "ec-core",
651 "ec-mp4",655 "ec-mp4",
652 "ec-riff",656 "ec-riff",
657+ "ec-testkit",
653 ]658 ]
654 659
655 [[package]]660 [[package]]
@@ -720,6 +725,7 @@ version = "0.1.0"
720 dependencies = [725 dependencies = [
721 "ec-core",726 "ec-core",
722 "ec-matroska",727 "ec-matroska",
728+ "ec-testkit",
723 ]729 ]
724 730
725 [[package]]731 [[package]]
@@ -743,6 +749,7 @@ dependencies = [
743 "ec-core",749 "ec-core",
744 "ec-dsp",750 "ec-dsp",
745 "ec-ogg",751 "ec-ogg",
752+ "ec-testkit",
746 ]753 ]
747 754
748 [[package]]755 [[package]]
crates/ec-dts/Cargo.tomlmodified+3 -0
@@ -8,3 +8,6 @@ authors.workspace = true
8 8
9 [dependencies]9 [dependencies]
10 ec-core.workspace = true10 ec-core.workspace = true
11+
12+[dev-dependencies]
13+ec-testkit.workspace = true
crates/ec-dts/devscripts/cmp_all.shmodified+4 -2
@@ -2,7 +2,9 @@
2 # Decode each FATE sample with ec-dts and ffmpeg (-flags +bitexact, integer2 # Decode each FATE sample with ec-dts and ffmpeg (-flags +bitexact, integer
3 # path) and compare. Needs the dec example built (release).3 # path) and compare. Needs the dec example built (release).
4 set -u4 set -u
5-d=${1:-$HOME/dts-fate}5+d=${1:-${EC_FIXTURES:-$HOME/fixtures}/open/fate/dts}
6+FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg}
7+FP=$(dirname "$FF")/ffprobe
6 dec=${CARGO_TARGET_DIR:-target}/release/examples/dec8 dec=${CARGO_TARGET_DIR:-target}/release/examples/dec
7 here=$(cd "$(dirname "$0")" && pwd)9 here=$(cd "$(dirname "$0")" && pwd)
8 out=${TMPDIR:-/tmp}/dtscmp10 out=${TMPDIR:-/tmp}/dtscmp
@@ -13,7 +15,7 @@ for f in "$d"/*; do
13 echo "== $b"15 echo "== $b"
14 "$dec" "$f" "$out/$b.ours" 2>&1 | tail -316 "$dec" "$f" "$out/$b.ours" 2>&1 | tail -3
15 co="-core_only 1"; case "$b" in xch*|dts_es*|x96*) co="";; esac17 co="-core_only 1"; case "$b" in xch*|dts_es*|x96*) co="";; esac
16- ffmpeg -v error -y -flags +bitexact $co -i "$f" -f s32le "$out/$b.ref" 2>&1 | tail -218+ "$FF" -v error -y -flags +bitexact $co -i "$f" -f s32le "$out/$b.ref" 2>&1 | tail -2
17 nch=$(ffprobe -v error -show_entries stream=channels -of csv=p=0 "$f")19 nch=$(ffprobe -v error -show_entries stream=channels -of csv=p=0 "$f")
18 perm=""; [ "$nch" = 7 ] && perm="0,1,2,3,6,4,5"20 perm=""; [ "$nch" = 7 ] && perm="0,1,2,3,6,4,5"
19 skip=0; case "$b" in x96*) skip=2048;; *.dtshd) skip=1024;; esac21 skip=0; case "$b" in x96*) skip=2048;; *.dtshd) skip=1024;; esac
crates/ec-dts/devscripts/cmp_float.shmodified+4 -2
@@ -1,7 +1,9 @@
1 #!/usr/bin/env bash1 #!/usr/bin/env bash
2 # Compare ec-dts against ffmpeg's default (floating point) decoder path.2 # Compare ec-dts against ffmpeg's default (floating point) decoder path.
3 set -u3 set -u
4-d=${1:-$HOME/dts-fate}4+d=${1:-${EC_FIXTURES:-$HOME/fixtures}/open/fate/dts}
5+FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg}
6+FP=$(dirname "$FF")/ffprobe
5 dec=${CARGO_TARGET_DIR:-target}/release/examples/dec7 dec=${CARGO_TARGET_DIR:-target}/release/examples/dec
6 here=$(cd "$(dirname "$0")" && pwd)8 here=$(cd "$(dirname "$0")" && pwd)
7 out=${TMPDIR:-/tmp}/dtscmpf9 out=${TMPDIR:-/tmp}/dtscmpf
@@ -11,7 +13,7 @@ for f in "$d"/*.dtshd "$d"/dts_es.dts "$here"/../fixtures/*.dts; do
11 case "$b" in xll*|xbr*) continue;; esac13 case "$b" in xll*|xbr*) continue;; esac
12 co="-core_only 1"; case "$b" in xch*|dts_es*|x96*|*.dts) co="";; esac14 co="-core_only 1"; case "$b" in xch*|dts_es*|x96*|*.dts) co="";; esac
13 "$dec" "$f" "$out/$b.ours" 2>/dev/null15 "$dec" "$f" "$out/$b.ours" 2>/dev/null
14- ffmpeg -v error -y $co -i "$f" -f f32le "$out/$b.ref" 2>&1 | tail -216+ "$FF" -v error -y $co -i "$f" -f f32le "$out/$b.ref" 2>&1 | tail -2
15 nch=$(ffprobe -v error -show_entries stream=channels -of csv=p=0 "$f")17 nch=$(ffprobe -v error -show_entries stream=channels -of csv=p=0 "$f")
16 perm=""; [ "$nch" = 7 ] && perm="0,1,2,3,6,4,5"18 perm=""; [ "$nch" = 7 ] && perm="0,1,2,3,6,4,5"
17 skip=0; case "$b" in x96*) skip=2048;; *.dtshd) skip=1024;; esac19 skip=0; case "$b" in x96*) skip=2048;; *.dtshd) skip=1024;; esac
crates/ec-dts/devscripts/fate.shdeleted+0 -16
@@ -1,16 +0,0 @@
1-#!/usr/bin/env bash
2-# Fetch the public FFmpeg FATE DTS samples (dcadec conformance suite) into $1.
3-set -e
4-d=${1:-$HOME/dts-fate}
5-mkdir -p "$d"
6-cd "$d"
7-base=https://fate-suite.ffmpeg.org/dts
8-for f in dcadec-suite/core_51_24_48_768_0.dtshd dcadec-suite/core_51_24_48_768_1.dtshd \
9- dcadec-suite/x96_51_24_96_1509.dtshd dcadec-suite/x96_xch_61_24_96_3840.dtshd \
10- dcadec-suite/xbr_51_24_48_3840.dtshd dcadec-suite/xch_61_24_48_768.dtshd \
11- dcadec-suite/xll_51_24_48_768.dtshd dcadec-suite/xll_51_16_192_768_0.dtshd \
12- dts_es.dts master_audio_7.1_24bit.dts; do
13- b=$(basename "$f")
14- [ -s "$b" ] || curl -sfO "$base/$f"
15-done
16-ls "$d"
crates/ec-dts/tests/fate_vectors.rsmodified+24 -30
@@ -4,24 +4,11 @@
4 //! kHz, alone and with XCH), the core inside XBR and XLL (DTS-HD) streams and4 //! kHz, alone and with XCH), the core inside XBR and XLL (DTS-HD) streams and
5 //! a DTS-ES elementary stream.5 //! a DTS-ES elementary stream.
6 //!6 //!
7-//! The samples are not committed. Fetch them with
8-//! `devscripts/fate.sh <dir>` and point `EC_DTS_FATE` at the directory
9-//! (default `fixtures/audio/dts-fate` at the repository root). A missing
10-//! directory or ffmpeg skips loudly; the committed fixtures in
11-//! `ffmpeg_exact.rs` are the gate that fails on absence.
12 7
13-use std::path::{Path, PathBuf};8+use std::path::Path;
14-use std::process::Command;
15 9
16 use ec_dts::DtsDecoder;10 use ec_dts::DtsDecoder;
17 11
18-fn dir() -> PathBuf {
19- match std::env::var("EC_DTS_FATE") {
20- Ok(p) => PathBuf::from(p),
21- Err(_) => Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/audio/dts-fate"),
22- }
23-}
24-
25 /// The STRMDATA chunk of a `.dtshd` file, or the whole buffer.12 /// The STRMDATA chunk of a `.dtshd` file, or the whole buffer.
26 fn strmdata(buf: &[u8]) -> &[u8] {13 fn strmdata(buf: &[u8]) -> &[u8] {
27 if !buf.starts_with(b"DTSHDHDR") {14 if !buf.starts_with(b"DTSHDHDR") {
@@ -67,13 +54,22 @@ fn decode_ours(data: &[u8]) -> (Vec<i32>, usize, u32) {
67 }54 }
68 55
69 fn decode_ffmpeg(path: &Path, core_only: bool) -> Vec<i32> {56 fn decode_ffmpeg(path: &Path, core_only: bool) -> Vec<i32> {
70- let mut cmd = Command::new("ffmpeg");57+ let mut cmd = ec_testkit::ffmpeg();
71 cmd.args(["-v", "error", "-nostdin", "-flags", "+bitexact"]);58 cmd.args(["-v", "error", "-nostdin", "-flags", "+bitexact"]);
72 if core_only {59 if core_only {
73 cmd.args(["-core_only", "1"]);60 cmd.args(["-core_only", "1"]);
74 }61 }
75- let out = cmd.arg("-i").arg(path).args(["-f", "s32le", "-"]).output().unwrap();62+ let out = cmd
76- assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));63+ .arg("-i")
64+ .arg(path)
65+ .args(["-f", "s32le", "-"])
66+ .output()
67+ .unwrap();
68+ assert!(
69+ out.status.success(),
70+ "{}",
71+ String::from_utf8_lossy(&out.stderr)
72+ );
77 out.stdout73 out.stdout
78 .chunks_exact(4)74 .chunks_exact(4)
79 .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) >> 8)75 .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) >> 8)
@@ -82,12 +78,6 @@ fn decode_ffmpeg(path: &Path, core_only: bool) -> Vec<i32> {
82 78
83 #[test]79 #[test]
84 fn fate_vectors_are_bit_exact_against_ffmpeg() {80 fn fate_vectors_are_bit_exact_against_ffmpeg() {
85- let d = dir();
86- let ffmpeg = Command::new("ffmpeg").arg("-version").output().is_ok();
87- if !d.is_dir() || !ffmpeg {
88- eprintln!("skipping: FATE samples ({}) or ffmpeg missing", d.display());
89- return;
90- }
91 // (file, ffmpeg -core_only, leading samples ffmpeg trims from .dtshd)81 // (file, ffmpeg -core_only, leading samples ffmpeg trims from .dtshd)
92 let cases = [82 let cases = [
93 ("core_51_24_48_768_0.dtshd", true, 1024),83 ("core_51_24_48_768_0.dtshd", true, 1024),
@@ -101,16 +91,17 @@ fn fate_vectors_are_bit_exact_against_ffmpeg() {
101 ];91 ];
102 let mut ran = 0;92 let mut ran = 0;
103 for (name, core_only, skip) in cases {93 for (name, core_only, skip) in cases {
104- let path = d.join(name);94+ let path = ec_testkit::fixture(&format!("open/fate/dts/{name}"));
105- let Ok(raw) = std::fs::read(&path) else {95+ let raw = std::fs::read(&path).expect("read fixture");
106- eprintln!("skipping {name}: not present");
107- continue;
108- };
109 let (ours, ch, rate) = decode_ours(strmdata(&raw));96 let (ours, ch, rate) = decode_ours(strmdata(&raw));
110 let reference = decode_ffmpeg(&path, core_only);97 let reference = decode_ffmpeg(&path, core_only);
111 // ours is front-to-back; ffmpeg puts the back centre of a 6.1 stream98 // ours is front-to-back; ffmpeg puts the back centre of a 6.1 stream
112 // before the side surrounds.99 // before the side surrounds.
113- let perm: Vec<usize> = if ch == 7 { vec![0, 1, 2, 3, 6, 4, 5] } else { (0..ch).collect() };100+ let perm: Vec<usize> = if ch == 7 {
101+ vec![0, 1, 2, 3, 6, 4, 5]
102+ } else {
103+ (0..ch).collect()
104+ };
114 let ours: Vec<i32> = ours105 let ours: Vec<i32> = ours
115 .chunks_exact(ch)106 .chunks_exact(ch)
116 .skip(skip)107 .skip(skip)
@@ -119,7 +110,10 @@ fn fate_vectors_are_bit_exact_against_ffmpeg() {
119 assert_eq!(ours.len(), reference.len(), "{name}: sample count");110 assert_eq!(ours.len(), reference.len(), "{name}: sample count");
120 let bad = ours.iter().zip(&reference).position(|(a, b)| a != b);111 let bad = ours.iter().zip(&reference).position(|(a, b)| a != b);
121 assert_eq!(bad, None, "{name}: first mismatch at {bad:?}");112 assert_eq!(bad, None, "{name}: first mismatch at {bad:?}");
122- eprintln!("{name}: {ch} ch {rate} Hz {} samples/ch bit-exact", ours.len() / ch);113+ eprintln!(
114+ "{name}: {ch} ch {rate} Hz {} samples/ch bit-exact",
115+ ours.len() / ch
116+ );
123 ran += 1;117 ran += 1;
124 }118 }
125 eprintln!("{ran} FATE vectors compared");119 eprintln!("{ran} FATE vectors compared");
crates/ec-dts/tests/ffmpeg_exact.rsmodified+34 -29
@@ -6,15 +6,11 @@
6 //! The fixtures are made with ffmpeg's own DTS encoder (`-c:a dca -strict6 //! The fixtures are made with ffmpeg's own DTS encoder (`-c:a dca -strict
7 //! -2`): stereo and mono tones, a mono sweep at 32 kHz, 5.1 tones at 44.17 //! -2`): stereo and mono tones, a mono sweep at 32 kHz, 5.1 tones at 44.1
8 //! kHz and 5.1 noise with ADPCM at 48 kHz. Each is decoded here and by8 //! kHz and 5.1 noise with ADPCM at 48 kHz. Each is decoded here and by
9-//! ffmpeg and every 24-bit sample must be equal. ffmpeg is test tooling and
10-//! is driven through `std::process`; without it the comparison skips loudly.
11-//! The fixtures themselves are required: a missing one fails.
12 //!9 //!
13 //! The 14-bit and little-endian stream layouts are derived from the same10 //! The 14-bit and little-endian stream layouts are derived from the same
14 //! fixtures here and must decode to identical samples.11 //! fixtures here and must decode to identical samples.
15 12
16 use std::path::{Path, PathBuf};13 use std::path::{Path, PathBuf};
17-use std::process::Command;
18 14
19 use ec_core::{Decoder, Error};15 use ec_core::{Decoder, Error};
20 use ec_dts::{DtsDecoder, Options, StreamFormat};16 use ec_dts::{DtsDecoder, Options, StreamFormat};
@@ -35,14 +31,6 @@ fn fixture_names() -> Vec<String> {
35 v31 v
36 }32 }
37 33
38-fn have_ffmpeg() -> bool {
39- Command::new("ffmpeg")
40- .arg("-version")
41- .output()
42- .map(|o| o.status.success())
43- .unwrap_or(false)
44-}
45-
46 /// Split a BE16 elementary stream into its core frames.34 /// Split a BE16 elementary stream into its core frames.
47 fn frames(data: &[u8]) -> Vec<&[u8]> {35 fn frames(data: &[u8]) -> Vec<&[u8]> {
48 let mut out = Vec::new();36 let mut out = Vec::new();
@@ -83,7 +71,7 @@ fn decode_ours(frames: &[Vec<u8>]) -> (Vec<i32>, usize, u32) {
83 }71 }
84 72
85 fn decode_ffmpeg(path: &Path) -> Vec<i32> {73 fn decode_ffmpeg(path: &Path) -> Vec<i32> {
86- let out = Command::new("ffmpeg")74+ let out = ec_testkit::ffmpeg()
87 .args(["-v", "error", "-nostdin", "-flags", "+bitexact", "-i"])75 .args(["-v", "error", "-nostdin", "-flags", "+bitexact", "-i"])
88 .arg(path)76 .arg(path)
89 .args(["-f", "s32le", "-"])77 .args(["-f", "s32le", "-"])
@@ -144,10 +132,6 @@ fn to_layout(frame: &[u8], format: StreamFormat) -> Vec<u8> {
144 132
145 #[test]133 #[test]
146 fn fixtures_are_bit_exact_against_ffmpeg() {134 fn fixtures_are_bit_exact_against_ffmpeg() {
147- let ff = have_ffmpeg();
148- if !ff {
149- eprintln!("skip comparison: ffmpeg not on PATH");
150- }
151 for name in fixture_names() {135 for name in fixture_names() {
152 let path = fixtures().join(&name);136 let path = fixtures().join(&name);
153 let data = std::fs::read(&path).unwrap();137 let data = std::fs::read(&path).unwrap();
@@ -157,7 +141,6 @@ fn fixtures_are_bit_exact_against_ffmpeg() {
157 assert!(!ours.is_empty());141 assert!(!ours.is_empty());
158 let peak = ours.iter().map(|v| v.abs()).max().unwrap();142 let peak = ours.iter().map(|v| v.abs()).max().unwrap();
159 assert!(peak > 1000, "{name}: decoded silence (peak {peak})");143 assert!(peak > 1000, "{name}: decoded silence (peak {peak})");
160- if ff {
161 let reference = decode_ffmpeg(&path);144 let reference = decode_ffmpeg(&path);
162 assert_eq!(ours.len(), reference.len(), "{name}: sample count");145 assert_eq!(ours.len(), reference.len(), "{name}: sample count");
163 let bad = ours.iter().zip(&reference).position(|(a, b)| a != b);146 let bad = ours.iter().zip(&reference).position(|(a, b)| a != b);
@@ -173,11 +156,9 @@ fn fixtures_are_bit_exact_against_ffmpeg() {
173 );156 );
174 }157 }
175 }158 }
176-}
177 159
178 #[test]160 #[test]
179 fn stream_layouts_decode_identically() {161 fn stream_layouts_decode_identically() {
180- let ff = have_ffmpeg();
181 let tmp = std::env::temp_dir().join(format!("ec-dts-layouts-{}", std::process::id()));162 let tmp = std::env::temp_dir().join(format!("ec-dts-layouts-{}", std::process::id()));
182 std::fs::create_dir_all(&tmp).unwrap();163 std::fs::create_dir_all(&tmp).unwrap();
183 for name in fixture_names() {164 for name in fixture_names() {
@@ -191,23 +172,38 @@ fn stream_layouts_decode_identically() {
191 let h1 = ec_dts::parse_frame_header(&conv[0]).unwrap();172 let h1 = ec_dts::parse_frame_header(&conv[0]).unwrap();
192 assert_eq!(h1.format, fmt, "{name} {fmt:?}");173 assert_eq!(h1.format, fmt, "{name} {fmt:?}");
193 assert_eq!(174 assert_eq!(
194- (h0.sample_rate, h0.channels, h0.samples_per_frame, h0.frame_size),175+ (
195- (h1.sample_rate, h1.channels, h1.samples_per_frame, h1.frame_size),176+ h0.sample_rate,
177+ h0.channels,
178+ h0.samples_per_frame,
179+ h0.frame_size
180+ ),
181+ (
182+ h1.sample_rate,
183+ h1.channels,
184+ h1.samples_per_frame,
185+ h1.frame_size
186+ ),
196 "{name} {fmt:?}"187 "{name} {fmt:?}"
197 );188 );
198- assert_eq!(conv[0].len(), h1.stream_frame_size, "{name} {fmt:?}: stored size");189+ assert_eq!(
190+ conv[0].len(),
191+ h1.stream_frame_size,
192+ "{name} {fmt:?}: stored size"
193+ );
199 let (got, _, _) = decode_ours(&conv);194 let (got, _, _) = decode_ours(&conv);
200 assert_eq!(got, want, "{name} {fmt:?}: samples differ from BE16");195 assert_eq!(got, want, "{name} {fmt:?}: samples differ from BE16");
201- if ff {
202 let p = tmp.join(format!("{name}.{fmt:?}.dts"));196 let p = tmp.join(format!("{name}.{fmt:?}.dts"));
203 std::fs::write(&p, conv.concat()).unwrap();197 std::fs::write(&p, conv.concat()).unwrap();
204 let reference = decode_ffmpeg(&p);198 let reference = decode_ffmpeg(&p);
205 let n = want.len().min(reference.len());199 let n = want.len().min(reference.len());
206- assert!(n > want.len() / 2, "{name} {fmt:?}: ffmpeg decoded too little");200+ assert!(
201+ n > want.len() / 2,
202+ "{name} {fmt:?}: ffmpeg decoded too little"
203+ );
207 assert_eq!(&reference[..n], &want[..n], "{name} {fmt:?}: vs ffmpeg");204 assert_eq!(&reference[..n], &want[..n], "{name} {fmt:?}: vs ffmpeg");
208 }205 }
209 }206 }
210- }
211 let _ = std::fs::remove_dir_all(&tmp);207 let _ = std::fs::remove_dir_all(&tmp);
212 }208 }
213 209
@@ -233,7 +229,10 @@ fn header_api_states_the_stream() {
233 assert_eq!(&next[..4], &data[..4], "{name}: next frame");229 assert_eq!(&next[..4], &data[..4], "{name}: next frame");
234 }230 }
235 // Probe behaviour on junk and short input.231 // Probe behaviour on junk and short input.
236- assert!(matches!(ec_dts::parse_frame_header(&[0x7F, 0xFE]), Err(Error::NeedMore)));232+ assert!(matches!(
233+ ec_dts::parse_frame_header(&[0x7F, 0xFE]),
234+ Err(Error::NeedMore)
235+ ));
237 assert!(matches!(236 assert!(matches!(
238 ec_dts::parse_frame_header(&[0u8; 32]),237 ec_dts::parse_frame_header(&[0u8; 32]),
239 Err(Error::Corrupt { .. })238 Err(Error::Corrupt { .. })
@@ -341,7 +340,10 @@ fn dts_hd_substream_is_parsed_and_the_core_is_output() {
341 dec.decode_frame(&prev).unwrap();340 dec.decode_frame(&prev).unwrap();
342 let got = dec.decode_frame(&with).unwrap();341 let got = dec.decode_frame(&with).unwrap();
343 assert_eq!(got.data[0].len(), want.data[0].len());342 assert_eq!(got.data[0].len(), want.data[0].len());
344- assert!(got.data[0] == want.data[0], "HD frame must give the core samples");343+ assert!(
344+ got.data[0] == want.data[0],
345+ "HD frame must give the core samples"
346+ );
345 let i = dec.frame_info().unwrap();347 let i = dec.frame_info().unwrap();
346 assert!(i.hd_substream && i.xll, "XLL flagged: {i:?}");348 assert!(i.hd_substream && i.xll, "XLL flagged: {i:?}");
347 349
@@ -378,7 +380,10 @@ fn damaged_streams_never_panic() {
378 errors += 1;380 errors += 1;
379 }381 }
380 }382 }
381- assert!(errors > 0, "corruption should be noticed at least sometimes");383+ assert!(
384+ errors > 0,
385+ "corruption should be noticed at least sometimes"
386+ );
382 // And the decoder still works on a clean frame afterwards.387 // And the decoder still works on a clean frame afterwards.
383 dec.reset();388 dec.reset();
384 dec.decode_frame(fr[0]).unwrap();389 dec.decode_frame(fr[0]).unwrap();
crates/ec-flac/Cargo.tomlmodified+3 -0
@@ -8,3 +8,6 @@ authors.workspace = true
8 8
9 [dependencies]9 [dependencies]
10 ec-core = { workspace = true }10 ec-core = { workspace = true }
11+
12+[dev-dependencies]
13+ec-testkit.workspace = true
crates/ec-flac/fuzz/seed.shmodified+2 -2
@@ -11,8 +11,8 @@ set -euo pipefail
11 11
12 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)12 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
13 ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd)13 ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd)
14-FIXTURES="$ROOT/fixtures"14+FIXTURES=${EC_FIXTURES:-$ROOT/fixtures}
15-[ -d "$FIXTURES/audio" ] || { echo "seed.sh: $FIXTURES/audio missing; run scripts/link-fixtures.sh" >&2; exit 2; }15+[ -d "$FIXTURES/audio" ] || { echo "seed.sh: $FIXTURES/audio missing; run scripts/fixtures.sh" >&2; exit 2; }
16 XIPH="$FIXTURES/vectors/flac-xiph/flac-test-files-main"16 XIPH="$FIXTURES/vectors/flac-xiph/flac-test-files-main"
17 [ -d "$XIPH" ] || { echo "seed.sh: $XIPH missing; run scripts/fetch-vectors.sh" >&2; exit 2; }17 [ -d "$XIPH" ] || { echo "seed.sh: $XIPH missing; run scripts/fetch-vectors.sh" >&2; exit 2; }
18 18
crates/ec-flac/tests/encode_matrix.rsmodified+14 -66
@@ -9,7 +9,6 @@
9 //! cargo test -p ec-flac --release --test encode_matrix -- --nocapture9 //! cargo test -p ec-flac --release --test encode_matrix -- --nocapture
10 10
11 use std::path::{Path, PathBuf};11 use std::path::{Path, PathBuf};
12-use std::process::Command;
13 12
14 use ec_flac::encode::{EncoderConfig, encode};13 use ec_flac::encode::{EncoderConfig, encode};
15 14
@@ -20,34 +19,6 @@ struct Source {
20 bits: u32,19 bits: u32,
21 }20 }
22 21
23-/// Fixture-presence probe for the encoder matrix corpus.
24-/// Returns whether the fixture is present, but never silently: under
25-/// `EC_REQUIRE_FIXTURES=1` an absent fixture is a hard failure naming the path
26-/// and the script that regenerates it, so a host whose fixture library drifted
27-/// reports RED instead of a green SKIP (class: gate-skips-on-its-own-failure;
28-/// model `have_ffmpeg` in crates/ec-av1/src/stream.rs, which was silently
29-/// short-circuited because the probe ran first in a compound `if`).
30-///
31-/// Order is load-bearing: probe, assert, return. Never merge the probe into
32-/// the same `if` as the escape.
33-fn require_fixture(path: &Path, generator: &str) -> bool {
34- let present = path.exists();
35- assert!(
36- present || std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
37- "EC_REQUIRE_FIXTURES=1 but fixture {} is absent -- regenerate with: {}",
38- path.display(),
39- generator
40- );
41- if !present {
42- eprintln!("SKIP: fixture {} absent", path.display());
43- }
44- present
45-}
46-
47-fn fixtures() -> PathBuf {
48- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
49-}
50-
51 /// A working directory keyed by test name: these tests are threads of one22 /// A working directory keyed by test name: these tests are threads of one
52 /// process, so a shared temp directory would have them deleting each other's23 /// process, so a shared temp directory would have them deleting each other's
53 /// files.24 /// files.
@@ -58,7 +29,7 @@ fn workdir(test: &str) -> PathBuf {
58 }29 }
59 30
60 fn probe(path: &Path) -> Option<Source> {31 fn probe(path: &Path) -> Option<Source> {
61- let out = Command::new("ffprobe")32+ let out = ec_testkit::ffprobe()
62 .args([33 .args([
63 "-v",34 "-v",
64 "error",35 "error",
@@ -71,7 +42,7 @@ fn probe(path: &Path) -> Option<Source> {
71 ])42 ])
72 .arg(path)43 .arg(path)
73 .output()44 .output()
74- .ok()?;45+ .expect("run ffprobe");
75 // Key=value, because ffprobe prints its own field order, not the requested46 // Key=value, because ffprobe prints its own field order, not the requested
76 // one — a positional parse silently swaps rate and channels.47 // one — a positional parse silently swaps rate and channels.
77 let text = String::from_utf8_lossy(&out.stdout);48 let text = String::from_utf8_lossy(&out.stdout);
@@ -100,7 +71,7 @@ fn probe(path: &Path) -> Option<Source> {
100 71
101 fn ffmpeg_pcm(path: &Path, bits: u32) -> Vec<u8> {72 fn ffmpeg_pcm(path: &Path, bits: u32) -> Vec<u8> {
102 let format = if bits <= 16 { "s16le" } else { "s32le" };73 let format = if bits <= 16 { "s16le" } else { "s32le" };
103- let out = Command::new("ffmpeg")74+ let out = ec_testkit::ffmpeg()
104 .args(["-v", "error", "-i"])75 .args(["-v", "error", "-i"])
105 .arg(path)76 .arg(path)
106 .args(["-f", format, "-"])77 .args(["-f", format, "-"])
@@ -135,13 +106,13 @@ fn samples_from_pcm(pcm: &[u8], bits: u32) -> Vec<i32> {
135 106
136 fn ffmpeg_flac_size(src: &Path, out: &Path) -> Option<u64> {107 fn ffmpeg_flac_size(src: &Path, out: &Path) -> Option<u64> {
137 let _ = std::fs::remove_file(out);108 let _ = std::fs::remove_file(out);
138- let status = Command::new("ffmpeg")109+ let status = ec_testkit::ffmpeg()
139 .args(["-v", "error", "-y", "-i"])110 .args(["-v", "error", "-y", "-i"])
140 .arg(src)111 .arg(src)
141 .args(["-c:a", "flac"])112 .args(["-c:a", "flac"])
142 .arg(out)113 .arg(out)
143 .status()114 .status()
144- .ok()?;115+ .expect("run ffmpeg");
145 match status.success() {116 match status.success() {
146 true => std::fs::metadata(out).ok().map(|m| m.len()),117 true => std::fs::metadata(out).ok().map(|m| m.len()),
147 false => None,118 false => None,
@@ -149,36 +120,23 @@ fn ffmpeg_flac_size(src: &Path, out: &Path) -> Option<u64> {
149 }120 }
150 121
151 fn matrix() -> Vec<Source> {122 fn matrix() -> Vec<Source> {
152- let audio = fixtures().join("audio");123+ let mut paths: Vec<PathBuf> = std::fs::read_dir(ec_testkit::root().join("audio"))
153- let vectors = fixtures().join("vectors/flac-xiph/flac-test-files-main/subset");124+ .expect("fixture audio directory")
154- let mut paths: Vec<PathBuf> = Vec::new();125+ .map(|e| e.expect("fixture entry").path())
155- // Probe first, assert inside the helper, and only then take the empty-list
156- // branch: under EC_REQUIRE_FIXTURES the assert fires instead of a silent
157- // skip that leaves every loop below running zero times.
158- if require_fixture(&audio, "scripts/gen-fixtures.sh") {
159- let entries = std::fs::read_dir(&audio)
160- .unwrap_or_else(|e| panic!("read fixture dir {}: {e}", audio.display()));
161- let mut found: Vec<PathBuf> = entries
162- .filter_map(|e| e.ok().map(|e| e.path()))
163 .filter(|p| {126 .filter(|p| {
164 let name = p.file_name().unwrap_or_default().to_string_lossy();127 let name = p.file_name().unwrap_or_default().to_string_lossy();
165 name.starts_with("flac-") || name.starts_with("wav16-")128 name.starts_with("flac-") || name.starts_with("wav16-")
166 })129 })
167 .collect();130 .collect();
168- found.sort();131+ paths.sort();
169- paths.append(&mut found);
170- }
171 // Depth coverage the generated fixtures do not have: 24- and 20-bit.132 // Depth coverage the generated fixtures do not have: 24- and 20-bit.
172- if require_fixture(&vectors, "scripts/fetch-vectors.sh") {
173 for name in [133 for name in [
174 "28 - high resolution audio, default settings.flac",134 "28 - high resolution audio, default settings.flac",
175 "37 - 20 bit per sample.flac",135 "37 - 20 bit per sample.flac",
176 ] {136 ] {
177- let p = vectors.join(name);137+ paths.push(ec_testkit::fixture(&format!(
178- if p.exists() {138+ "vectors/flac-xiph/flac-test-files-main/subset/{name}"
179- paths.push(p);139+ )));
180- }
181- }
182 }140 }
183 paths.iter().filter_map(|p| probe(p)).collect()141 paths.iter().filter_map(|p| probe(p)).collect()
184 }142 }
@@ -186,10 +144,6 @@ fn matrix() -> Vec<Source> {
186 #[test]144 #[test]
187 fn encoded_streams_decode_back_bit_exact_through_ffmpeg() {145 fn encoded_streams_decode_back_bit_exact_through_ffmpeg() {
188 let sources = matrix();146 let sources = matrix();
189- if sources.is_empty() {
190- eprintln!("skipped: fixtures not generated");
191- return;
192- }
193 // Non-empty floor: the loop below must run, not zero times.147 // Non-empty floor: the loop below must run, not zero times.
194 assert!(148 assert!(
195 sources.len() >= 5,149 sources.len() >= 5,
@@ -268,13 +222,7 @@ fn encoded_streams_decode_back_bit_exact_through_ffmpeg() {
268 222
269 #[test]223 #[test]
270 fn our_streams_survive_a_probe_and_state_their_shape() {224 fn our_streams_survive_a_probe_and_state_their_shape() {
271- // The 5.1 source this test needs is a named fixture, not a shape we hope the225+ let surround = ec_testkit::fixture("audio/flac-5.1-44100.flac");
272- // matrix happens to contain: probe it first so EC_REQUIRE_FIXTURES fails on
273- // a drifted library instead of skipping.
274- let surround = fixtures().join("audio/flac-5.1-44100.flac");
275- if !require_fixture(&surround, "scripts/gen-fixtures.sh") {
276- return;
277- }
278 let source = matrix()226 let source = matrix()
279 .into_iter()227 .into_iter()
280 .find(|s| s.channels == 6)228 .find(|s| s.channels == 6)
@@ -298,7 +246,7 @@ fn our_streams_survive_a_probe_and_state_their_shape() {
298 assert_eq!(probed.rate, source.rate);246 assert_eq!(probed.rate, source.rate);
299 assert_eq!(probed.bits, source.bits);247 assert_eq!(probed.bits, source.bits);
300 // `-v error` clean: ffmpeg must find nothing to complain about.248 // `-v error` clean: ffmpeg must find nothing to complain about.
301- let out_err = Command::new("ffmpeg")249+ let out_err = ec_testkit::ffmpeg()
302 .args(["-v", "error", "-i"])250 .args(["-v", "error", "-i"])
303 .arg(&out)251 .arg(&out)
304 .args(["-f", "null", "-"])252 .args(["-f", "null", "-"])
crates/ec-flac/tests/level_depth_parity.rsmodified+6 -4
@@ -26,7 +26,7 @@ use std::path::{Path, PathBuf};
26 use std::process::Command;26 use std::process::Command;
27 27
28 use ec_flac::decode::FlacReader;28 use ec_flac::decode::FlacReader;
29-use ec_flac::encode::{encode, EncoderConfig};29+use ec_flac::encode::{EncoderConfig, encode};
30 30
31 /// Largest accepted ratio of our size to ffmpeg's size at the matching level.31 /// Largest accepted ratio of our size to ffmpeg's size at the matching level.
32 const MARGIN: f64 = 1.05;32 const MARGIN: f64 = 1.05;
@@ -99,7 +99,7 @@ const CASES: [Case; 4] = [
99 ];99 ];
100 100
101 fn ffmpeg(args: &[&str]) {101 fn ffmpeg(args: &[&str]) {
102- let status = Command::new("ffmpeg")102+ let status = ec_testkit::ffmpeg()
103 .args(["-hide_banner", "-loglevel", "error", "-y"])103 .args(["-hide_banner", "-loglevel", "error", "-y"])
104 .args(args)104 .args(args)
105 .status()105 .status()
@@ -108,7 +108,7 @@ fn ffmpeg(args: &[&str]) {
108 }108 }
109 109
110 fn ffprobe_stream(path: &Path) -> (u32, u32, u32) {110 fn ffprobe_stream(path: &Path) -> (u32, u32, u32) {
111- let out = Command::new("ffprobe")111+ let out = ec_testkit::ffprobe()
112 .args([112 .args([
113 "-v",113 "-v",
114 "error",114 "error",
@@ -226,7 +226,9 @@ fn level_and_depth_parity_with_ffmpeg_flac() {
226 fs::create_dir_all(&dir).expect("create work dir");226 fs::create_dir_all(&dir).expect("create work dir");
227 227
228 println!();228 println!();
229- println!("| case | ec-flac level | ec-flac bytes | ffmpeg -compression_level | ffmpeg bytes | ratio | verdict |");229+ println!(
230+ "| case | ec-flac level | ec-flac bytes | ffmpeg -compression_level | ffmpeg bytes | ratio | verdict |"
231+ );
230 println!("|---|---|---|---|---|---|---|");232 println!("|---|---|---|---|---|---|---|");
231 233
232 let mut failures: Vec<String> = Vec::new();234 let mut failures: Vec<String> = Vec::new();
crates/ec-flac/tests/xiph_vectors.rsmodified+10 -56
@@ -5,54 +5,20 @@
5 //! [`ec_flac::decode::DecodedStream::to_pcm_bytes`] writes) and the two buffers5 //! [`ec_flac::decode::DecodedStream::to_pcm_bytes`] writes) and the two buffers
6 //! must be identical. Lossless codec, no tolerance.6 //! must be identical. Lossless codec, no tolerance.
7 //!7 //!
8-//! The corpus is fetched by `scripts/fetch-vectors.sh`; without it every test
9-//! here skips rather than fails, so a fresh clone still runs green.
10 //!8 //!
11 //! Run the tables:9 //! Run the tables:
12 //! cargo test -p ec-flac --release --test xiph_vectors -- --nocapture10 //! cargo test -p ec-flac --release --test xiph_vectors -- --nocapture
13 11
14 use std::path::{Path, PathBuf};12 use std::path::{Path, PathBuf};
15-use std::process::Command;
16 13
17 use ec_flac::checksum::md5_of_samples;14 use ec_flac::checksum::md5_of_samples;
18 use ec_flac::decode::FlacReader;15 use ec_flac::decode::FlacReader;
19 16
20-fn corpus(kind: &str) -> Option<Vec<PathBuf>> {17+fn corpus(kind: &str) -> Vec<PathBuf> {
21- let dir = Path::new(env!("CARGO_MANIFEST_DIR"))18+ ec_testkit::fixtures(
22- .join("../../fixtures/vectors/flac-xiph/flac-test-files-main")19+ &format!("vectors/flac-xiph/flac-test-files-main/{kind}"),
23- .join(kind);20+ "flac",
24- // A missing corpus made every gate below skip GREEN having decoded nothing21+ )
25- // — the "gate skips on its own failure" class. The root `fixtures/` tree is
26- // gitignored, so `git worktree add` hands every lane worktree a tree without
27- // it. `EC_REQUIRE_FIXTURES=1` turns that into a hard failure naming the
28- // exact path and the command that produces it; unset, the skip is kept and
29- // now says what it skipped. Set it in every batch run.
30- if !dir.is_dir() {
31- assert!(
32- std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
33- "the FLAC xiph {kind} corpus is missing at {} — these gates would prove \
34- nothing. A worktree has no gitignored root `fixtures/`: run \
35- scripts/link-fixtures.sh, or fetch it with scripts/fetch-vectors.sh.",
36- dir.display()
37- );
38- eprintln!(
39- "SKIP the FLAC xiph {kind} corpus is missing at {} — these gates proved \
40- nothing; run scripts/link-fixtures.sh, or fetch it with \
41- scripts/fetch-vectors.sh (or set EC_REQUIRE_FIXTURES=1 to make this a failure).",
42- dir.display()
43- );
44- return None;
45- }
46- let mut files: Vec<PathBuf> = std::fs::read_dir(&dir)
47- .ok()?
48- .filter_map(|e| e.ok().map(|e| e.path()))
49- .filter(|p| p.extension().is_some_and(|e| e == "flac"))
50- .collect();
51- files.sort();
52- match files.is_empty() {
53- true => None,
54- false => Some(files),
55- }
56 }22 }
57 23
58 /// Decode `path` with ffmpeg into the same raw layout our decoder writes.24 /// Decode `path` with ffmpeg into the same raw layout our decoder writes.
@@ -61,7 +27,7 @@ fn ffmpeg_pcm(path: &Path, bits_per_sample: u32) -> Result<Vec<u8>, String> {
61 true => "s16le",27 true => "s16le",
62 false => "s32le",28 false => "s32le",
63 };29 };
64- let out = Command::new("ffmpeg")30+ let out = ec_testkit::ffmpeg()
65 .args(["-v", "error", "-i"])31 .args(["-v", "error", "-i"])
66 .arg(path)32 .arg(path)
67 .args(["-f", format, "-"])33 .args(["-f", format, "-"])
@@ -82,10 +48,7 @@ fn name(path: &Path) -> String {
82 48
83 #[test]49 #[test]
84 fn subset_vectors_decode_bit_exact_against_ffmpeg() {50 fn subset_vectors_decode_bit_exact_against_ffmpeg() {
85- let Some(files) = corpus("subset") else {51+ let files = corpus("subset");
86- eprintln!("skipped: fixtures/vectors/flac-xiph not fetched");
87- return;
88- };
89 let mut failures = Vec::new();52 let mut failures = Vec::new();
90 let mut passed = 0;53 let mut passed = 0;
91 for path in &files {54 for path in &files {
@@ -153,10 +116,7 @@ fn subset_vectors_decode_bit_exact_against_ffmpeg() {
153 116
154 #[test]117 #[test]
155 fn uncommon_vectors_decode_bit_exact_or_refuse_by_name() {118 fn uncommon_vectors_decode_bit_exact_or_refuse_by_name() {
156- let Some(files) = corpus("uncommon") else {119+ let files = corpus("uncommon");
157- eprintln!("skipped: fixtures/vectors/flac-xiph not fetched");
158- return;
159- };
160 let mut failures = Vec::new();120 let mut failures = Vec::new();
161 for path in &files {121 for path in &files {
162 let bytes = std::fs::read(path).expect("read fixture");122 let bytes = std::fs::read(path).expect("read fixture");
@@ -188,10 +148,7 @@ fn uncommon_vectors_decode_bit_exact_or_refuse_by_name() {
188 148
189 #[test]149 #[test]
190 fn faulty_vectors_error_and_never_panic() {150 fn faulty_vectors_error_and_never_panic() {
191- let Some(files) = corpus("faulty") else {151+ let files = corpus("faulty");
192- eprintln!("skipped: fixtures/vectors/flac-xiph not fetched");
193- return;
194- };
195 // Faults our reader is expected to catch outright rather than decode past:152 // Faults our reader is expected to catch outright rather than decode past:
196 // these break the structure a decoder must trust.153 // these break the structure a decoder must trust.
197 let must_reject = ["06 - ", "07 - ", "08 - ", "09 - ", "11 - "];154 let must_reject = ["06 - ", "07 - ", "08 - ", "09 - ", "11 - "];
@@ -214,10 +171,7 @@ fn faulty_vectors_error_and_never_panic() {
214 171
215 #[test]172 #[test]
216 fn seek_table_positions_the_reader_at_a_frame() {173 fn seek_table_positions_the_reader_at_a_frame() {
217- let Some(files) = corpus("subset") else {174+ let files = corpus("subset");
218- eprintln!("skipped: fixtures/vectors/flac-xiph not fetched");
219- return;
220- };
221 // "48 - Extremely large SEEKTABLE" is the file with a seek table worth175 // "48 - Extremely large SEEKTABLE" is the file with a seek table worth
222 // exercising; any file carrying one proves the hook.176 // exercising; any file carrying one proves the hook.
223 let mut checked = 0;177 let mut checked = 0;
crates/ec-mp3/Cargo.tomlmodified+3 -0
@@ -10,3 +10,6 @@ authors.workspace = true
10 ec-core = { workspace = true }10 ec-core = { workspace = true }
11 ec-dsp = { workspace = true }11 ec-dsp = { workspace = true }
12 wide = { workspace = true }12 wide = { workspace = true }
13+
14+[dev-dependencies]
15+ec-testkit.workspace = true
crates/ec-mp3/fuzz/seed.shmodified+2 -1
@@ -12,9 +12,10 @@ here=$(cd -- "$(dirname -- "$0")" && pwd)
12 dst="$here/corpus/decode"12 dst="$here/corpus/decode"
13 mkdir -p "$dst"13 mkdir -p "$dst"
14 src="sine=frequency=440:duration=1"14 src="sine=frequency=440:duration=1"
15+FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg}
15 16
16 enc() { # enc <name> <codec> <ext> <ar> <ac> <bitrate> <format>17 enc() { # enc <name> <codec> <ext> <ar> <ac> <bitrate> <format>
17- ffmpeg -v error -y -f lavfi -i "$src" -c:a "$2" -ar "$4" -ac "$5" -b:a "$6" -f "$7" "$dst/$1.$3"18+ "$FF" -v error -y -f lavfi -i "$src" -c:a "$2" -ar "$4" -ac "$5" -b:a "$6" -f "$7" "$dst/$1.$3"
18 }19 }
19 20
20 enc mp2-mono-32k mp2 mp2 32000 1 64k mp221 enc mp2-mono-32k mp2 mp2 32000 1 64k mp2
crates/ec-mp3/tests/decode_matrix.rsmodified+7 -28
@@ -9,32 +9,13 @@
9 //! Run the table:9 //! Run the table:
10 //! cargo test -p ec-mp3 --release --test decode_matrix -- --nocapture10 //! cargo test -p ec-mp3 --release --test decode_matrix -- --nocapture
11 11
12-use std::path::{Path, PathBuf};12+use std::path::Path;
13-use std::process::Command;
14 use std::time::Instant;13 use std::time::Instant;
15 14
16 use ec_mp3::Mp3Reader;15 use ec_mp3::Mp3Reader;
17 16
18-fn fixtures() -> PathBuf {
19- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
20-}
21-
22-fn mp3_fixtures() -> Vec<PathBuf> {
23- let dir = fixtures().join("audio");
24- let Ok(entries) = std::fs::read_dir(&dir) else {
25- return Vec::new();
26- };
27- let mut out: Vec<PathBuf> = entries
28- .flatten()
29- .map(|e| e.path())
30- .filter(|p| p.extension().is_some_and(|e| e == "mp3"))
31- .collect();
32- out.sort();
33- out
34-}
35-
36 fn ffmpeg_decode(path: &Path) -> Option<(Vec<f32>, u32, usize)> {17 fn ffmpeg_decode(path: &Path) -> Option<(Vec<f32>, u32, usize)> {
37- let out = Command::new("ffmpeg")18+ let out = ec_testkit::ffmpeg()
38 .args(["-v", "error", "-i"])19 .args(["-v", "error", "-i"])
39 .arg(path)20 .arg(path)
40 .args(["-f", "f32le", "-"])21 .args(["-f", "f32le", "-"])
@@ -45,10 +26,12 @@ fn ffmpeg_decode(path: &Path) -> Option<(Vec<f32>, u32, usize)> {
45 }26 }
46 let samples = out27 let samples = out
47 .stdout28 .stdout
48- .as_chunks::<4>().0.iter()29+ .as_chunks::<4>()
30+ .0
31+ .iter()
49 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))32 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
50 .collect();33 .collect();
51- let probe = Command::new("ffprobe")34+ let probe = ec_testkit::ffprobe()
52 .args([35 .args([
53 "-v",36 "-v",
54 "error",37 "error",
@@ -122,11 +105,7 @@ fn best_alignment(got: &[f32], want: &[f32], channels: usize) -> (f64, usize) {
122 105
123 #[test]106 #[test]
124 fn decodes_every_fixture_like_ffmpeg() {107 fn decodes_every_fixture_like_ffmpeg() {
125- let files = mp3_fixtures();108+ let files = ec_testkit::fixtures("audio", "mp3");
126- if files.is_empty() {
127- eprintln!("no MP3 fixtures: run scripts/gen-fixtures.sh and scripts/gen-mp3-fixtures.sh");
128- return;
129- }
130 println!(109 println!(
131 "{:<34} {:>6} {:>3} {:>9} {:>9} {:>8}",110 "{:<34} {:>6} {:>3} {:>9} {:>9} {:>8}",
132 "fixture", "rate", "ch", "samples", "corr", "x rt"111 "fixture", "rate", "ch", "samples", "corr", "x rt"
crates/ec-mp3/tests/encode_matrix.rsmodified+45 -474
@@ -9,7 +9,6 @@
9 //! cargo test -p ec-mp3 --release --test encode_matrix -- --nocapture9 //! cargo test -p ec-mp3 --release --test encode_matrix -- --nocapture
10 10
11 use std::path::{Path, PathBuf};11 use std::path::{Path, PathBuf};
12-use std::process::Command;
13 12
14 use ec_mp3::{FrameHeader, Mp3Encoder, Mp3EncoderConfig};13 use ec_mp3::{FrameHeader, Mp3Encoder, Mp3EncoderConfig};
15 14
@@ -41,34 +40,6 @@ fn bar_for(name: &str, kbps: u32) -> f64 {
41 .fold(f64::INFINITY, f64::min)40 .fold(f64::INFINITY, f64::min)
42 }41 }
43 42
44-fn fixtures() -> PathBuf {
45- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
46-}
47-
48-/// Fixture-presence probe for the encoder matrix corpus.
49-/// Returns whether the fixture is present, but never silently: under
50-/// `EC_REQUIRE_FIXTURES=1` an absent fixture is a hard failure naming the path
51-/// and the script that regenerates it, so a host whose fixture library drifted
52-/// reports RED instead of a green SKIP (class: gate-skips-on-its-own-failure;
53-/// model `have_ffmpeg` in crates/ec-av1/src/stream.rs, which was silently
54-/// short-circuited because the probe ran first in a compound `if`).
55-///
56-/// Order is load-bearing: probe, assert, return. Never merge the probe into
57-/// the same `if` as the escape.
58-fn require_fixture(path: &Path, generator: &str) -> bool {
59- let present = path.exists();
60- assert!(
61- present || std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
62- "EC_REQUIRE_FIXTURES=1 but fixture {} is absent -- regenerate with: {}",
63- path.display(),
64- generator
65- );
66- if !present {
67- eprintln!("SKIP: fixture {} absent", path.display());
68- }
69- present
70-}
71-
72 fn workdir(test: &str) -> PathBuf {43 fn workdir(test: &str) -> PathBuf {
73 let dir = std::env::temp_dir().join(format!("ec-mp3-{}-{test}", std::process::id()));44 let dir = std::env::temp_dir().join(format!("ec-mp3-{}-{test}", std::process::id()));
74 std::fs::create_dir_all(&dir).expect("create work dir");45 std::fs::create_dir_all(&dir).expect("create work dir");
@@ -76,22 +47,26 @@ fn workdir(test: &str) -> PathBuf {
76 }47 }
77 48
78 /// Reads a WAV fixture as interleaved f32 plus its rate and channel count.49 /// Reads a WAV fixture as interleaved f32 plus its rate and channel count.
79-fn read_wav(path: &Path) -> Option<(Vec<f32>, u32, usize)> {50+fn read_wav(path: &Path) -> (Vec<f32>, u32, usize) {
80- let out = Command::new("ffmpeg")51+ let out = ec_testkit::ffmpeg()
81 .args(["-v", "error", "-i"])52 .args(["-v", "error", "-i"])
82 .arg(path)53 .arg(path)
83 .args(["-f", "f32le", "-"])54 .args(["-f", "f32le", "-"])
84 .output()55 .output()
85- .ok()?;56+ .expect("run ffmpeg");
86- if !out.status.success() {57+ assert!(
87- return None;58+ out.status.success(),
88- }59+ "ffmpeg could not read {}",
60+ path.display()
61+ );
89 let samples = out62 let samples = out
90 .stdout63 .stdout
91- .as_chunks::<4>().0.iter()64+ .as_chunks::<4>()
65+ .0
66+ .iter()
92 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))67 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
93 .collect();68 .collect();
94- let probe = Command::new("ffprobe")69+ let probe = ec_testkit::ffprobe()
95 .args([70 .args([
96 "-v",71 "-v",
97 "error",72 "error",
@@ -104,14 +79,18 @@ fn read_wav(path: &Path) -> Option<(Vec<f32>, u32, usize)> {
104 ])79 ])
105 .arg(path)80 .arg(path)
106 .output()81 .output()
107- .ok()?;82+ .expect("run ffprobe");
108 let text = String::from_utf8_lossy(&probe.stdout);83 let text = String::from_utf8_lossy(&probe.stdout);
109 let field = |key: &str| {84 let field = |key: &str| {
110 text.lines()85 text.lines()
111 .find_map(|l| l.strip_prefix(key)?.strip_prefix('='))86 .find_map(|l| l.strip_prefix(key)?.strip_prefix('='))
112 .and_then(|v| v.trim().parse::<u32>().ok())87 .and_then(|v| v.trim().parse::<u32>().ok())
113 };88 };
114- Some((samples, field("sample_rate")?, field("channels")? as usize))89+ (
90+ samples,
91+ field("sample_rate").expect("sample rate"),
92+ field("channels").expect("channels") as usize,
93+ )
115 }94 }
116 95
117 fn correlation(a: &[f32], b: &[f32]) -> f64 {96 fn correlation(a: &[f32], b: &[f32]) -> f64 {
@@ -151,51 +130,6 @@ fn aligned(got: &[f32], want: &[f32], channels: usize) -> (f64, usize) {
151 best130 best
152 }131 }
153 132
154-/// Worst short-window error energy, relative to the source, over the file.
155-///
156-/// Whole-file correlation cannot see pre-echo: quantisation noise smeared
157-/// backwards across a 576-sample granule before an attack is a few
158-/// milliseconds of audible hash inside a minute of otherwise clean signal, and
159-/// integrating over the minute divides it away. Measured on this crate, going
160-/// from one short block per 9196 granules to 526 of them moved whole-file
161-/// correlation by 0.00004 -- in the wrong direction -- while changing exactly
162-/// the thing short blocks exist to fix. So the sweep also reports the worst
163-/// window: error energy over source energy, in dB, over 20 ms windows,
164-/// which is the scale a transient's pre-echo lives on.
165-fn worst_window_db(got: &[f32], want: &[f32], offset: usize, channels: usize) -> f64 {
166- let window = 20 * 44100 / 1000 * channels;
167- let skip = 1152 * channels;
168- let n = (got.len() - offset).min(want.len());
169- let mut worst = f64::MIN;
170- let mut start = skip;
171- while start + window + skip <= n {
172- let (mut err, mut sig) = (0.0f64, 0.0f64);
173- for i in start..start + window {
174- let d = f64::from(got[offset + i]) - f64::from(want[i]);
175- err += d * d;
176- sig += f64::from(want[i]) * f64::from(want[i]);
177- }
178- // A window with no signal in it has no pre-echo to hide, and its
179- // ratio would be meaningless; the -60 dBFS gate skips digital silence
180- // and the fade-ins around it.
181- if sig / window as f64 > 1e-6 {
182- let db = 10.0 * (err / sig.max(1e-30)).log10();
183- if db > worst {
184- worst = db;
185- if std::env::var_os("EC_MP3_WORST_WHERE").is_some() {
186- eprintln!(
187- " worst so far {db:+.1} dB at {:.2} s, level {:.1} dBFS",
188- start as f64 / (44100.0 * channels as f64),
189- 10.0 * (sig / window as f64).log10()
190- );
191- }
192- }
193- }
194- start += window;
195- }
196- worst
197-}
198-
199 fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> {133 fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> {
200 let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {134 let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
201 bitrate_kbps: kbps,135 bitrate_kbps: kbps,
@@ -219,11 +153,8 @@ fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> {
219 /// so the gate is the quality those bytes carried.153 /// so the gate is the quality those bytes carried.
220 #[test]154 #[test]
221 fn cbr_quality_holds_its_floor() {155 fn cbr_quality_holds_its_floor() {
222- let path = fixtures().join("audio/wav16-stereo-48000.wav");156+ let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav");
223- let Some((pcm, rate, channels)) = read_wav(&path) else {157+ let (pcm, rate, channels) = read_wav(&path);
224- eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh");
225- return;
226- };
227 let bytes = encode(&pcm, rate, channels, 192);158 let bytes = encode(&pcm, rate, channels, 192);
228 let file = workdir("cbr").join("cbr192.mp3");159 let file = workdir("cbr").join("cbr192.mp3");
229 std::fs::write(&file, &bytes).unwrap();160 std::fs::write(&file, &bytes).unwrap();
@@ -243,7 +174,7 @@ fn cbr_quality_holds_its_floor() {
243 }174 }
244 175
245 fn decode(file: &Path) -> Vec<f32> {176 fn decode(file: &Path) -> Vec<f32> {
246- let out = Command::new("ffmpeg")177+ let out = ec_testkit::ffmpeg()
247 .args(["-v", "warning", "-i"])178 .args(["-v", "warning", "-i"])
248 .arg(file)179 .arg(file)
249 .args(["-f", "f32le", "-"])180 .args(["-f", "f32le", "-"])
@@ -255,7 +186,9 @@ fn decode(file: &Path) -> Vec<f32> {
255 String::from_utf8_lossy(&out.stderr)186 String::from_utf8_lossy(&out.stderr)
256 );187 );
257 out.stdout188 out.stdout
258- .as_chunks::<4>().0.iter()189+ .as_chunks::<4>()
190+ .0
191+ .iter()
259 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))192 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
260 .collect()193 .collect()
261 }194 }
@@ -282,11 +215,8 @@ fn encode_vbr(pcm: &[f32], rate: u32, channels: usize, quality: f32) -> Vec<u8>
282 #[test]215 #[test]
283 fn vbr_frames_vary_their_bitrate_index() {216 fn vbr_frames_vary_their_bitrate_index() {
284 let name = "mp3src-stereo-48000";217 let name = "mp3src-stereo-48000";
285- let path = fixtures().join(format!("audio/{name}.wav"));218+ let path = ec_testkit::fixture(&format!("audio/{name}.wav"));
286- let Some((pcm, rate, channels)) = read_wav(&path) else {219+ let (pcm, rate, channels) = read_wav(&path);
287- eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh");
288- return;
289- };
290 let bytes = encode_vbr(&pcm, rate, channels, 0.5);220 let bytes = encode_vbr(&pcm, rate, channels, 0.5);
291 // Walk the frame headers (MPEG-1, Layer III), skipping the Xing frame.221 // Walk the frame headers (MPEG-1, Layer III), skipping the Xing frame.
292 let table = [222 let table = [
@@ -319,7 +249,7 @@ fn vbr_frames_vary_their_bitrate_index() {
319 let work = workdir("vbr");249 let work = workdir("vbr");
320 let file = work.join("vbr.mp3");250 let file = work.join("vbr.mp3");
321 std::fs::write(&file, &bytes).unwrap();251 std::fs::write(&file, &bytes).unwrap();
322- let out = Command::new("ffmpeg")252+ let out = ec_testkit::ffmpeg()
323 .args(["-v", "warning", "-i"])253 .args(["-v", "warning", "-i"])
324 .arg(&file)254 .arg(&file)
325 .args(["-f", "f32le", "-"])255 .args(["-f", "f32le", "-"])
@@ -332,14 +262,16 @@ fn vbr_frames_vary_their_bitrate_index() {
332 );262 );
333 let decoded: Vec<f32> = out263 let decoded: Vec<f32> = out
334 .stdout264 .stdout
335- .as_chunks::<4>().0.iter()265+ .as_chunks::<4>()
266+ .0
267+ .iter()
336 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))268 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
337 .collect();269 .collect();
338 let corr = correlation(&decoded, &pcm);270 let corr = correlation(&decoded, &pcm);
339 let bar = bar_for(name, 192);271 let bar = bar_for(name, 192);
340 println!("vbr corr={corr:.5} bar={bar:.5}");272 println!("vbr corr={corr:.5} bar={bar:.5}");
341 assert!(corr >= bar, "corr {corr:.5} < bar {bar:.5}");273 assert!(corr >= bar, "corr {corr:.5} < bar {bar:.5}");
342- let probe = Command::new("ffprobe")274+ let probe = ec_testkit::ffprobe()
343 .args(["-v", "error", "-show_format"])275 .args(["-v", "error", "-show_format"])
344 .arg(&file)276 .arg(&file)
345 .output()277 .output()
@@ -355,11 +287,8 @@ fn vbr_frames_vary_their_bitrate_index() {
355 287
356 #[test]288 #[test]
357 fn vbr_mean_bitrate_tracks_quality_on_music() {289 fn vbr_mean_bitrate_tracks_quality_on_music() {
358- let path = fixtures().join("audio/wav16-stereo-48000.wav");290+ let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav");
359- let Some((pcm, rate, channels)) = read_wav(&path) else {291+ let (pcm, rate, channels) = read_wav(&path);
360- eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh");
361- return;
362- };
363 let mut previous = 0.0;292 let mut previous = 0.0;
364 for q in [0.25f32, 0.5, 0.75] {293 for q in [0.25f32, 0.5, 0.75] {
365 let bytes = encode_vbr(&pcm, rate, channels, q);294 let bytes = encode_vbr(&pcm, rate, channels, q);
@@ -383,38 +312,22 @@ fn vbr_mean_bitrate_tracks_quality_on_music() {
383 312
384 #[test]313 #[test]
385 fn encodes_above_the_incumbent_bar() {314 fn encodes_above_the_incumbent_bar() {
386- let dir = fixtures().join("audio");315+ let sources: Vec<PathBuf> = ec_testkit::fixtures("audio", "wav")
387- // Probe first, assert inside the helper, and only then take the empty-list316+ .into_iter()
388- // branch: under EC_REQUIRE_FIXTURES the assert fires instead of a silent
389- // skip that leaves every row below running zero times.
390- if !require_fixture(&dir, "scripts/gen-fixtures.sh") {
391- return;
392- }
393- let mut sources: Vec<PathBuf> = std::fs::read_dir(&dir)
394- .unwrap_or_else(|e| panic!("read fixture dir {}: {e}", dir.display()))
395- .filter_map(|e| e.ok().map(|e| e.path()))
396 .filter(|p| {317 .filter(|p| {
397- let name = p.file_name().map(|n| n.to_string_lossy().to_string());318+ let name = p.file_name().unwrap().to_string_lossy().to_string();
398- name.is_some_and(|n| n.starts_with("wav16-") || n.starts_with("mp3src-"))319+ (name.starts_with("wav16-") || name.starts_with("mp3src-"))
399- && p.extension().is_some_and(|e| e == "wav")320+ && (name.contains("mono") || name.contains("stereo"))
400 })321 })
401 .collect();322 .collect();
402- sources.sort();
403- sources.retain(|p| {
404- let name = p.file_name().unwrap().to_string_lossy().to_string();
405- name.contains("mono") || name.contains("stereo")
406- });
407 // The corpus is eight committed WAVs (four `mp3src-*`, four `wav16-*`),323 // The corpus is eight committed WAVs (four `mp3src-*`, four `wav16-*`),
408 // all produced by `scripts/gen-fixtures.sh`. Fewer than all eight means324 // all produced by `scripts/gen-fixtures.sh`. Fewer than all eight means
409 // the library drifted, not that the rows passed.325 // the library drifted, not that the rows passed.
410 assert!(326 assert!(
411 sources.len() >= 8,327 sources.len() >= 8,
412- "only {} of the 8 mp3 encoder-matrix WAV fixtures are present in {} -- \328+ "only {} of the 8 mp3 encoder-matrix WAV fixtures are present",
413- regenerate with: scripts/gen-fixtures.sh",329+ sources.len()
414- sources.len(),
415- dir.display()
416 );330 );
417- let mut decoded_rows = 0usize;
418 let work = workdir("encode");331 let work = workdir("encode");
419 println!(332 println!(
420 "{:<30} {:>5} {:>6} {:>3} {:>9} {:>8} {:>9}",333 "{:<30} {:>5} {:>6} {:>3} {:>9} {:>8} {:>9}",
@@ -422,10 +335,7 @@ fn encodes_above_the_incumbent_bar() {
422 );335 );
423 let mut failures = Vec::new();336 let mut failures = Vec::new();
424 for source in &sources {337 for source in &sources {
425- let Some((pcm, rate, channels)) = read_wav(source) else {338+ let (pcm, rate, channels) = read_wav(source);
426- continue;
427- };
428- decoded_rows += 1;
429 for kbps in BITRATES {339 for kbps in BITRATES {
430 let bar = bar_for(&source.file_name().unwrap().to_string_lossy(), kbps);340 let bar = bar_for(&source.file_name().unwrap().to_string_lossy(), kbps);
431 let bytes = encode(&pcm, rate, channels, kbps);341 let bytes = encode(&pcm, rate, channels, kbps);
@@ -434,7 +344,7 @@ fn encodes_above_the_incumbent_bar() {
434 source.file_stem().unwrap().to_string_lossy()344 source.file_stem().unwrap().to_string_lossy()
435 ));345 ));
436 std::fs::write(&path, &bytes).expect("write encoded file");346 std::fs::write(&path, &bytes).expect("write encoded file");
437- let out = Command::new("ffmpeg")347+ let out = ec_testkit::ffmpeg()
438 .args(["-v", "warning", "-i"])348 .args(["-v", "warning", "-i"])
439 .arg(&path)349 .arg(&path)
440 .args(["-f", "f32le", "-"])350 .args(["-f", "f32le", "-"])
@@ -446,7 +356,9 @@ fn encodes_above_the_incumbent_bar() {
446 }356 }
447 let decoded: Vec<f32> = out357 let decoded: Vec<f32> = out
448 .stdout358 .stdout
449- .as_chunks::<4>().0.iter()359+ .as_chunks::<4>()
360+ .0
361+ .iter()
450 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))362 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
451 .collect();363 .collect();
452 // With the Info tag's delay and padding honoured, ffmpeg hands364 // With the Info tag's delay and padding honoured, ffmpeg hands
@@ -491,200 +403,9 @@ fn encodes_above_the_incumbent_bar() {
491 }403 }
492 }404 }
493 }405 }
494- // A present-but-unreadable WAV takes the `read_wav` skip above, so the
495- // corpus count alone would leave this green having measured nothing.
496- assert!(
497- decoded_rows == sources.len(),
498- "only {decoded_rows} of {} fixtures decoded; a present fixture that \
499- ffmpeg cannot read is a broken fixture, not a passing row",
500- sources.len()
501- );
502- assert!(failures.is_empty(), "{failures:#?}");
503-}
504-
505-// ---------------------------------------------------------------------------
506-// The live reference: LAME on the user's own library, at matched constant
507-// bitrate. `encodes_above_the_incumbent_bar` measures against a frozen number
508-// from the crate this one replaces; that number cannot notice LAME moving, and
509-// the fixtures it covers are synthetic. This one encodes the same seconds of
510-// the same file with both encoders at the same bitrate and correlates each
511-// against the samples that went in.
512-// ---------------------------------------------------------------------------
513-
514-/// Sources for [`real_library_sweep_vs_lame`], the same list the vorbis and
515-/// opus library gates use.
516-const LIBRARY: [(&str, &str); 7] = [
517- ("nik", "~/Music/reeln.mp4"),
518- ("reelo", "~/Music/reelo.mp3"),
519- ("her", "~/Music/reeli.mp3"),
520- ("reell", "~/Music/reell.mp4"),
521- ("reelm", "~/Music/reelm.wav"),
522- ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),
523- (
524- "hein",
525- "~/Downloads/reelm.mp3",
526- ),
527-];
528-
529-/// How much worse than LAME a row's worst 20 ms window may be, in dB.
530-///
531-/// The gap was 12.6 dB when this floor went in, on the two spoken-word
532-/// sources; mid/side stereo and the demand-weighted frame split closed it.
533-/// Every row now beats libmp3lame's worst window except hein at 192 kbit/s,
534-/// which sits 0.2 dB behind, so the floor is one decibel.
535-const WORST_WINDOW_EXCESS_DB: f64 = 1.0;
536-
537-/// How far under LAME a row may sit before the sweep fails, in correlation.
538-///
539-/// The first measurement put every row between -0.00103 and +0.00142. All
540-/// fourteen are now ahead of libmp3lame, the thinnest being hein at 192
541-/// kbit/s at +0.00002, so the floor is zero: a row falling behind the
542-/// reference at all is the regression.
543-const LAME_CORR_FLOOR: f64 = 0.0;
544-
545-fn expand(path: &str) -> PathBuf {
546- PathBuf::from(match path.strip_prefix("~/") {
547- Some(rest) => format!(
548- "{}/{rest}",
549- std::env::var("HOME").unwrap_or_else(|_| "/home".into())
550- ),
551- None => path.to_string(),
552- })
553-}
554-
555-/// Decodes `seconds` of a source to interleaved stereo f32 at 44.1 kHz.
556-fn decode_source(path: &Path, seconds: u32) -> Option<Vec<f32>> {
557- let out = Command::new("ffmpeg")
558- .args(["-v", "error", "-i"])
559- .arg(path)
560- .args([
561- "-vn",
562- "-t",
563- &seconds.to_string(),
564- "-ac",
565- "2",
566- "-ar",
567- "44100",
568- "-f",
569- "f32le",
570- "-",
571- ])
572- .output()
573- .ok()?;
574- if !out.status.success() || out.stdout.is_empty() {
575- return None;
576- }
577- Some(
578- out.stdout
579- .as_chunks::<4>().0.iter()
580- .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
581- .collect(),
582- )
583-}
584-
585-/// Ours against LAME on the user's library, at matched constant bitrate:
586-///
587-/// cargo test -p ec-mp3 --release --test encode_matrix \
588-/// real_library_sweep_vs_lame -- --ignored --nocapture
589-#[test]
590-#[ignore = "needs the user's library and ffmpeg's libmp3lame"]
591-fn real_library_sweep_vs_lame() {
592- let seconds = 60u32;
593- let work = workdir("lame-sweep");
594- println!(
595- "{:<7} {:>5} {:>9} {:>9} {:>8} {:>8} {:>8} {:>8} {:>8}",
596- "source",
597- "kbps",
598- "corr_ours",
599- "corr_lame",
600- "gap",
601- "wworst_o",
602- "wworst_r",
603- "ours_kb",
604- "lame_kb"
605- );
606- let mut rows = 0;
607- let mut failures = Vec::new();
608- // `EC_MP3_SWEEP_ONLY=reelo,dl8a` narrows the sweep to named sources, so a
609- // constant can be swept against the rows it moves without paying for the
610- // rows it does not.
611- let only = std::env::var("EC_MP3_SWEEP_ONLY").unwrap_or_default();
612- for (name, src) in LIBRARY {
613- if !only.is_empty() && !only.split(',').any(|w| w.trim() == name) {
614- continue;
615- }
616- let src = expand(src);
617- if !src.exists() {
618- println!("{name:<7} SKIP (missing)");
619- continue;
620- }
621- let Some(pcm) = decode_source(&src, seconds) else {
622- println!("{name:<7} SKIP (decode)");
623- continue;
624- };
625- let secs = pcm.len() as f64 / (44100.0 * 2.0);
626- for kbps in [128u32, 192] {
627- let ours_bytes = encode(&pcm, 44100, 2, kbps);
628- let ours_file = work.join(format!("ours-{name}-{kbps}.mp3"));
629- std::fs::write(&ours_file, &ours_bytes).expect("write ours");
630- let lame_file = work.join(format!("lame-{name}-{kbps}.mp3"));
631- let status = Command::new("ffmpeg")
632- .args(["-y", "-v", "error", "-i"])
633- .arg(&src)
634- .args([
635- "-vn",
636- "-t",
637- &seconds.to_string(),
638- "-ac",
639- "2",
640- "-ar",
641- "44100",
642- "-c:a",
643- "libmp3lame",
644- "-b:a",
645- &format!("{kbps}k"),
646- ])
647- .arg(&lame_file)
648- .status()
649- .expect("ffmpeg runs");
650- assert!(status.success(), "libmp3lame encode of {name} at {kbps}k");
651- // Both decoded by the same decoder and aligned the same way: an
652- // encoder delay is not a quality difference.
653- let measure = |file: &Path| -> (f64, f64) {
654- let decoded = decode(file);
655- let (corr, offset) = aligned(&decoded, &pcm, 2);
656- (corr, worst_window_db(&decoded, &pcm, offset, 2))
657- };
658- let ((ours_corr, ours_worst), (lame_corr, lame_worst)) =
659- (measure(&ours_file), measure(&lame_file));
660- let kb =
661- |p: &Path| std::fs::metadata(p).expect("size").len() as f64 * 8.0 / secs / 1000.0;
662- let gap = ours_corr - lame_corr;
663- println!(
664- "{name:<7} {kbps:>5} {ours_corr:>9.5} {lame_corr:>9.5} {gap:>+8.5} \
665- {ours_worst:>+8.1} {lame_worst:>+8.1} {:>8.1} {:>8.1}",
666- kb(&ours_file),
667- kb(&lame_file)
668- );
669- rows += 1;
670- if gap < LAME_CORR_FLOOR {
671- failures.push(format!(
672- "{name} at {kbps} kbit/s: {ours_corr:.5} against LAME's {lame_corr:.5}"
673- ));
674- }
675- if ours_worst - lame_worst > WORST_WINDOW_EXCESS_DB {
676- failures.push(format!(
677- "{name} at {kbps} kbit/s: worst window {ours_worst:.1} dB \
678- against LAME's {lame_worst:.1} dB"
679- ));
680- }
681- }
682- }
683- assert!(rows > 0, "no library sources were readable");
684 assert!(failures.is_empty(), "{failures:#?}");406 assert!(failures.is_empty(), "{failures:#?}");
685 }407 }
686 408
687-/// The `mode_extension` of every frame of a stream, in order.
688 fn mode_exts(bytes: &[u8]) -> Vec<u8> {409 fn mode_exts(bytes: &[u8]) -> Vec<u8> {
689 let mut out = Vec::new();410 let mut out = Vec::new();
690 let mut at = 0;411 let mut at = 0;
@@ -745,153 +466,3 @@ fn mid_side_follows_the_channel_correlation() {
745 }466 }
746 }467 }
747 }468 }
748-
749-/// libmp3lame's VBR levels, encoded once per source so the level that
750-/// actually spent what we spent can be picked by measurement. Nominal rates
751-/// are no guide: on speech, V6 lands near 60 kbit/s rather than its nominal
752-/// 115, because libmp3lame drops the rate hard on easy material.
753-const LAME_V_LEVELS: [u32; 10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
754-
755-/// How far under libmp3lame a VBR row may sit in correlation when it spent at
756-/// least as many bits. Thirteen of the fourteen rows are ahead; the floor is
757-/// set by her at quality 0.3, which is 0.00042 behind while spending 1.5%
758-/// less.
759-const VBR_CORR_FLOOR: f64 = -0.0005;
760-
761-/// How far behind libmp3lame's worst 20 ms window a VBR row may sit. Set by
762-/// nik and reelo at quality 0.3, both 2.8 dB behind: the frames our VBR calls
763-/// easy are where it still under-spends against a transient.
764-const VBR_WORST_EXCESS_DB: f64 = 3.5;
765-
766-/// How much of libmp3lame's rate ours may spend at a matched quality. Rows
767-/// where libmp3lame is already on its top rung (V0) are exempt: it cannot
768-/// spend more there, so a premium measures its ceiling and not our appetite.
769-const VBR_RATE_CEILING: f64 = 8.0;
770-
771-/// Our VBR against libmp3lame's, on the user's own library, at a matched rate.
772-///
773-/// CBR has had a reference gate since `real_library_sweep_vs_lame`; VBR has
774-/// had none, which is why the demand-weighted frame split landed in the CBR
775-/// arm only -- VBR's bitrate choice is calibrated to the noise-to-mask ratio
776-/// the even split produces, and nothing could tell whether moving both was a
777-/// gain or a loss.
778-#[test]
779-#[ignore = "needs the user's library and ffmpeg's libmp3lame"]
780-fn real_library_vbr_vs_lame() {
781- let seconds = 60u32;
782- let work = workdir("lame-vbr");
783- println!(
784- "{:<7} {:>4} {:>9} {:>9} {:>8} {:>8} {:>8} {:>8} {:>8} {:>4}",
785- "source",
786- "q",
787- "corr_ours",
788- "corr_lame",
789- "gap",
790- "wworst_o",
791- "wworst_r",
792- "ours_kb",
793- "lame_kb",
794- "V"
795- );
796- let only = std::env::var("EC_MP3_SWEEP_ONLY").unwrap_or_default();
797- let mut rows = 0;
798- let mut failures = Vec::new();
799- for (name, src) in LIBRARY {
800- if !only.is_empty() && !only.split(',').any(|w| w.trim() == name) {
801- continue;
802- }
803- let src = expand(src);
804- if !src.exists() {
805- println!("{name:<7} SKIP (missing)");
806- continue;
807- }
808- let Some(pcm) = decode_source(&src, seconds) else {
809- println!("{name:<7} SKIP (decode)");
810- continue;
811- };
812- let secs = pcm.len() as f64 / (44100.0 * 2.0);
813- let kb = |p: &Path| std::fs::metadata(p).expect("size").len() as f64 * 8.0 / secs / 1000.0;
814- // Every rung of libmp3lame's VBR ladder, measured on this source.
815- let lame_ladder: Vec<(u32, PathBuf, f64)> = LAME_V_LEVELS
816- .iter()
817- .map(|&level| {
818- let file = work.join(format!("lame-{name}-v{level}.mp3"));
819- let status = Command::new("ffmpeg")
820- .args(["-y", "-v", "error", "-i"])
821- .arg(&src)
822- .args([
823- "-vn",
824- "-t",
825- &seconds.to_string(),
826- "-ac",
827- "2",
828- "-ar",
829- "44100",
830- "-c:a",
831- "libmp3lame",
832- "-q:a",
833- &level.to_string(),
834- ])
835- .arg(&file)
836- .status()
837- .expect("ffmpeg runs");
838- assert!(status.success(), "libmp3lame V{level} of {name}");
839- let rate = kb(&file);
840- (level, file, rate)
841- })
842- .collect();
843- for quality in [0.3f32, 0.6] {
844- let ours_bytes = encode_vbr(&pcm, 44100, 2, quality);
845- let ours_file = work.join(format!("ours-{name}-{quality}.mp3"));
846- std::fs::write(&ours_file, &ours_bytes).expect("write ours");
847- let ours_kb = kb(&ours_file);
848- // The level that actually spent what we spent.
849- let (level, lame_file) = lame_ladder
850- .iter()
851- .min_by(|a, b| {
852- (a.2 - ours_kb)
853- .abs()
854- .partial_cmp(&(b.2 - ours_kb).abs())
855- .expect("finite")
856- })
857- .map(|(v, f, _)| (*v, f.clone()))
858- .expect("a ladder rung");
859- let measure = |file: &Path| -> (f64, f64) {
860- let decoded = decode(file);
861- let (corr, offset) = aligned(&decoded, &pcm, 2);
862- (corr, worst_window_db(&decoded, &pcm, offset, 2))
863- };
864- let ((ours_corr, ours_worst), (lame_corr, lame_worst)) =
865- (measure(&ours_file), measure(&lame_file));
866- let lame_kb = kb(&lame_file);
867- let gap = ours_corr - lame_corr;
868- let premium = (ours_kb / lame_kb - 1.0) * 100.0;
869- println!(
870- "{name:<7} {quality:>4} {ours_corr:>9.5} {lame_corr:>9.5} {gap:>+8.5} \
871- {ours_worst:>+8.1} {lame_worst:>+8.1} {ours_kb:>8.1} {lame_kb:>8.1} {level:>4}"
872- );
873- rows += 1;
874- // Being behind on quality is only a failure if we did not also
875- // spend less to get there; spending more is a failure on its own.
876- if gap < VBR_CORR_FLOOR && ours_kb >= lame_kb * 0.98 {
877- failures.push(format!(
878- "{name} at q{quality}: {ours_corr:.5} against LAME's {lame_corr:.5} \
879- at {ours_kb:.1} against {lame_kb:.1} kbit/s"
880- ));
881- }
882- if ours_worst - lame_worst > VBR_WORST_EXCESS_DB {
883- failures.push(format!(
884- "{name} at q{quality}: worst window {ours_worst:.1} dB \
885- against LAME's {lame_worst:.1} dB"
886- ));
887- }
888- if level > 0 && premium > VBR_RATE_CEILING {
889- failures.push(format!(
890- "{name} at q{quality}: {premium:+.1}% of LAME's rate (V{level})"
891- ));
892- }
893- }
894- }
895- assert!(rows > 0, "no library sources were readable");
896- assert!(failures.is_empty(), "{failures:#?}");
897-}
crates/ec-mp3/tests/mp2_matrix.rsmodified+6 -39
@@ -6,34 +6,13 @@
6 //! mode, the joint-stereo bound, CRC-protected frames and Layer I -- things no6 //! mode, the joint-stereo bound, CRC-protected frames and Layer I -- things no
7 //! encoder here produces. The oracle is `ffmpeg -c:a mp2 -i x.mp2 -f f32le`.7 //! encoder here produces. The oracle is `ffmpeg -c:a mp2 -i x.mp2 -f f32le`.
8 //!8 //!
9-//! ffmpeg is needed; absent, the tests skip (fail under `EC_REQUIRE_FIXTURES=1`).
10 //!9 //!
11 //! cargo test -p ec-mp3 --release --test mp2_matrix -- --nocapture10 //! cargo test -p ec-mp3 --release --test mp2_matrix -- --nocapture
12 11
13 use std::path::PathBuf;12 use std::path::PathBuf;
14-use std::process::Command;
15 13
16 use ec_mp3::{FrameHeader, Mp3Reader};14 use ec_mp3::{FrameHeader, Mp3Reader};
17 15
18-fn required() -> bool {
19- std::env::var_os("EC_REQUIRE_FIXTURES").is_some_and(|v| !v.is_empty() && v != "0")
20-}
21-
22-fn have_ffmpeg() -> bool {
23- let ok = Command::new("ffmpeg")
24- .arg("-version")
25- .output()
26- .is_ok_and(|o| o.status.success());
27- if !ok {
28- assert!(
29- !required(),
30- "EC_REQUIRE_FIXTURES is set but ffmpeg is missing"
31- );
32- eprintln!("skip: ffmpeg not available");
33- }
34- ok
35-}
36-
37 fn work_dir() -> PathBuf {16 fn work_dir() -> PathBuf {
38 let d = std::env::temp_dir().join("ec-mp2-matrix");17 let d = std::env::temp_dir().join("ec-mp2-matrix");
39 std::fs::create_dir_all(&d).unwrap();18 std::fs::create_dir_all(&d).unwrap();
@@ -42,7 +21,7 @@ fn work_dir() -> PathBuf {
42 21
43 fn ffmpeg_decode(path: &std::path::Path, channels: usize, layer: u8) -> Vec<f32> {22 fn ffmpeg_decode(path: &std::path::Path, channels: usize, layer: u8) -> Vec<f32> {
44 let decoder = if layer == 1 { "mp1float" } else { "mp2float" };23 let decoder = if layer == 1 { "mp1float" } else { "mp2float" };
45- let out = Command::new("ffmpeg")24+ let out = ec_testkit::ffmpeg()
46 .args(["-v", "error", "-c:a", decoder, "-i"])25 .args(["-v", "error", "-c:a", decoder, "-i"])
47 .arg(path)26 .arg(path)
48 .args(["-ac", &channels.to_string(), "-f", "f32le", "-"])27 .args(["-ac", &channels.to_string(), "-f", "f32le", "-"])
@@ -64,7 +43,7 @@ fn ffmpeg_decode(path: &std::path::Path, channels: usize, layer: u8) -> Vec<f32>
64 /// ffmpeg's fixed-point decoder (the default `mp2`/`mp1`): s16 out.43 /// ffmpeg's fixed-point decoder (the default `mp2`/`mp1`): s16 out.
65 fn ffmpeg_decode_s16(path: &std::path::Path, channels: usize, layer: u8) -> Vec<i16> {44 fn ffmpeg_decode_s16(path: &std::path::Path, channels: usize, layer: u8) -> Vec<i16> {
66 let decoder = if layer == 1 { "mp1" } else { "mp2" };45 let decoder = if layer == 1 { "mp1" } else { "mp2" };
67- let out = Command::new("ffmpeg")46+ let out = ec_testkit::ffmpeg()
68 .args(["-v", "error", "-c:a", decoder, "-i"])47 .args(["-v", "error", "-c:a", decoder, "-i"])
69 .arg(path)48 .arg(path)
70 .args(["-ac", &channels.to_string(), "-f", "s16le", "-"])49 .args(["-ac", &channels.to_string(), "-f", "s16le", "-"])
@@ -133,9 +112,6 @@ impl Rng {
133 112
134 #[test]113 #[test]
135 fn encoder_streams_match_ffmpeg() {114 fn encoder_streams_match_ffmpeg() {
136- if !have_ffmpeg() {
137- return;
138- }
139 let dir = work_dir();115 let dir = work_dir();
140 let sources = [116 let sources = [
141 "sine=frequency=1000:sample_rate={R}:duration=1.5",117 "sine=frequency=1000:sample_rate={R}:duration=1.5",
@@ -161,7 +137,7 @@ fn encoder_streams_match_ffmpeg() {
161 for (n, &(codec, rate, ch, br)) in cases.iter().enumerate() {137 for (n, &(codec, rate, ch, br)) in cases.iter().enumerate() {
162 let src = sources[n % sources.len()].replace("{R}", &rate.to_string());138 let src = sources[n % sources.len()].replace("{R}", &rate.to_string());
163 let path = dir.join(format!("enc-{n}.mp2"));139 let path = dir.join(format!("enc-{n}.mp2"));
164- let st = Command::new("ffmpeg")140+ let st = ec_testkit::ffmpeg()
165 .args(["-v", "error", "-y", "-f", "lavfi", "-i", &src, "-ac"])141 .args(["-v", "error", "-y", "-f", "lavfi", "-i", &src, "-ac"])
166 .arg(ch.to_string())142 .arg(ch.to_string())
167 .args(["-c:a", codec, "-b:a", br])143 .args(["-c:a", codec, "-b:a", br])
@@ -453,9 +429,6 @@ fn compare_stream(name: &str, frames: &[Vec<u8>], tolerance: f32) -> f32 {
453 429
454 #[test]430 #[test]
455 fn random_frames_match_ffmpeg() {431 fn random_frames_match_ffmpeg() {
456- if !have_ffmpeg() {
457- return;
458- }
459 let mut rng = Rng(0x9E37_79B9_7F4A_7C15);432 let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
460 let mut worst = 0.0f32;433 let mut worst = 0.0f32;
461 let mut streams = 0;434 let mut streams = 0;
@@ -494,7 +467,7 @@ fn random_frames_match_ffmpeg() {
494 }467 }
495 468
496 fn have_encoder(name: &str) -> bool {469 fn have_encoder(name: &str) -> bool {
497- Command::new("ffmpeg")470+ ec_testkit::ffmpeg()
498 .args(["-hide_banner", "-encoders"])471 .args(["-hide_banner", "-encoders"])
499 .output()472 .output()
500 .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(name))473 .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).contains(name))
@@ -504,13 +477,7 @@ fn have_encoder(name: &str) -> bool {
504 /// intensity bound, dual channel, and CRC-protected frames.477 /// intensity bound, dual channel, and CRC-protected frames.
505 #[test]478 #[test]
506 fn twolame_streams_match_ffmpeg() {479 fn twolame_streams_match_ffmpeg() {
507- if !have_ffmpeg() {480+ assert!(have_encoder("libtwolame"), "ffmpeg has no libtwolame");
508- return;
509- }
510- if !have_encoder("libtwolame") {
511- eprintln!("skip: ffmpeg has no libtwolame");
512- return;
513- }
514 let dir = work_dir();481 let dir = work_dir();
515 let cases: &[(&str, u32, &str, u32, bool)] = &[482 let cases: &[(&str, u32, &str, u32, bool)] = &[
516 ("joint_stereo", 44100, "64k", 2, false),483 ("joint_stereo", 44100, "64k", 2, false),
@@ -531,7 +498,7 @@ fn twolame_streams_match_ffmpeg() {
531 let src = format!(498 let src = format!(
532 "aevalsrc=0.4*sin(2*PI*(300+1500*t)*t)|0.3*sin(2*PI*700*t)+0.05*random(1):s={rate}:d=2"499 "aevalsrc=0.4*sin(2*PI*(300+1500*t)*t)|0.3*sin(2*PI*700*t)+0.05*random(1):s={rate}:d=2"
533 );500 );
534- let st = Command::new("ffmpeg")501+ let st = ec_testkit::ffmpeg()
535 .args(["-v", "error", "-y", "-f", "lavfi", "-i", &src, "-ac"])502 .args(["-v", "error", "-y", "-f", "lavfi", "-i", &src, "-ac"])
536 .arg(ch.to_string())503 .arg(ch.to_string())
537 .args(["-c:a", "libtwolame", "-mode", mode, "-b:a", br])504 .args(["-c:a", "libtwolame", "-mode", mode, "-b:a", br])
crates/ec-opus/Cargo.tomlmodified+1 -0
@@ -16,6 +16,7 @@ wide.workspace = true
16 rustfft = { version = "6", optional = true, default-features = false }16 rustfft = { version = "6", optional = true, default-features = false }
17 17
18 [dev-dependencies]18 [dev-dependencies]
19+ec-testkit.workspace = true
19 ec-dsp.workspace = true20 ec-dsp.workspace = true
20 ec-ogg.workspace = true21 ec-ogg.workspace = true
21 cpu-time = "1.0.0"22 cpu-time = "1.0.0"
crates/ec-opus/fuzz/seed.shmodified+4 -3
@@ -13,9 +13,10 @@ set -euo pipefail
13 13
14 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)14 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
15 ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd)15 ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd)
16-VECTORS="$ROOT/fixtures/vectors/opus-rfc6716/opus_testvectors"16+FIX=${EC_FIXTURES:-$ROOT/fixtures}
17-AUDIO="$ROOT/fixtures/audio"17+VECTORS="$FIX/vectors/opus-rfc6716/opus_testvectors"
18-[ -d "$VECTORS" ] || { echo "seed.sh: $VECTORS missing; run scripts/link-fixtures.sh" >&2; exit 2; }18+AUDIO="$FIX/audio"
19+[ -d "$VECTORS" ] || { echo "seed.sh: $VECTORS missing; run scripts/fixtures.sh" >&2; exit 2; }
19 20
20 PKT_DIR="$FUZZ_DIR/corpus/decode_packet"21 PKT_DIR="$FUZZ_DIR/corpus/decode_packet"
21 TOC_DIR="$FUZZ_DIR/corpus/parse_toc"22 TOC_DIR="$FUZZ_DIR/corpus/parse_toc"
crates/ec-opus/tests/conformance.rsmodified+81 -2406

Diff too large; view file

@@ -94,8 +94,7 @@ fn read_vector(path: &Path) -> Vec<VectorPacket> {
94 }94 }
95 95
96 fn vectors_dir() -> PathBuf {96 fn vectors_dir() -> PathBuf {
97- Path::new(env!("CARGO_MANIFEST_DIR"))97+ ec_testkit::root().join("vectors/opus-rfc6716/opus_testvectors")
98- .join("../../fixtures/vectors/opus-rfc6716/opus_testvectors")
99 }98 }
100 99
101 /// Decodes a vector at 48 kHz stereo, returning the samples and how many100 /// Decodes a vector at 48 kHz stereo, returning the samples and how many
@@ -421,27 +420,14 @@ fn read_i16(path: &Path) -> Vec<i16> {
421 /// of RFC 8251 Section 10) and `testvectorNNm.dec` (without it). An420 /// of RFC 8251 Section 10) and `testvectorNNm.dec` (without it). An
422 /// implementation is compliant when it matches either set.421 /// implementation is compliant when it matches either set.
423 fn vectors_dir_8251() -> PathBuf {422 fn vectors_dir_8251() -> PathBuf {
424- Path::new(env!("CARGO_MANIFEST_DIR"))423+ ec_testkit::root().join("vectors/opus-rfc8251/opus_newvectors")
425- .join("../../fixtures/vectors/opus-rfc8251/opus_newvectors")
426 }424 }
427 425
428 /// Runs one RFC 8251 vector (stereo) against one of its reference files. Returns426 /// Runs one RFC 8251 vector (stereo) against one of its reference files. Returns
429 /// `(range-exact, decoded packets, quality %)`; the caller decides what passes.427 /// `(range-exact, decoded packets, quality %)`; the caller decides what passes.
430 fn run_rfc8251(name: &str, reference: &str) -> (usize, usize, f64) {428 fn run_rfc8251(name: &str, reference: &str) -> (usize, usize, f64) {
431 let dir = vectors_dir_8251();429 let dir = vectors_dir_8251();
432- let bit = dir.join(format!("{name}.bit"));430+ let bit = ec_testkit::fixture(&format!("vectors/opus-rfc8251/opus_newvectors/{name}.bit"));
433- if !bit.exists() {
434- assert!(
435- std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
436- "RFC 8251 test vector {name} missing at {} — run scripts/fetch-vectors.sh opus-rfc8251",
437- bit.display()
438- );
439- eprintln!(
440- "SKIP RFC 8251 test vector {name} missing at {}",
441- bit.display()
442- );
443- return (0, 0, f64::NAN);
444- }
445 let packets = read_vector(&bit);431 let packets = read_vector(&bit);
446 let (pcm, matched, decoded) = decode_vector_ch(&packets, 2, false);432 let (pcm, matched, decoded) = decode_vector_ch(&packets, 2, false);
447 let refs = read_i16(&dir.join(reference));433 let refs = read_i16(&dir.join(reference));
@@ -506,33 +492,10 @@ const VECTORS: [&str; 12] = [
506 #[test]492 #[test]
507 fn rfc6716_test_vectors() {493 fn rfc6716_test_vectors() {
508 let _timing = timing_shared();494 let _timing = timing_shared();
509- // A missing test vector made this gate skip GREEN having decoded nothing —
510- // the "gate skips on its own failure" class. The root `fixtures/` tree is
511- // gitignored, so `git worktree add` hands every lane worktree a tree without
512- // it. `EC_REQUIRE_FIXTURES=1` turns a missing vector into a hard failure
513- // naming the exact path and the command that produces it; unset, the skip
514- // is kept and now says what it skipped. Set it in every batch run.
515- let base = vectors_dir();
516 let mut table = Vec::new();495 let mut table = Vec::new();
517 for name in VECTORS {496 for name in VECTORS {
518- let path = base.join(format!("{name}.bit"));497+ let path =
519- if !path.exists() {498+ ec_testkit::fixture(&format!("vectors/opus-rfc6716/opus_testvectors/{name}.bit"));
520- assert!(
521- std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
522- "RFC 6716 test vector {name} missing at {} — this gate would prove \
523- nothing. A worktree has no gitignored root `fixtures/`: run \
524- scripts/link-fixtures.sh, or fetch it with scripts/fetch-vectors.sh.",
525- path.display()
526- );
527- eprintln!(
528- "SKIP RFC 6716 test vector {name} missing at {} — this gate proved \
529- nothing; run scripts/link-fixtures.sh, or fetch it with \
530- scripts/fetch-vectors.sh (or set EC_REQUIRE_FIXTURES=1 to make this \
531- a failure).",
532- path.display()
533- );
534- continue;
535- }
536 let packets = read_vector(&path);499 let packets = read_vector(&path);
537 let (pcm, matched, decoded) = decode_vector(&packets);500 let (pcm, matched, decoded) = decode_vector(&packets);
538 let reference = read_i16(&vectors_dir().join(format!("{name}.dec")));501 let reference = read_i16(&vectors_dir().join(format!("{name}.dec")));
@@ -631,9 +594,7 @@ fn parse_opus_head(p: &[u8]) -> OpusHead {
631 }594 }
632 595
633 fn fixture(name: &str) -> PathBuf {596 fn fixture(name: &str) -> PathBuf {
634- Path::new(env!("CARGO_MANIFEST_DIR"))597+ ec_testkit::fixture(&format!("audio/{name}"))
635- .join("../../fixtures/audio")
636- .join(name)
637 }598 }
638 599
639 /// ffmpeg's decode of the same file, interleaved `f32` in ffmpeg's channel600 /// ffmpeg's decode of the same file, interleaved `f32` in ffmpeg's channel
@@ -643,8 +604,8 @@ fn fixture(name: &str) -> PathBuf {
643 /// own native Opus decoder is a third implementation and deviates from libopus604 /// own native Opus decoder is a third implementation and deviates from libopus
644 /// by as much as 0.97 correlation on this very fixture's coupled surround605 /// by as much as 0.97 correlation on this very fixture's coupled surround
645 /// streams, so it makes a poor oracle.606 /// streams, so it makes a poor oracle.
646-fn ffmpeg_decode(path: &Path, channels: usize) -> Option<Vec<f32>> {607+fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<f32> {
647- let out = Command::new("ffmpeg")608+ let out = ec_testkit::ffmpeg()
648 .args(["-v", "error", "-c:a", "libopus", "-i"])609 .args(["-v", "error", "-c:a", "libopus", "-i"])
649 .arg(path)610 .arg(path)
650 .args([611 .args([
@@ -657,18 +618,18 @@ fn ffmpeg_decode(path: &Path, channels: usize) -> Option<Vec<f32>> {
657 "-",618 "-",
658 ])619 ])
659 .output()620 .output()
660- .ok()?;621+ .expect("run ffmpeg");
661- if !out.status.success() {622+ assert!(
662- return None;623+ out.status.success(),
663- }624+ "ffmpeg could not decode {}",
664- Some(625+ path.display()
626+ );
665 out.stdout627 out.stdout
666 .as_chunks::<4>()628 .as_chunks::<4>()
667 .0629 .0
668 .iter()630 .iter()
669 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))631 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
670- .collect(),632+ .collect()
671- )
672 }633 }
673 634
674 /// Decodes an Ogg-Opus file with the multistream decoder, pre-skip removed.635 /// Decodes an Ogg-Opus file with the multistream decoder, pre-skip removed.
@@ -729,14 +690,7 @@ fn ogg_opus_fixtures_match_ffmpeg() {
729 ("opus-ogg-5.1-48000.opus", 6),690 ("opus-ogg-5.1-48000.opus", 6),
730 ] {691 ] {
731 let path = fixture(name);692 let path = fixture(name);
732- if !path.exists() {693+ let reference = ffmpeg_decode(&path, channels);
733- eprintln!("{name}: missing, skipped (run scripts/gen-fixtures.sh)");
734- continue;
735- }
736- let Some(reference) = ffmpeg_decode(&path, channels) else {
737- eprintln!("{name}: ffmpeg unavailable, skipped");
738- continue;
739- };
740 let (mine, ch) = decode_ogg(&path);694 let (mine, ch) = decode_ogg(&path);
741 assert_eq!(ch, channels, "{name}: channel count");695 assert_eq!(ch, channels, "{name}: channel count");
742 let mut worst = 1.0f64;696 let mut worst = 1.0f64;
@@ -772,14 +726,7 @@ fn five_one_channels_land_in_the_right_places() {
772 const VORBIS_TO_FFMPEG_5_1: [usize; 6] = [0, 2, 1, 4, 5, 3];726 const VORBIS_TO_FFMPEG_5_1: [usize; 6] = [0, 2, 1, 4, 5, 3];
773 const TONES: [f64; 6] = [220.0, 440.0, 660.0, 55.0, 880.0, 1320.0];727 const TONES: [f64; 6] = [220.0, 440.0, 660.0, 55.0, 880.0, 1320.0];
774 let path = fixture("opus-ogg-5.1-48000.opus");728 let path = fixture("opus-ogg-5.1-48000.opus");
775- if !path.exists() {729+ let reference = ffmpeg_decode(&path, 6);
776- eprintln!("5.1 fixture missing, skipped");
777- return;
778- }
779- let Some(reference) = ffmpeg_decode(&path, 6) else {
780- eprintln!("ffmpeg unavailable, skipped");
781- return;
782- };
783 let (pcm, channels) = decode_ogg(&path);730 let (pcm, channels) = decode_ogg(&path);
784 assert_eq!(channels, 6);731 assert_eq!(channels, 6);
785 let dominant = |x: &[f32], ch: usize| -> usize {732 let dominant = |x: &[f32], ch: usize| -> usize {
@@ -864,9 +811,6 @@ fn decode_speed() {
864 ("opus-ogg-5.1-48000.opus", 6),811 ("opus-ogg-5.1-48000.opus", 6),
865 ] {812 ] {
866 let path = fixture(name);813 let path = fixture(name);
867- if !path.exists() {
868- continue;
869- }
870 let data = fs::read(&path).unwrap();814 let data = fs::read(&path).unwrap();
871 let packets = ogg_packets(&data);815 let packets = ogg_packets(&data);
872 let head = parse_opus_head(&packets[0]);816 let head = parse_opus_head(&packets[0]);
@@ -902,8 +846,7 @@ fn decode_speed() {
902 846
903 // The fixtures are sine tones, which are cheap; testvector01 is real music847 // The fixtures are sine tones, which are cheap; testvector01 is real music
904 // at a high rate and is the honest stereo number.848 // at a high rate and is the honest stereo number.
905- let path = vectors_dir().join("testvector01.bit");849+ let path = ec_testkit::fixture("vectors/opus-rfc6716/opus_testvectors/testvector01.bit");
906- if path.exists() {
907 let packets = read_vector(&path);850 let packets = read_vector(&path);
908 let mut out = vec![0.0f32; 5760 * 2];851 let mut out = vec![0.0f32; 5760 * 2];
909 let mut samples = 0usize;852 let mut samples = 0usize;
@@ -918,53 +861,6 @@ fn decode_speed() {
918 println!("testvector01 (stereo music): {realtime:.0}x realtime");861 println!("testvector01 (stereo music): {realtime:.0}x realtime");
919 assert!(realtime >= 135.0, "stereo music decodes at {realtime:.0}x");862 assert!(realtime >= 135.0, "stereo music decodes at {realtime:.0}x");
920 }863 }
921-}
922-
923-#[test]
924-#[ignore = "probe: report harness with no asserts; unblocks by setting EC_OPUS_FILES to committed .opus fixtures -- unset, it decodes nothing"]
925-fn real_library_sweep() {
926- let _timing = timing_shared();
927- // Files named on the command line (EC_OPUS_FILES=a.opus:b.opus), decoded
928- // and compared against libopus channel by channel, with the decode speed.
929- let files = std::env::var("EC_OPUS_FILES").unwrap_or_default();
930- for f in files.split(':').filter(|s| !s.is_empty()) {
931- let path = PathBuf::from(f);
932- let (pcm, channels) = decode_ogg(&path);
933- let reference = ffmpeg_decode(&path, channels).expect("libopus");
934- let n = (reference.len() / channels).min(pcm.len() / channels);
935- let mut worst = 1.0f64;
936- for c in 0..channels {
937- let a: Vec<f32> = (0..n).map(|i| pcm[i * channels + c]).collect();
938- let b: Vec<f32> = (0..n).map(|i| reference[i * channels + c]).collect();
939- let corr = correlation(&a, &b);
940- worst = worst.min(corr);
941- println!("{f}: channel {c} correlation {corr:.5}");
942- }
943- // Speed on the same file.
944- let data = fs::read(&path).unwrap();
945- let packets = ogg_packets(&data);
946- let head = parse_opus_head(&packets[0]);
947- let audio: Vec<&Vec<u8>> = packets.iter().skip(2).filter(|p| !p.is_empty()).collect();
948- let mut dec =
949- MultistreamDecoder::with_rate(48000, head.streams, head.coupled, &head.mapping);
950- let mut out = vec![0.0f32; 5760 * channels];
951- let mut samples = 0usize;
952- for p in &audio {
953- samples += dec.decode_float(p, &mut out).unwrap();
954- }
955- dec.reset();
956- let start = std::time::Instant::now();
957- for p in &audio {
958- dec.decode_float(p, &mut out).unwrap();
959- }
960- let elapsed = start.elapsed().as_secs_f64();
961- println!(
962- "{f}: {channels} ch, {:.1} s audio, {:.0}x realtime, worst channel {worst:.5}",
963- samples as f64 / 48000.0,
964- samples as f64 / 48000.0 / elapsed
965- );
966- }
967-}
968 864
969 // ---------------------------------------------------------------------------865 // ---------------------------------------------------------------------------
970 // Encoder: self-consistency (range-exact against our own decoder)866 // Encoder: self-consistency (range-exact against our own decoder)
@@ -1583,14 +1479,7 @@ fn encode_packets(enc: &mut Encoder, pcm: &[f32], channels: usize) -> Vec<Vec<u8
1583 }1479 }
1584 1480
1585 fn temp_path(name: &str) -> PathBuf {1481 fn temp_path(name: &str) -> PathBuf {
1586- let root = std::env::var_os("EC_OPUS_SCRATCH")1482+ std::env::temp_dir().join(format!("ec-opus-enc-{}-{name}", std::process::id()))
1587- .map(PathBuf::from)
1588- .unwrap_or_else(|| {
1589- let home = std::env::var_os("HOME").expect("HOME set for encoder scratch");
1590- PathBuf::from(home).join(".cache/silk2")
1591- });
1592- fs::create_dir_all(&root).unwrap();
1593- root.join(format!("ec-opus-enc-{}-{name}", std::process::id()))
1594 }1483 }
1595 1484
1596 /// The full product rate table, mono and stereo, decoded by libopus: the1485 /// The full product rate table, mono and stereo, decoded by libopus: the
@@ -1617,11 +1506,7 @@ fn oracle_decodes_our_packets_across_the_rate_table() {
1617 total,1506 total,
1618 enc.look_ahead(960) as i64,1507 enc.look_ahead(960) as i64,
1619 );1508 );
1620- let Some(reference) = ffmpeg_decode(&path, channels) else {1509+ let reference = ffmpeg_decode(&path, channels);
1621- eprintln!("ffmpeg unavailable, skipped");
1622- let _ = fs::remove_file(&path);
1623- return;
1624- };
1625 let _ = fs::remove_file(&path);1510 let _ = fs::remove_file(&path);
1626 let n = (reference.len() / channels).min(total);1511 let n = (reference.len() / channels).min(total);
1627 assert!(1512 assert!(
@@ -1691,11 +1576,7 @@ fn oracle_decodes_our_packets_across_the_rate_table() {
1691 total,1576 total,
1692 pre_skip as i64,1577 pre_skip as i64,
1693 );1578 );
1694- let Some(reference) = ffmpeg_decode(&path, 1) else {1579+ let reference = ffmpeg_decode(&path, 1);
1695- eprintln!("ffmpeg unavailable, skipped");
1696- let _ = fs::remove_file(&path);
1697- return;
1698- };
1699 let _ = fs::remove_file(&path);1580 let _ = fs::remove_file(&path);
1700 let mut dec = Decoder::new(48000, 1).unwrap();1581 let mut dec = Decoder::new(48000, 1).unwrap();
1701 let mut buf = vec![0f32; 5760];1582 let mut buf = vec![0f32; 5760];
@@ -1748,11 +1629,7 @@ fn five_one_encode_end_to_end() {
1748 let head = opus_head(6, pre_skip as u16, Some((streams, coupled, mapping)));1629 let head = opus_head(6, pre_skip as u16, Some((streams, coupled, mapping)));
1749 let path = temp_path("5.1.opus");1630 let path = temp_path("5.1.opus");
1750 write_ogg_opus(&path, &packets, head, 6, total, pre_skip as i64);1631 write_ogg_opus(&path, &packets, head, 6, total, pre_skip as i64);
1751- let Some(reference) = ffmpeg_decode(&path, 6) else {1632+ let reference = ffmpeg_decode(&path, 6);
1752- eprintln!("ffmpeg unavailable, skipped");
1753- let _ = fs::remove_file(&path);
1754- return;
1755- };
1756 let _ = fs::remove_file(&path);1633 let _ = fs::remove_file(&path);
1757 let n = (reference.len() / 6).min(total);1634 let n = (reference.len() / 6).min(total);
1758 assert!(n >= total - 960, "libopus returned {n} of {total} samples");1635 assert!(n >= total - 960, "libopus returned {n} of {total} samples");
@@ -1789,7 +1666,7 @@ fn ogg_opus_round_trip_duration_is_exact() {
1789 total,1666 total,
1790 pre_skip as i64,1667 pre_skip as i64,
1791 );1668 );
1792- let probe = Command::new("ffprobe")1669+ let probe = ec_testkit::ffprobe()
1793 .args([1670 .args([
1794 "-v",1671 "-v",
1795 "error",1672 "error",
@@ -1820,71 +1697,16 @@ fn ogg_opus_round_trip_duration_is_exact() {
1820 "ffprobe reports {dur} s, expected {expected} s (2.000 s + pre-skip)"1697 "ffprobe reports {dur} s, expected {expected} s (2.000 s + pre-skip)"
1821 );1698 );
1822 }1699 }
1823- if let Some(decoded) = ffmpeg_decode(&path, 2) {1700+ let decoded = ffmpeg_decode(&path, 2);
1824 assert_eq!(1701 assert_eq!(
1825 decoded.len() / 2,1702 decoded.len() / 2,
1826 total,1703 total,
1827 "libopus decoded {} samples of {total}",1704 "libopus decoded {} samples of {total}",
1828 decoded.len() / 21705 decoded.len() / 2
1829 );1706 );
1830- }
1831 let _ = fs::remove_file(&path);1707 let _ = fs::remove_file(&path);
1832 }1708 }
1833 1709
1834-/// Cross-check against the reference `opus_demo` decoder (RFC 6716
1835-/// Appendix A) over its own `.bit` format, when the binary is available:
1836-/// `EC_OPUS_DEMO=/path/to/opus_demo cargo test`.
1837-#[test]
1838-fn opus_demo_decodes_our_bit_stream() {
1839- let _timing = timing_shared();
1840- let Ok(demo) = std::env::var("EC_OPUS_DEMO") else {
1841- eprintln!("EC_OPUS_DEMO unset, skipped");
1842- return;
1843- };
1844- let pcm = test_signal(2, 2.0);
1845- let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap();
1846- enc.set_bitrate(256_000);
1847- let mut out = vec![0u8; 1500];
1848- let mut bit = Vec::new();
1849- for block in pcm.as_chunks::<{ 960 * 2 }>().0 {
1850- let len = enc.encode_float(block, 960, &mut out).expect("encode");
1851- bit.extend_from_slice(&(len as u32).to_be_bytes());
1852- bit.extend_from_slice(&enc.final_range().to_be_bytes());
1853- bit.extend_from_slice(&out[..len]);
1854- }
1855- let bit_path = temp_path("demo.bit");
1856- let pcm_path = temp_path("demo.pcm");
1857- fs::write(&bit_path, &bit).unwrap();
1858- let status = Command::new(&demo)
1859- .arg("-d")
1860- .arg("48000")
1861- .arg("2")
1862- .arg(&bit_path)
1863- .arg(&pcm_path)
1864- .status()
1865- .expect("run opus_demo");
1866- assert!(status.success(), "opus_demo refused our stream");
1867- let decoded = read_i16(&pcm_path);
1868- let _ = fs::remove_file(&bit_path);
1869- let _ = fs::remove_file(&pcm_path);
1870- // opus_demo does not apply pre-skip; compensate for the 120-sample delay.
1871- let delay = 120usize;
1872- let n = (decoded.len() / 2 - delay).min(pcm.len() / 2 - delay);
1873- let mut worst = 1.0f64;
1874- for c in 0..2 {
1875- let a: Vec<f32> = (0..n).map(|i| pcm[i * 2 + c]).collect();
1876- let b: Vec<f32> = (0..n)
1877- .map(|i| decoded[(i + delay) * 2 + c] as f32 / 32768.0)
1878- .collect();
1879- worst = worst.min(correlation(&a, &b));
1880- }
1881- println!("opus_demo 256 kbps stereo: worst corr {worst:.4}");
1882- assert!(
1883- worst >= 0.9,
1884- "reference decoder heard correlation {worst:.4}"
1885- );
1886-}
1887-
1888 /// The steady-state encode loop allocates nothing: every buffer — MDCT1710 /// The steady-state encode loop allocates nothing: every buffer — MDCT
1889 /// scratch, PVQ vectors, the range coder's frame — is owned by the encoder1711 /// scratch, PVQ vectors, the range coder's frame — is owned by the encoder
1890 /// and sized on the first frame (the decoder discipline, applied to the1712 /// and sized on the first frame (the decoder discipline, applied to the
@@ -2047,15 +1869,13 @@ fn garbage_payloads_never_panic() {
2047 }1869 }
2048 }1870 }
2049 // Truncations of a real packet, which exercise the mid-frame paths.1871 // Truncations of a real packet, which exercise the mid-frame paths.
2050- let path = vectors_dir().join("testvector10.bit");1872+ let path = ec_testkit::fixture("vectors/opus-rfc6716/opus_testvectors/testvector10.bit");
2051- if path.exists() {
2052 for p in read_vector(&path).iter().take(200) {1873 for p in read_vector(&path).iter().take(200) {
2053 for cut in 1..p.payload.len().min(64) {1874 for cut in 1..p.payload.len().min(64) {
2054 let _ = dec.decode_float(&p.payload[..cut], &mut out);1875 let _ = dec.decode_float(&p.payload[..cut], &mut out);
2055 }1876 }
2056 }1877 }
2057 }1878 }
2058-}
2059 1879
2060 // ---------------------------------------------------------------------------1880 // ---------------------------------------------------------------------------
2061 // SILK encoder (mono, 20 ms, NB/WB)1881 // SILK encoder (mono, 20 ms, NB/WB)
@@ -2205,10 +2025,8 @@ fn silk_mono_nb_wb_roundtrip() {
2205 let _timing = timing_shared();2025 let _timing = timing_shared();
2206 let wav = fixture("wav16-mono-48000.wav");2026 let wav = fixture("wav16-mono-48000.wav");
2207 let mut sources = vec![("synthetic", speech_like())];2027 let mut sources = vec![("synthetic", speech_like())];
2208- if wav.exists() {
2209 let w = read_wav_mono(&wav);2028 let w = read_wav_mono(&wav);
2210 sources.push(("wav16-mono-48000", w[..w.len().min(96000)].to_vec()));2029 sources.push(("wav16-mono-48000", w[..w.len().min(96000)].to_vec()));
2211- }
2212 for (name, pcm) in &sources {2030 for (name, pcm) in &sources {
2213 for wideband in [false, true] {2031 for wideband in [false, true] {
2214 let (bandwidth, band, tag) = if wideband {2032 let (bandwidth, band, tag) = if wideband {
@@ -2229,10 +2047,9 @@ fn silk_mono_nb_wb_roundtrip() {
2229 assert!(corr >= 0.8, "{name} {tag}: corr {corr:.4}");2047 assert!(corr >= 0.8, "{name} {tag}: corr {corr:.4}");
2230 2048
2231 // Reference oracle: the packets in an Ogg-Opus file decode cleanly.2049 // Reference oracle: the packets in an Ogg-Opus file decode cleanly.
2232- if Command::new("ffmpeg").arg("-version").output().is_ok() {
2233 let path = temp_path(&format!("silk-{name}-{tag}.opus"));2050 let path = temp_path(&format!("silk-{name}-{tag}.opus"));
2234 write_ogg_opus(&path, &packets, opus_head(1, 120, None), 1, pcm.len(), 120);2051 write_ogg_opus(&path, &packets, opus_head(1, 120, None), 1, pcm.len(), 120);
2235- let out = Command::new("ffmpeg")2052+ let out = ec_testkit::ffmpeg()
2236 .args(["-v", "warning", "-c:a", "libopus", "-i"])2053 .args(["-v", "warning", "-c:a", "libopus", "-i"])
2237 .arg(&path)2054 .arg(&path)
2238 .args(["-f", "null", "-"])2055 .args(["-f", "null", "-"])
@@ -2247,7 +2064,6 @@ fn silk_mono_nb_wb_roundtrip() {
2247 }2064 }
2248 }2065 }
2249 }2066 }
2250-}
2251 2067
2252 #[test]2068 #[test]
2253 fn silk_mediumband_and_10ms_roundtrip() {2069 fn silk_mediumband_and_10ms_roundtrip() {
@@ -2279,12 +2095,11 @@ fn silk_mediumband_and_10ms_roundtrip() {
2279 packets.len()2095 packets.len()
2280 );2096 );
2281 assert!(corr >= floor, "{tag}: corr {corr:.4}");2097 assert!(corr >= floor, "{tag}: corr {corr:.4}");
2282- if let Some(oracle) = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len(), 120) {2098+ let oracle = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len(), 120);
2283 let (c, _) = aligned_corr(&oracle, &decoded, 2000);2099 let (c, _) = aligned_corr(&oracle, &decoded, 2000);
2284 assert!(c >= 0.99, "{tag}: our decode vs oracle decode corr {c:.4}");2100 assert!(c >= 0.99, "{tag}: our decode vs oracle decode corr {c:.4}");
2285 }2101 }
2286 }2102 }
2287-}
2288 2103
2289 #[test]2104 #[test]
2290 fn silk_multiframe_packets_roundtrip() {2105 fn silk_multiframe_packets_roundtrip() {
@@ -2319,13 +2134,12 @@ fn silk_multiframe_packets_roundtrip() {
2319 packets.len()2134 packets.len()
2320 );2135 );
2321 assert!(corr >= floor, "{tag}: corr {corr:.4} below {floor:.4}");2136 assert!(corr >= floor, "{tag}: corr {corr:.4} below {floor:.4}");
2322- if let Some(oracle) = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len(), 120) {2137+ let oracle = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len(), 120);
2323 let (c, _) = aligned_corr(&oracle, &decoded, 2500);2138 let (c, _) = aligned_corr(&oracle, &decoded, 2500);
2324 assert!(2139 assert!(
2325 c >= 0.99,2140 c >= 0.99,
2326 "{tag}: internal decode vs external decode corr {c:.4}"2141 "{tag}: internal decode vs external decode corr {c:.4}"
2327 );2142 );
2328- }
2329 if Command::new("gst-launch-1.0")2143 if Command::new("gst-launch-1.0")
2330 .arg("--version")2144 .arg("--version")
2331 .output()2145 .output()
@@ -2439,7 +2253,6 @@ fn silk_stereo_speech_roundtrip() {
2439 mono_floor[ch]2253 mono_floor[ch]
2440 );2254 );
2441 }2255 }
2442- if Command::new("ffmpeg").arg("-version").output().is_ok() {
2443 let path = temp_path(&format!("silk-stereo-{tag}.opus"));2256 let path = temp_path(&format!("silk-stereo-{tag}.opus"));
2444 write_ogg_opus(2257 write_ogg_opus(
2445 &path,2258 &path,
@@ -2449,7 +2262,7 @@ fn silk_stereo_speech_roundtrip() {
2449 total,2262 total,
2450 enc.look_ahead(frame) as i64,2263 enc.look_ahead(frame) as i64,
2451 );2264 );
2452- let out = Command::new("ffmpeg")2265+ let out = ec_testkit::ffmpeg()
2453 .args(["-v", "warning", "-c:a", "libopus", "-i"])2266 .args(["-v", "warning", "-c:a", "libopus", "-i"])
2454 .arg(&path)2267 .arg(&path)
2455 .args(["-f", "null", "-"])2268 .args(["-f", "null", "-"])
@@ -2465,8 +2278,7 @@ fn silk_stereo_speech_roundtrip() {
2465 let location = format!("location={}", path.display());2278 let location = format!("location={}", path.display());
2466 let out = Command::new("gst-launch-1.0")2279 let out = Command::new("gst-launch-1.0")
2467 .args([2280 .args([
2468- "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!",2281+ "-q", "filesrc", &location, "!", "oggdemux", "!", "opusdec", "!", "fakesink",
2469- "fakesink",
2470 ])2282 ])
2471 .output()2283 .output()
2472 .unwrap();2284 .unwrap();
@@ -2476,21 +2288,12 @@ fn silk_stereo_speech_roundtrip() {
2476 let _ = fs::remove_file(&path);2288 let _ = fs::remove_file(&path);
2477 }2289 }
2478 }2290 }
2479-}
2480 /// Reference oracle decode of `packets` as Ogg-Opus, or `None` without ffmpeg.2291 /// Reference oracle decode of `packets` as Ogg-Opus, or `None` without ffmpeg.
2481 /// `pre_skip` must be the encoder's advertised [`Encoder::look_ahead`] for2292 /// `pre_skip` must be the encoder's advertised [`Encoder::look_ahead`] for
2482 /// these packets: it is what the oracle trims off the front, so a caller that2293 /// these packets: it is what the oracle trims off the front, so a caller that
2483 /// compares sample-for-sample against its own decode at that same offset only2294 /// compares sample-for-sample against its own decode at that same offset only
2484 /// lines up when the two agree.2295 /// lines up when the two agree.
2485-fn oracle_decode(2296+fn oracle_decode(name: &str, packets: &[Vec<u8>], samples: usize, pre_skip: usize) -> Vec<f32> {
2486- name: &str,
2487- packets: &[Vec<u8>],
2488- samples: usize,
2489- pre_skip: usize,
2490-) -> Option<Vec<f32>> {
2491- if Command::new("ffmpeg").arg("-version").output().is_err() {
2492- return None;
2493- }
2494 let path = temp_path(&format!("{name}.opus"));2297 let path = temp_path(&format!("{name}.opus"));
2495 write_ogg_opus(2298 write_ogg_opus(
2496 &path,2299 &path,
@@ -2500,7 +2303,7 @@ fn oracle_decode(
2500 samples,2303 samples,
2501 pre_skip as i64,2304 pre_skip as i64,
2502 );2305 );
2503- let out = Command::new("ffmpeg")2306+ let out = ec_testkit::ffmpeg()
2504 .args(["-v", "warning", "-c:a", "libopus", "-i"])2307 .args(["-v", "warning", "-c:a", "libopus", "-i"])
2505 .arg(&path)2308 .arg(&path)
2506 .args(["-f", "null", "-"])2309 .args(["-f", "null", "-"])
@@ -2519,10 +2322,8 @@ fn oracle_decode(
2519 fn silk_sources() -> Vec<(&'static str, Vec<f32>)> {2322 fn silk_sources() -> Vec<(&'static str, Vec<f32>)> {
2520 let wav = fixture("wav16-mono-48000.wav");2323 let wav = fixture("wav16-mono-48000.wav");
2521 let mut sources = vec![("synthetic", speech_like())];2324 let mut sources = vec![("synthetic", speech_like())];
2522- if wav.exists() {
2523 let w = read_wav_mono(&wav);2325 let w = read_wav_mono(&wav);
2524 sources.push(("wav16-mono-48000", w[..w.len().min(96000)].to_vec()));2326 sources.push(("wav16-mono-48000", w[..w.len().min(96000)].to_vec()));
2525- }
2526 sources2327 sources
2527 }2328 }
2528 2329
@@ -2662,13 +2463,12 @@ fn hybrid_fb_roundtrip() {
2662 (28.0..=36.0).contains(&kbps),2463 (28.0..=36.0).contains(&kbps),
2663 "{name}: {kbps:.1} kbps for a 32 kbps CBR target"2464 "{name}: {kbps:.1} kbps for a 32 kbps CBR target"
2664 );2465 );
2665- if let Some(oracle) = oracle_decode(&format!("hybrid-{name}"), &packets, pcm.len(), delay) {2466+ let oracle = oracle_decode(&format!("hybrid-{name}"), &packets, pcm.len(), delay);
2666 let n = oracle.len().min(decoded.len() - delay);2467 let n = oracle.len().min(decoded.len() - delay);
2667 let c = correlation(&oracle[..n], &decoded[delay..delay + n]);2468 let c = correlation(&oracle[..n], &decoded[delay..delay + n]);
2668 eprintln!("hybrid FB {name}: oracle vs ours corr {c:.4}");2469 eprintln!("hybrid FB {name}: oracle vs ours corr {c:.4}");
2669 assert!(c >= 0.95, "{name}: oracle corr {c:.4}");2470 assert!(c >= 0.95, "{name}: oracle corr {c:.4}");
2670 }2471 }
2671- }
2672 // SWB when asked for it, and the rest of the automatic hybrid range2472 // SWB when asked for it, and the rest of the automatic hybrid range
2673 // (SILK's share leaves CELT least at the bottom of it).2473 // (SILK's share leaves CELT least at the bottom of it).
2674 let speech = speech_like();2474 let speech = speech_like();
@@ -2788,8 +2588,7 @@ fn hybrid_shapes_roundtrip() {
2788 total,2588 total,
2789 pre_skip as i64,2589 pre_skip as i64,
2790 );2590 );
2791- if Command::new("ffmpeg").arg("-version").output().is_ok() {2591+ let out = ec_testkit::ffmpeg()
2792- let out = Command::new("ffmpeg")
2793 .args(["-v", "warning", "-c:a", "libopus", "-i"])2592 .args(["-v", "warning", "-c:a", "libopus", "-i"])
2794 .arg(&path)2593 .arg(&path)
2795 .args(["-f", "null", "-"])2594 .args(["-f", "null", "-"])
@@ -2797,7 +2596,6 @@ fn hybrid_shapes_roundtrip() {
2797 .unwrap();2596 .unwrap();
2798 let stderr = String::from_utf8_lossy(&out.stderr);2597 let stderr = String::from_utf8_lossy(&out.stderr);
2799 assert!(out.status.success(), "{tag}: ffmpeg decode: {stderr}");2598 assert!(out.status.success(), "{tag}: ffmpeg decode: {stderr}");
2800- }
2801 if Command::new("gst-launch-1.0")2599 if Command::new("gst-launch-1.0")
2802 .arg("--version")2600 .arg("--version")
2803 .output()2601 .output()
@@ -2823,2189 +2621,66 @@ fn hybrid_shapes_roundtrip() {
2823 assert!(toc.stereo);2621 assert!(toc.stereo);
2824 }2622 }
2825 2623
2826-// ---------------------------------------------------------------------------2624+#[test]
2827-// Encoder library gate vs ffmpeg libopus (encoders-only comparison)2625+fn opus_compare_err_pinned_against_c() {
2828-// ---------------------------------------------------------------------------2626+ let _timing = timing_shared();
2829-//2627+ const N: usize = 48000 * 4;
2830-// Both the ec-opus encoder and ffmpeg's libopus encoder encode the same real2628+ let t: Vec<f64> = (0..N).map(|i| i as f64 / 48000.0).collect();
2831-// source PCM; BOTH bitstreams are decoded through ec-opus's own decoder, so
2832-// the gap isolates the encoders (the decoder is held constant). A 14-row sweep
2833-// (7 real sources × {64, 96} kbps) lands in `lanes/opus-gate-r1.sweep.txt`.
2834-// `#[ignore]`'d: it shells out to ffmpeg and walks a multi-gigabyte library.
2835-
2836-/// Expand a leading `~` to the home directory (the std `Path` API cannot).
2837-fn shellexpand(p: &str) -> PathBuf {
2838- if let Some(rest) = p.strip_prefix("~/")
2839- && let Some(home) = std::env::var_os("HOME")
2840- {
2841- return PathBuf::from(home).join(rest);
2842- }
2843- PathBuf::from(p)
2844-}
2845 2629
2846-/// Decode any source into interleaved f32, 48 kHz, stereo, capped at `secs`.2630+ let base = |c: usize| -> Vec<f64> {
2847-fn ffmpeg_decode_pcm(path: &Path, secs: f64) -> Vec<f32> {2631+ let ph = 0.5 * c as f64;
2848- let out = Command::new("ffmpeg")2632+ let ph2 = 0.3 * c as f64;
2849- .args(["-v", "error", "-i"])2633+ t.iter()
2850- .arg(path)2634+ .map(|&tt| {
2851- .args([2635+ 0.3 * (2.0 * std::f64::consts::PI * 440.0 * tt).sin()
2852- "-vn",2636+ + 0.2 * (2.0 * std::f64::consts::PI * 442.0 * tt + ph).sin()
2853- "-t",2637+ + 0.15 * (2.0 * std::f64::consts::PI * (800.0 + 200.0 * tt) * tt + ph2).sin()
2854- &format!("{secs}"),2638+ })
2855- "-ac",
2856- "2",
2857- "-ar",
2858- "48000",
2859- "-f",
2860- "f32le",
2861- "-acodec",
2862- "pcm_f32le",
2863- "-",
2864- ])
2865- .output()
2866- .expect("ffmpeg runs");
2867- assert!(
2868- out.status.success(),
2869- "ffmpeg source decode failed for {}: {}",
2870- path.display(),
2871- String::from_utf8_lossy(&out.stderr)
2872- );
2873- out.stdout
2874- .as_chunks::<4>()
2875- .0
2876- .iter()
2877- .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
2878 .collect()2639 .collect()
2879-}
2880-
2881-/// Encode `src` to an Ogg/Opus file with ffmpeg's libopus at `kbps` (VBR on),
2882-/// capped at `secs`. The realised rate is read back from the output file size.
2883-fn ffmpeg_encode_libopus(src: &Path, kbps: u32, out: &Path, secs: f64) {
2884- let res = Command::new("ffmpeg")
2885- .args(["-y", "-v", "error", "-i"])
2886- .arg(src)
2887- .args([
2888- "-vn",
2889- "-t",
2890- &format!("{secs}"),
2891- "-ac",
2892- "2",
2893- "-ar",
2894- "48000",
2895- "-c:a",
2896- "libopus",
2897- "-b:a",
2898- &format!("{kbps}k"),
2899- "-vbr",
2900- "on",
2901- ])
2902- .arg(out)
2903- .output()
2904- .expect("ffmpeg runs");
2905- assert!(
2906- res.status.success(),
2907- "ffmpeg libopus encode failed for {} at {kbps}k: {}",
2908- src.display(),
2909- String::from_utf8_lossy(&res.stderr)
2910- );
2911-}
2912-
2913-/// Lag-scan `decoded` against `source` over ±`max_lag` samples by mean-channel
2914-/// correlation, then emit a `source`-length aligned copy of `decoded`. The lag
2915-/// search runs on the first 10 s only (the task spec) — the encoder/decoder
2916-/// algorithmic delay is constant, so the peak found there holds for the whole
2917-/// file — and the correlation is computed inline without per-lag allocations.
2918-/// The delay lands the peak at a positive lag; the symmetric scan keeps the
2919-/// gate honest if a reference decoder shifts the other way.
2920-fn align_to_source(
2921- source: &[f32],
2922- decoded: &[f32],
2923- channels: usize,
2924- max_lag: usize,
2925-) -> (i32, Vec<f32>) {
2926- let sf = source.len() / channels;
2927- let df = decoded.len() / channels;
2928- let scan_frames = sf.min(df).min(48000 * 10);
2929- let scan = max_lag.min(scan_frames);
2930- let mut best = -1.0f64;
2931- let mut best_lag = 0i32;
2932- for lag in -(scan as i32)..=(scan as i32) {
2933- let i0 = if lag < 0 { (-lag) as usize } else { 0 };
2934- let j0 = if lag < 0 { 0 } else { lag as usize };
2935- let len = scan_frames.saturating_sub(i0.max(j0));
2936- if len < 4800 {
2937- continue;
2938- }
2939- let mut cacc = 0.0f64;
2940- for ch in 0..channels {
2941- let (mut sxy, mut sxx, mut syy) = (0.0f64, 0.0f64, 0.0f64);
2942- for i in 0..len {
2943- let a = source[(i0 + i) * channels + ch] as f64;
2944- let b = decoded[(j0 + i) * channels + ch] as f64;
2945- sxy += a * b;
2946- sxx += a * a;
2947- syy += b * b;
2948- }
2949- if sxx > 0.0 && syy > 0.0 {
2950- cacc += sxy / (sxx * syy).sqrt();
2951- }
2952- }
2953- let c = cacc / channels as f64;
2954- if c > best {
2955- best = c;
2956- best_lag = lag;
2957- }
2958- }
2959- // Build a source-length aligned copy using the chosen lag.
2960- let mut aligned = vec![0.0f32; sf * channels];
2961- let i0 = if best_lag < 0 {
2962- (-best_lag) as usize
2963- } else {
2964- 0
2965 };2640 };
2966- let j0 = if best_lag < 0 { 0 } else { best_lag as usize };2641+ let to_i16s = |sig: &[f64]| -> Vec<i16> {
2967- let len = sf.saturating_sub(i0).min(df.saturating_sub(j0));2642+ sig.iter()
2968- for i in 0..len {2643+ .map(|&v| (v.clamp(-1.0, 1.0) * 32767.0) as i16)
2969- for ch in 0..channels {2644+ .collect()
2970- aligned[(i0 + i) * channels + ch] = decoded[(j0 + i) * channels + ch];2645+ };
2971- }2646+ let stereo = |l: &[f64], r: &[f64]| -> Vec<i16> {
2972- }2647+ let mut o = Vec::with_capacity(N * 2);
2973- (best_lag, aligned)2648+ let li = to_i16s(l);
2974-}2649+ let ri = to_i16s(r);
2975-2650+ for i in 0..N {
2976-/// Mean-channel normalized cross-correlation between two interleaved signals,2651+ o.push(li[i]);
2977-/// computed inline (no per-channel Vec allocation).2652+ o.push(ri[i]);
2978-fn corr_interleaved(a: &[f32], b: &[f32], channels: usize) -> f64 {
2979- let n = (a.len() / channels).min(b.len() / channels);
2980- let mut acc = 0.0f64;
2981- for ch in 0..channels {
2982- let (mut sxy, mut sxx, mut syy) = (0.0f64, 0.0f64, 0.0f64);
2983- for i in 0..n {
2984- let av = a[i * channels + ch] as f64;
2985- let bv = b[i * channels + ch] as f64;
2986- sxy += av * bv;
2987- sxx += av * av;
2988- syy += bv * bv;
2989- }
2990- if sxx > 0.0 && syy > 0.0 {
2991- acc += sxy / (sxx * syy).sqrt();
2992- }
2993- }
2994- acc / channels as f64
2995 }2653 }
2654+ o
2655+ };
2996 2656
2997-/// Per-second correlation statistics: `(min_second_corr, seconds_below_0.9)`,2657+ let b0 = base(0);
2998-/// computed inline without per-second Vec allocation.2658+ let b1 = base(1);
2999-fn per_second_corr(source: &[f32], decoded: &[f32], channels: usize) -> (f64, u32) {
3000- let n = (source.len() / channels).min(decoded.len() / channels);
3001- let sec = 48000usize;
3002- let mut min_c = 1.0f64;
3003- let mut drops = 0u32;
3004- let mut start = 0usize;
3005- while start + sec <= n {
3006- let mut acc = 0.0f64;
3007- for ch in 0..channels {
3008- let (mut sxy, mut sxx, mut syy) = (0.0f64, 0.0f64, 0.0f64);
3009- for i in 0..sec {
3010- let a = source[(start + i) * channels + ch] as f64;
3011- let b = decoded[(start + i) * channels + ch] as f64;
3012- sxy += a * b;
3013- sxx += a * a;
3014- syy += b * b;
3015- }
3016- if sxx > 0.0 && syy > 0.0 {
3017- acc += sxy / (sxx * syy).sqrt();
3018- }
3019- }
3020- let c = acc / channels as f64;
3021- min_c = min_c.min(c);
3022- if c < 0.9 {
3023- drops += 1;
3024- }
3025- start += sec;
3026- }
3027- (min_c, drops)
3028-}
3029 2659
3030-#[test]2660+ let a = stereo(&b0, &b1);
3031-#[ignore = "library gate: hand-run 14-row sweep, 120s per source, needs ffmpeg libopus and the local ~/Music corpus (~12 min); the reelm@64k dropout that first failed it is fixed per lanes/opus-drop-r2.report.md, so only the corpus dependency keeps it out of the default suite"]2661+ let err_id = opus_compare_err(&a, &a, 2);
3032-fn encoder_library_gate_vs_libopus() {2662+ let q_id = opus_compare(&a, &a, 2);
3033- let _timing = timing_shared();2663+ assert_eq!(err_id, 0.0, "identical signals must give err=0");
3034- const SECS: f64 = 120.0; // 2 min cap; full 600s made the 14-row sweep infeasible2664+ assert_eq!(q_id, 100.0, "identical signals must give Q=100");
3035- const FRAME: usize = 960; // 20 ms at 48 kHz
3036- const CHANNELS: usize = 2;
3037- const MAX_LAG: usize = 2000;
3038 2665
3039- let sources: &[(&str, &str)] = &[2666+ // Case 2: mild perturbation (+0.5 dB on L, quiet 1500 Hz partial on L).
3040- ("nik", "~/Music/reeln.mp4"),2667+ let gain = 10f64.powf(0.5 / 10.0);
3041- ("reelo", "~/Music/reelo.mp3"),2668+ let lp: Vec<f64> = t
3042- ("her", "~/Music/reeli.mp3"),
3043- ("reell", "~/Music/reell.mp4"),
3044- ("reelm", "~/Music/reelm.wav"),
3045- ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),
3046- ("hein", "~/Downloads/reelm.mp3"),
3047- ];
3048- let only: Vec<String> = std::env::var("SWEEP_ONLY")
3049- .unwrap_or_default()
3050- .split(',')
3051- .filter(|s| !s.is_empty())
3052- .map(|s| s.trim().to_owned())
3053- .collect();
3054- let sources: Vec<(String, PathBuf)> = sources
3055 .iter()2669 .iter()
3056- .filter(|(tag, _)| only.is_empty() || only.iter().any(|o| o == tag))2670+ .zip(b0.iter())
3057- .map(|(tag, p)| (tag.to_string(), shellexpand(p)))2671+ .map(|(&tt, &bv)| bv * gain + 0.02 * (2.0 * std::f64::consts::PI * 1500.0 * tt).sin())
3058- .collect();
3059- assert!(!sources.is_empty(), "SWEEP_ONLY matched no sources");
3060-
3061- let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes");
3062- fs::create_dir_all(&lanes_dir).unwrap();
3063- let sweep_path = lanes_dir.join("opus-gate-r1.sweep.txt");
3064- let scratch = lanes_dir.join("opus-gate-r1.scratch.ogg");
3065-
3066- let mut rows: Vec<String> = Vec::new();
3067- let mut rate_violations: Vec<String> = Vec::new();
3068- let mut dropout_violations: Vec<String> = Vec::new();
3069-
3070- for (tag, src) in &sources {
3071- if !src.exists() {
3072- eprintln!("SKIP {tag}: missing {}", src.display());
3073- continue;
3074- }
3075- let source_pcm = ffmpeg_decode_pcm(src, SECS);
3076- let source_frames = source_pcm.len() / CHANNELS;
3077- assert!(source_frames > 48_000, "{tag}: source too short");
3078- let seconds = source_frames as f64 / 48000.0;
3079- let source_i16 = to_i16(&source_pcm);
3080-
3081- for &kbps in &[64u32, 96u32] {
3082- // Reference: ffmpeg libopus, VBR on, realised rate from file size.
3083- ffmpeg_encode_libopus(src, kbps, &scratch, SECS);
3084- let ref_bytes = fs::metadata(&scratch)
3085- .map(|m| m.len() as usize)
3086- .unwrap_or(0);
3087- let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
3088- let (ref_dec, ref_ch) = decode_ogg(&scratch);
3089- assert_eq!(ref_ch, CHANNELS, "{tag}@{kbps}: ref not stereo");
3090- let (_, ref_aligned) = align_to_source(&source_pcm, &ref_dec, CHANNELS, MAX_LAG);
3091-
3092- // Ours: ec-opus encoder at the reference's realised rate, decoded
3093- // by our own decoder; payload bytes give the realised rate.
3094- let mut enc = Encoder::new(48000, CHANNELS, Application::Audio).expect("encoder");
3095- enc.set_bitrate((ref_kbps * 1000.0).round() as u32);
3096- enc.set_vbr_constrained(true);
3097- let (ours_dec, ours_bytes) = roundtrip_own(&mut enc, &source_pcm, CHANNELS, FRAME);
3098- let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0;
3099- // Drop the zero-padded tail of the final frame to match the source.
3100- let ours_trim: Vec<f32> = ours_dec
3101- .into_iter()
3102- .take(source_frames * CHANNELS)
3103 .collect();2672 .collect();
3104- let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);2673+ let b = stereo(&lp, &b1);
3105- let ours_i16 = to_i16(&ours_aligned);2674+ let err = opus_compare_err(&a, &b, 2);
3106- let ref_i16 = to_i16(&ref_aligned);2675+ let q = opus_compare(&a, &b, 2);
3107-2676+ // Pinned to the C reference value (4.444987); tolerance absorbs libm
3108- // Equal-length i16 inputs for opus_compare (trim to common length).2677+ // transcendental rounding differences across toolchains.
3109- let cmp_frames = (source_i16.len() / CHANNELS)
3110- .min(ours_i16.len() / CHANNELS)
3111- .min(ref_i16.len() / CHANNELS);
3112- let trim = |v: &[i16]| -> Vec<i16> { v[..cmp_frames * CHANNELS].to_vec() };
3113- let s_i = trim(&source_i16);
3114- let o_i = trim(&ours_i16);
3115- let r_i = trim(&ref_i16);
3116- let q_ours = opus_compare(&s_i, &o_i, CHANNELS);
3117- let q_ref = opus_compare(&s_i, &r_i, CHANNELS);
3118- let err_ours = opus_compare_err(&s_i, &o_i, CHANNELS);
3119- let err_ref = opus_compare_err(&s_i, &r_i, CHANNELS);
3120- let err_ratio = if err_ref > 0.0 {
3121- err_ours / err_ref
3122- } else {
3123- f64::INFINITY
3124- };
3125-
3126- let corr_ours = corr_interleaved(&source_pcm, &ours_aligned, CHANNELS);
3127- let corr_ref = corr_interleaved(&source_pcm, &ref_aligned, CHANNELS);
3128- let gap = corr_ref - corr_ours;
3129- let (minsec_ours, drop_ours) = per_second_corr(&source_pcm, &ours_aligned, CHANNELS);
3130- let (minsec_ref, drop_ref) = per_second_corr(&source_pcm, &ref_aligned, CHANNELS);
3131- let rate_pct = (ours_kbps / ref_kbps - 1.0) * 100.0;
3132-
3133- if rate_pct.abs() > 5.0 {
3134- rate_violations.push(format!("{tag}@{kbps}k: rate {rate_pct:+.1}% (|>5%)"));
3135- }
3136- // Dropout gate: ours must not lose a second the reference kept.
3137- if drop_ours > 0 && drop_ref == 0 {
3138- dropout_violations.push(format!(
3139- "{tag}@{kbps}k: ours dropped {drop_ours}s below 0.9 corr, ref 0s"
3140- ));
3141- }
3142-
3143- println!(
3144- "{tag}@{kbps}k: ref {ref_kbps:.1} ours {ours_kbps:.1} kbps ({rate_pct:+.1}%), \
3145- corr o={corr_ours:.4} r={corr_ref:.4} gap={gap:+.4}, \
3146- Q o={q_ours:.2} r={q_ref:.2}, err_ratio {err_ratio:.3}, \
3147- minsec o={minsec_ours:.4} r={minsec_ref:.4}, drop o={drop_ours} r={drop_ref}"
3148- );
3149- rows.push(format!(
3150- "{tag}\t{kbps}\t{ours_kbps:.1}\t{ref_kbps:.1}\t{rate_pct:+.1}\t\
3151- {corr_ours:.4}\t{corr_ref:.4}\t{gap:+.4}\t\
3152- {q_ours:.2}\t{q_ref:.2}\t{err_ratio:.3}\t\
3153- {minsec_ours:.4}\t{minsec_ref:.4}\t{drop_ours}\t{drop_ref}"
3154- ));
3155- }
3156- }
3157- let _ = fs::remove_file(&scratch);
3158-
3159- let mut table = String::new();
3160- table.push_str("# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1)\n");
3161- table.push_str("# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo\n");
3162- table.push_str(
3163- "# source\tkbps\tours_kbps\tref_kbps\trate%\tcorr_ours\tcorr_ref\tgap\t\
3164- Q_ours\tQ_ref\terr_ratio\tminsec_ours\tminsec_ref\tdrop_ours\tdrop_ref\n",
3165- );
3166- for r in &rows {
3167- table.push_str(r);
3168- table.push('\n');
3169- }
3170- fs::write(&sweep_path, table).unwrap();
3171- println!("wrote {}", sweep_path.display());
3172-
3173- // Rate gate: report violations, never panic.
3174- if !rate_violations.is_empty() {
3175- eprintln!("RATE GATE violations (|rate%| > 5):");
3176- for v in &rate_violations {
3177- eprintln!(" {v}");
3178- }
3179- } else {
3180- println!("RATE GATE: all rows within ±5%");
3181- }
3182- // Dropout gate: hard fail — a second the reference kept must not drop out.
3183 assert!(2678 assert!(
3184- dropout_violations.is_empty(),
3185- "DROPOUT GATE failed (ours dropped seconds ref kept):\n {}",
3186- dropout_violations.join("\n ")
3187- );
3188- println!("DROPOUT GATE: passed (no ours-only dropouts)");
3189-}
3190-
3191-// ---------------------------------------------------------------------------
3192-// SILK / speech-rate library gate vs libopus (lane opus-silk r1).
3193-//
3194-// Source: ~/Music/reelm.wav (real interview speech) downmixed to MONO. Rows:
3195-// 12k NB, 16k NB, 24k WB (SILK), 32k hybrid. Ours via Encoder::new(48000, 1,
3196-// Application::Voip) with set_bitrate and set_bandwidth/set_mode as needed so
3197-// Voip really picks SILK/Hybrid — the mode each row took is printed from the
3198-// first packet's TOC config byte (RFC 6716 §3.1). Reference: ffmpeg libopus
3199-// -application voip -b:a <rate>, mono, VBR on. RATE GATE ±5%, DROPOUT GATE.
3200-// SIGN RULE (verbatim): gap = ref_corr - ours_corr; MORE NEGATIVE = OURS BETTER.
3201-// Run: cargo test -p ec-opus --release --test conformance \
3202-// silk_library_gate_vs_libopus -- --ignored --nocapture
3203-// ---------------------------------------------------------------------------
3204-
3205-/// Mode label from a packet's TOC config byte (RFC 6716 §3.1): config = toc>>3.
3206-fn toc_mode_label(toc: u8) -> &'static str {
3207- match toc >> 3 {
3208- 0..=3 => "SILK-NB",
3209- 4..=7 => "SILK-MB",
3210- 8..=11 => "SILK-WB",
3211- 12 | 13 => "Hybrid-SWB",
3212- 14 | 15 => "Hybrid-FB",
3213- 16..=31 => "CELT",
3214- _ => "??",
3215- }
3216-}
3217-
3218-// corner-cut: near-duplicate of ffmpeg_decode_pcm / ffmpeg_encode_libopus with
3219-// -ac 1 and -application voip. Parameterising the existing helpers would touch
3220-// the stereo gate's callsites; keep this lane self-contained. Ceiling: only the
3221-// SILK gate needs mono voip — merge when a second mono consumer appears.
3222-/// Decode any source into interleaved f32, 48 kHz, MONO, capped at `secs`.
3223-fn ffmpeg_decode_pcm_mono(path: &Path, secs: f64) -> Vec<f32> {
3224- let out = Command::new("ffmpeg")
3225- .args(["-v", "error", "-i"])
3226- .arg(path)
3227- .args([
3228- "-vn",
3229- "-t",
3230- &format!("{secs}"),
3231- "-ac",
3232- "1",
3233- "-ar",
3234- "48000",
3235- "-f",
3236- "f32le",
3237- "-acodec",
3238- "pcm_f32le",
3239- "-",
3240- ])
3241- .output()
3242- .expect("ffmpeg runs");
3243- assert!(
3244- out.status.success(),
3245- "ffmpeg mono decode failed for {}: {}",
3246- path.display(),
3247- String::from_utf8_lossy(&out.stderr)
3248- );
3249- out.stdout
3250- .as_chunks::<4>()
3251- .0
3252- .iter()
3253- .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
3254- .collect()
3255-}
3256-
3257-/// Encode `src` to a mono Ogg/Opus file with ffmpeg libopus, VoIP application,
3258-/// at `kbps` (VBR on), capped at `secs`. Realised rate read back from file size.
3259-fn ffmpeg_encode_libopus_mono_voip(src: &Path, kbps: u32, out: &Path, secs: f64) {
3260- let res = Command::new("ffmpeg")
3261- .args(["-y", "-v", "error", "-i"])
3262- .arg(src)
3263- .args([
3264- "-vn",
3265- "-t",
3266- &format!("{secs}"),
3267- "-ac",
3268- "1",
3269- "-ar",
3270- "48000",
3271- "-c:a",
3272- "libopus",
3273- "-application",
3274- "voip",
3275- "-b:a",
3276- &format!("{kbps}k"),
3277- "-vbr",
3278- "on",
3279- ])
3280- .arg(out)
3281- .output()
3282- .expect("ffmpeg runs");
3283- assert!(
3284- res.status.success(),
3285- "ffmpeg libopus mono voip encode failed at {kbps}k: {}",
3286- String::from_utf8_lossy(&res.stderr)
3287- );
3288-}
3289-
3290-/// Same as [`roundtrip_own`] but also returns the encoded packets, so the SILK
3291-/// gate can re-decode them through ffmpeg (decoder-symmetric comparison).
3292-fn roundtrip_own_packets(
3293- enc: &mut Encoder,
3294- pcm: &[f32],
3295- channels: usize,
3296- frame: usize,
3297-) -> (Vec<f32>, Vec<Vec<u8>>, usize) {
3298- let mut dec = Decoder::new(48000, channels).unwrap();
3299- let mut out = vec![0u8; 1500];
3300- let mut decoded = Vec::new();
3301- let mut packets = Vec::new();
3302- let mut buf = vec![0.0f32; 5760 * channels];
3303- let mut bytes = 0usize;
3304- let mut padded = Vec::new();
3305- for block in pcm.chunks(frame * channels) {
3306- let block = if block.len() < frame * channels {
3307- padded.clear();
3308- padded.extend_from_slice(block);
3309- padded.resize(frame * channels, 0.0);
3310- &padded[..]
3311- } else {
3312- block
3313- };
3314- let len = enc.encode_float(block, frame, &mut out).expect("encode");
3315- bytes += len;
3316- packets.push(out[..len].to_vec());
3317- let n = dec.decode_float(&out[..len], &mut buf).expect("decode");
3318- assert_eq!(n, frame, "decoded frame size");
3319- assert_eq!(
3320- dec.final_range(),
3321- enc.final_range(),
3322- "range state diverged between encoder and decoder"
3323- );
3324- decoded.extend_from_slice(&buf[..n * channels]);
3325- }
3326- (decoded, packets, bytes)
3327-}
3328-
3329-/// First audio packet's TOC byte from Ogg-Opus bytes (skips OpusHead/OpusTags).
3330-fn first_audio_toc(ogg: &[u8]) -> u8 {
3331- for p in ogg_packets(ogg) {
3332- if p.len() >= 8 && (&p[..8] == b"OpusHead" || &p[..8] == b"OpusTags") {
3333- continue;
3334- }
3335- if !p.is_empty() {
3336- return p[0];
3337- }
3338- }
3339- 0
3340-}
3341-
3342-#[test]
3343-#[ignore = "library gate: hand-run mono VoIP sweep; blocked until ~/Music/reelm.wav is back in the corpus (hard-asserts src.exists) and it is a multi-minute ffmpeg run, not a suite test"]
3344-fn silk_library_gate_vs_libopus() {
3345- let _timing = timing_shared();
3346- const SECS: f64 = 120.0; // 2 min cap
3347- const FRAME: usize = 960; // 20 ms at 48 kHz
3348- const CHANNELS: usize = 1; // MONO
3349- const MAX_LAG: usize = 2000;
3350-
3351- let src = shellexpand("~/Music/reelm.wav");
3352- assert!(src.exists(), "source missing: {}", src.display());
3353-
3354- let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes");
3355- fs::create_dir_all(&lanes_dir).unwrap();
3356- let sweep_path = lanes_dir.join("opus-mode-r1.sweep.txt");
3357- let ref_ogg = temp_path("opus-silk-r2-ref.opus");
3358- let ours_ogg = temp_path("opus-silk-r2-ours.opus");
3359-
3360- // Source PCM: mono, 48 kHz.
3361- let source_pcm = ffmpeg_decode_pcm_mono(&src, SECS);
3362- let source_frames = source_pcm.len() / CHANNELS;
3363- assert!(source_frames > 48_000, "source too short");
3364- let seconds = source_frames as f64 / 48000.0;
3365-
3366- // (label, kbps, forced bandwidth, forced mode, reference lowpass cutoff).
3367- // cutoff: NB 4 kHz, WB 8 kHz, hybrid-FB unfiltered (None) — compare each
3368- // encoder only against the band it can actually reproduce.
3369- type Row = (
3370- &'static str,
3371- u32,
3372- Option<Bandwidth>,
3373- Option<Mode>,
3374- Option<f64>,
3375- );
3376- let rows: &[Row] = &[
3377- // All rows auto since lane opus-mode: the selector is libopus's, so
3378- // the mode must match the reference's (asserted below) and the
3379- // comparison is full-band (no lowpass).
3380- ("12k", 12, None, None, None),
3381- ("16k", 16, None, None, None),
3382- ("24k", 24, None, None, None),
3383- ("32k", 32, None, None, None),
3384- ];
3385-
3386- let mut out_rows: Vec<String> = Vec::new();
3387- let mut rate_violations: Vec<String> = Vec::new();
3388- let mut dropout_violations: Vec<String> = Vec::new();
3389- let mut lag_violations: Vec<String> = Vec::new();
3390-
3391- for &(tag, kbps, bw, mode, cutoff) in rows {
3392- // Band-limited reference source for this row's corr/opus_compare.
3393- let ref_source: Vec<f32> = match cutoff {
3394- Some(hz) => lowpass(&source_pcm, hz),
3395- None => source_pcm.clone(),
3396- };
3397- let ref_source_i16 = to_i16(&ref_source);
3398-
3399- // Reference: ffmpeg libopus, mono, voip, VBR; realised rate from size.
3400- ffmpeg_encode_libopus_mono_voip(&src, kbps, &ref_ogg, SECS);
3401- let ref_bytes = fs::metadata(&ref_ogg)
3402- .map(|m| m.len() as usize)
3403- .unwrap_or(0);
3404- let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
3405- // SYMMETRY: ref decoded through ffmpeg libopus (the reference decoder),
3406- // NOT our own decoder — so both sides cross the same decoder. (r1 used
3407- // decode_ogg, our own MultistreamDecoder, for the ref side.)
3408- let ref_dec = ffmpeg_decode(&ref_ogg, CHANNELS).expect("ffmpeg libopus decode of ref");
3409- let ref_trim: Vec<f32> = ref_dec.into_iter().take(source_frames * CHANNELS).collect();
3410- let (lag_ref, ref_aligned) = align_to_source(&source_pcm, &ref_trim, CHANNELS, MAX_LAG);
3411- // REF MODE: libopus's actual mode from its first audio packet TOC.
3412- let ref_ogg_bytes = fs::read(&ref_ogg).expect("read ref ogg");
3413- let ref_mode = toc_mode_label(first_audio_toc(&ref_ogg_bytes));
3414-
3415- // Ours: ec-opus Voip at the reference's realised rate.
3416- let mut enc = Encoder::new(48000, CHANNELS, Application::Voip).expect("encoder");
3417- enc.set_bitrate((ref_kbps * 1000.0).round() as u32);
3418- if let Some(b) = bw {
3419- enc.set_bandwidth(Some(b));
3420- }
3421- if let Some(m) = mode {
3422- enc.set_mode(Some(m));
3423- }
3424- enc.set_vbr_constrained(true);
3425- let pre_skip = enc.look_ahead(FRAME) as i64;
3426-
3427- // Probe which mode the encoder actually picked, from the first TOC byte.
3428- let mut probe = enc.clone();
3429- let mut toc_buf = [0u8; 1500];
3430- probe
3431- .encode_float(&source_pcm[..FRAME * CHANNELS], FRAME, &mut toc_buf)
3432- .expect("encode probe");
3433- let mode_label = toc_mode_label(toc_buf[0]);
3434- assert_eq!(
3435- ref_mode, mode_label,
3436- "{tag}: mode mismatch ref={ref_mode} ours={mode_label} (MODE GATE)"
3437- );
3438-
3439- // Own-decoder roundtrip (range-coder invariant) + packet capture.
3440- let (ours_own_dec, ours_packets, ours_bytes) =
3441- roundtrip_own_packets(&mut enc, &source_pcm, CHANNELS, FRAME);
3442- let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0;
3443-
3444- // SYMMETRY: re-decode OUR packets through ffmpeg libopus too.
3445- write_ogg_opus(
3446- &ours_ogg,
3447- &ours_packets,
3448- opus_head(CHANNELS, pre_skip as u16, None),
3449- CHANNELS,
3450- source_frames,
3451- pre_skip,
3452- );
3453- let ours_dec = ffmpeg_decode(&ours_ogg, CHANNELS).expect("ffmpeg libopus decode of ours");
3454- let ours_trim: Vec<f32> = ours_dec
3455- .into_iter()
3456- .take(source_frames * CHANNELS)
3457- .collect();
3458- let (lag_ours, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);
3459-
3460- // Own-decoder aligned (extra column: decoder drift visibility).
3461- let ours_own_trim: Vec<f32> = ours_own_dec
3462- .into_iter()
3463- .take(source_frames * CHANNELS)
3464- .collect();
3465- let (_, ours_own_aligned) = align_to_source(&source_pcm, &ours_own_trim, CHANNELS, MAX_LAG);
3466-
3467- // LAG GATE: a lag at the scan bound is an invalid measurement, not a result.
3468- if (lag_ours as i64).abs() >= MAX_LAG as i64 {
3469- lag_violations.push(format!(
3470- "{tag}: ours lag {lag_ours} hit scan bound {MAX_LAG}"
3471- ));
3472- }
3473- if (lag_ref as i64).abs() >= MAX_LAG as i64 {
3474- lag_violations.push(format!("{tag}: ref lag {lag_ref} hit scan bound {MAX_LAG}"));
3475- }
3476-
3477- let ours_i16 = to_i16(&ours_aligned);
3478- let ref_i16 = to_i16(&ref_aligned);
3479- let cmp_frames = (ref_source_i16.len() / CHANNELS)
3480- .min(ours_i16.len() / CHANNELS)
3481- .min(ref_i16.len() / CHANNELS);
3482- let trim = |v: &[i16]| -> Vec<i16> { v[..cmp_frames * CHANNELS].to_vec() };
3483- let s_i = trim(&ref_source_i16);
3484- let o_i = trim(&ours_i16);
3485- let r_i = trim(&ref_i16);
3486- let q_ours = opus_compare(&s_i, &o_i, CHANNELS);
3487- let q_ref = opus_compare(&s_i, &r_i, CHANNELS);
3488- let err_ours = opus_compare_err(&s_i, &o_i, CHANNELS);
3489- let err_ref = opus_compare_err(&s_i, &r_i, CHANNELS);
3490- let err_ratio = if err_ref > 0.0 {
3491- err_ours / err_ref
3492- } else {
3493- f64::INFINITY
3494- };
3495-
3496- // Primary corr: band-limited reference. Secondary: full-band source.
3497- let corr_ours_bl = corr_interleaved(&ref_source, &ours_aligned, CHANNELS);
3498- let corr_ref_bl = corr_interleaved(&ref_source, &ref_aligned, CHANNELS);
3499- let gap = corr_ref_bl - corr_ours_bl; // SIGN RULE: more negative = ours better
3500- let corr_ours_fb = corr_interleaved(&source_pcm, &ours_aligned, CHANNELS);
3501- let corr_ref_fb = corr_interleaved(&source_pcm, &ref_aligned, CHANNELS);
3502- let corr_ours_owndec = corr_interleaved(&ref_source, &ours_own_aligned, CHANNELS);
3503- let (minsec_ours, drop_ours) = per_second_corr(&ref_source, &ours_aligned, CHANNELS);
3504- let (minsec_ref, drop_ref) = per_second_corr(&ref_source, &ref_aligned, CHANNELS);
3505- let rate_pct = (ours_kbps / ref_kbps - 1.0) * 100.0;
3506-
3507- if rate_pct.abs() > 5.0 {
3508- rate_violations.push(format!("{tag}: rate {rate_pct:+.1}% (|>5%)"));
3509- }
3510- if drop_ours > 0 && drop_ref == 0 {
3511- dropout_violations.push(format!(
3512- "{tag}: ours dropped {drop_ours}s below 0.9 corr, ref 0s"
3513- ));
3514- }
3515- let row = format!(
3516- "{tag}: ref_mode={ref_mode} mode={mode_label}, ref {ref_kbps:.1} ours {ours_kbps:.1} kbps ({rate_pct:+.1}%), \
3517- lag o={lag_ours} r={lag_ref}, \
3518- corr_bl o={corr_ours_bl:.4} r={corr_ref_bl:.4} gap={gap:+.4}, \
3519- corr_fb o={corr_ours_fb:.4} r={corr_ref_fb:.4}, corr_owndec o={corr_ours_owndec:.4}, \
3520- Q o={q_ours:.2} r={q_ref:.2}, err_ratio {err_ratio:.3}, \
3521- minsec o={minsec_ours:.4} r={minsec_ref:.4}, drop o={drop_ours} r={drop_ref}"
3522- );
3523- println!("{row}");
3524- out_rows.push(row);
3525- }
3526- let _ = fs::remove_file(&ref_ogg);
3527- let _ = fs::remove_file(&ours_ogg);
3528-
3529- // Rate gate: report violations, never panic.
3530- let rate_gate = if rate_violations.is_empty() {
3531- "RATE GATE: all rows within ±5%".to_string()
3532- } else {
3533- let mut s = "RATE GATE violations (|rate%| > 5):".to_string();
3534- for v in &rate_violations {
3535- s.push_str("\n ");
3536- s.push_str(v);
3537- }
3538- s
3539- };
3540- if rate_violations.is_empty() {
3541- println!("{rate_gate}");
3542- } else {
3543- eprintln!("{rate_gate}");
3544- }
3545- // Lag gate: hard fail — a measurement at the scan bound is not a result.
3546- assert!(
3547- lag_violations.is_empty(),
3548- "LAG GATE failed (lag at scan bound):\n {}",
3549- lag_violations.join("\n ")
3550- );
3551- let lag_gate = "LAG GATE: passed (no lag at scan bound)";
3552- println!("{lag_gate}");
3553- // Dropout gate: hard fail — a second the reference kept must not drop out.
3554- assert!(
3555- dropout_violations.is_empty(),
3556- "DROPOUT GATE failed (ours dropped seconds ref kept):\n {}",
3557- dropout_violations.join("\n ")
3558- );
3559- let drop_gate = "DROPOUT GATE: passed (no ours-only dropouts)";
3560- println!("{drop_gate}");
3561-
3562- // Sweep file: raw rows + GATE lines (lane deliverable).
3563- let mut table = String::new();
3564- table.push_str("# ec-opus SILK/speech-rate gate vs ffmpeg libopus (r2)\n");
3565- table.push_str("# mono, 120s cap, VBR, 48kHz, Application::Voip; source reelm.wav\n");
3566- table.push_str("# r2: symmetric ffmpeg-libopus decode (both sides), lag gate, band-limited ref, ref mode\n");
3567- for r in &out_rows {
3568- table.push_str(r);
3569- table.push('\n');
3570- }
3571- table.push_str(&rate_gate);
3572- table.push('\n');
3573- table.push_str(lag_gate);
3574- table.push('\n');
3575- table.push_str(drop_gate);
3576- table.push('\n');
3577- fs::write(&sweep_path, table).unwrap();
3578- println!("wrote {}", sweep_path.display());
3579-}
3580-
3581-// ---------------------------------------------------------------------------
3582-// ORACLE: decode both our packets and ffmpeg-libopus ref packets through our
3583-// own SilkDecoder, read back the per-frame `Indices`, and print side-by-side
3584-// for the worst seconds to name the divergence mechanism.
3585-// Run: SWEEP_ONLY=reelm cargo test -p ec-opus --release --test conformance \
3586-// silk_silkq_oracle -- --ignored --nocapture
3587-// ---------------------------------------------------------------------------
3588-#[test]
3589-#[ignore = "probe: per-frame SILK Indices side-by-side oracle dump; unblocks when ~/Music/reelm.wav is back in the corpus (hard-asserts src.exists)"]
3590-fn silk_silkq_oracle() {
3591- let _timing = timing_shared();
3592- const SECS: f64 = 120.0;
3593- const FRAME: usize = 960; // 20 ms at 48 kHz
3594- const CHANNELS: usize = 1;
3595- const KBPS: u32 = 12;
3596- const TARGET_SECS: &[usize] = &[3, 39, 51, 5, 1];
3597-
3598- let src = shellexpand("~/Music/reelm.wav");
3599- assert!(src.exists(), "source missing: {}", src.display());
3600- let source_pcm = ffmpeg_decode_pcm_mono(&src, SECS);
3601-
3602- let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes");
3603- fs::create_dir_all(&lanes_dir).unwrap();
3604- let ref_ogg = temp_path("opus-silkq-oracle-ref.opus");
3605-
3606- // Reference: ffmpeg libopus mono voip at 12k.
3607- ffmpeg_encode_libopus_mono_voip(&src, KBPS, &ref_ogg, SECS);
3608- let ref_ogg_bytes = fs::read(&ref_ogg).expect("read ref ogg");
3609- let ref_packets: Vec<Vec<u8>> = ogg_packets(&ref_ogg_bytes)
3610- .into_iter()
3611- .skip(2)
3612- .filter(|p| !p.is_empty())
3613- .collect();
3614- let _ = fs::remove_file(&ref_ogg);
3615-
3616- // Ours: ec-opus Voip at 12k.
3617- let mut enc = Encoder::new(48000, CHANNELS, Application::Voip).expect("encoder");
3618- enc.set_bitrate(KBPS * 1000);
3619- enc.set_vbr_constrained(true);
3620- let mut out = vec![0u8; 1500];
3621- let mut ours_packets: Vec<Vec<u8>> = Vec::new();
3622- let mut padded = Vec::new();
3623- for block in source_pcm.chunks(FRAME * CHANNELS) {
3624- let block = if block.len() < FRAME * CHANNELS {
3625- padded.clear();
3626- padded.extend_from_slice(block);
3627- padded.resize(FRAME * CHANNELS, 0.0);
3628- &padded[..]
3629- } else {
3630- block
3631- };
3632- let len = enc.encode_float(block, FRAME, &mut out).expect("encode");
3633- ours_packets.push(out[..len].to_vec());
3634- }
3635-
3636- let ours_ix = collect_indices(&ours_packets);
3637- let ref_ix = collect_indices(&ref_packets);
3638-
3639- eprintln!(
3640- "ours frames: {} ref frames: {}",
3641- ours_ix.len(),
3642- ref_ix.len()
3643- );
3644-
3645- // Print side-by-side for target seconds (50 frames/sec at 20ms).
3646- let frames_per_sec = 50usize;
3647- let mut out_str = String::new();
3648- out_str.push_str("# reelm@12k SILK oracle: ours vs ffmpeg-libopus indices (r1)\n");
3649- out_str.push_str("# mono, 120s, 20ms frames, VBR constrained, 48kHz, Application::Voip\n");
3650- out_str.push_str(&format!(
3651- "# ours_frames={} ref_frames={}\n",
3652- ours_ix.len(),
3653- ref_ix.len()
3654- ));
3655- out_str.push_str("# sig: 0=unvoiced 2=voiced | per: LTP codebook | nlsf_i: 4=nointerp\n");
3656- out_str.push_str("# gains/ltp are 4 subframe indices; lag/contour only for voiced\n\n");
3657-
3658- for &sec in TARGET_SECS {
3659- let start = sec * frames_per_sec;
3660- let end = start + frames_per_sec;
3661- out_str.push_str(&format!(
3662- "=== second {} (frames {}–{}) ===\n",
3663- sec,
3664- start,
3665- end - 1
3666- ));
3667- out_str.push_str("frame side sig qoff gains[4] nlsf_i lag cont per ltp[4] ltpscl seed bytes\n");
3668- for f in start..end {
3669- let ours = ours_ix.get(f);
3670- let refr = ref_ix.get(f);
3671- if ours.is_none() && refr.is_none() {
3672- continue;
3673- }
3674- for (side, item) in [("O", ours), ("R", refr)] {
3675- match item {
3676- Some((ix, bytes)) => {
3677- let voiced = ix.signal_type == 2;
3678- let lag_str = if voiced {
3679- format!("{:4}", ix.lag_index)
3680- } else {
3681- " -".to_string()
3682- };
3683- let cont_str = if voiced {
3684- format!("{:4}", ix.contour_index)
3685- } else {
3686- " -".to_string()
3687- };
3688- let per_str = if voiced {
3689- format!("{}", ix.per_index)
3690- } else {
3691- "-".to_string()
3692- };
3693- let ltp_str = if voiced {
3694- format!(
3695- "[{},{},{},{}]",
3696- ix.ltp_index[0], ix.ltp_index[1], ix.ltp_index[2], ix.ltp_index[3]
3697- )
3698- } else {
3699- "[-,-,-,-]".to_string()
3700- };
3701- let ltpscl_str = if voiced {
3702- format!("{}", ix.ltp_scale_index)
3703- } else {
3704- "-".to_string()
3705- };
3706- out_str.push_str(&format!(
3707- "{:5} {} {:2} {:2} [{:2},{:2},{:2},{:2}] {:2} {} {} {} {} {} {:2} {:3}\n",
3708- f, side, ix.signal_type, ix.quant_offset_type,
3709- ix.gains[0], ix.gains[1], ix.gains[2], ix.gains[3],
3710- ix.nlsf_interp_coef_q2,
3711- lag_str, cont_str, per_str, ltp_str, ltpscl_str,
3712- ix.seed, bytes,
3713- ));
3714- }
3715- None => {
3716- out_str.push_str(&format!("{:5} {} -- missing --\n", f, side));
3717- }
3718- }
3719- }
3720- }
3721- out_str.push('\n');
3722- }
3723-
3724- // Summarize divergence statistics across ALL frames.
3725- let n = ours_ix.len().min(ref_ix.len());
3726- let mut sig_mismatch = 0;
3727- let mut qoff_mismatch = 0;
3728- let mut gain_diff_sum = 0i64;
3729- let mut nlsf_interp_diff = 0;
3730- let mut ltp_per_mismatch = 0;
3731- let mut ltp_idx_diff_sum = 0i64;
3732- let mut voiced_both = 0;
3733- let mut lag_diff_sum = 0i64;
3734- let mut bytes_ours = 0u64;
3735- let mut bytes_ref = 0u64;
3736- for i in 0..n {
3737- let (o, ob) = &ours_ix[i];
3738- let (r, rb) = &ref_ix[i];
3739- if o.signal_type != r.signal_type {
3740- sig_mismatch += 1;
3741- }
3742- if o.quant_offset_type != r.quant_offset_type {
3743- qoff_mismatch += 1;
3744- }
3745- for k in 0..4 {
3746- gain_diff_sum += (o.gains[k] as i64 - r.gains[k] as i64).abs();
3747- }
3748- if o.nlsf_interp_coef_q2 != r.nlsf_interp_coef_q2 {
3749- nlsf_interp_diff += 1;
3750- }
3751- if o.signal_type == 2 && r.signal_type == 2 {
3752- voiced_both += 1;
3753- if o.per_index != r.per_index {
3754- ltp_per_mismatch += 1;
3755- }
3756- for k in 0..4 {
3757- ltp_idx_diff_sum += (o.ltp_index[k] as i64 - r.ltp_index[k] as i64).abs();
3758- }
3759- lag_diff_sum += (o.lag_index as i64 - r.lag_index as i64).abs();
3760- }
3761- bytes_ours += *ob as u64;
3762- bytes_ref += *rb as u64;
3763- }
3764- out_str.push_str("=== divergence summary (all frames) ===\n");
3765- out_str.push_str(&format!("frames compared: {}\n", n));
3766- out_str.push_str(&format!(
3767- "signal_type mismatch: {} ({:.1}%)\n",
3768- sig_mismatch,
3769- 100.0 * sig_mismatch as f64 / n as f64
3770- ));
3771- out_str.push_str(&format!(
3772- "quant_offset mismatch: {} ({:.1}%)\n",
3773- qoff_mismatch,
3774- 100.0 * qoff_mismatch as f64 / n as f64
3775- ));
3776- out_str.push_str(&format!(
3777- "avg |gain diff| per subframe: {:.2}\n",
3778- gain_diff_sum as f64 / (n as f64 * 4.0)
3779- ));
3780- out_str.push_str(&format!(
3781- "nlsf_interp mismatch: {} ({:.1}%)\n",
3782- nlsf_interp_diff,
3783- 100.0 * nlsf_interp_diff as f64 / n as f64
3784- ));
3785- out_str.push_str(&format!("voiced_both: {}\n", voiced_both));
3786- out_str.push_str(&format!(
3787- " LTP per_index mismatch: {} ({:.1}%)\n",
3788- ltp_per_mismatch,
3789- 100.0 * ltp_per_mismatch as f64 / voiced_both.max(1) as f64
3790- ));
3791- out_str.push_str(&format!(
3792- " avg |ltp_index diff| per subframe: {:.2}\n",
3793- ltp_idx_diff_sum as f64 / (voiced_both.max(1) as f64 * 4.0)
3794- ));
3795- out_str.push_str(&format!(
3796- " avg |lag diff|: {:.2}\n",
3797- lag_diff_sum as f64 / voiced_both.max(1) as f64
3798- ));
3799- out_str.push_str(&format!(
3800- "total bytes: ours={} ref={} ratio={:.3}\n",
3801- bytes_ours,
3802- bytes_ref,
3803- bytes_ours as f64 / bytes_ref.max(1) as f64
3804- ));
3805-
3806- let out_path = lanes_dir.join("opus-silkq-r1.oracle.txt");
3807- fs::write(&out_path, &out_str).unwrap();
3808- println!("wrote {}", out_path.display());
3809- print!("{}", out_str);
3810-}
3811-
3812-/// Decode a SILK stream packet-by-packet through a fresh `SilkDecoder`,
3813-/// snapshotting each frame's coded indices — the oracle diagnostic's view of
3814-/// what the bitstream actually coded (our encoder's packets and a reference
3815-/// encoder's alike).
3816-fn collect_indices(packets: &[Vec<u8>]) -> Vec<(ec_opus::SilkDecIndices, usize)> {
3817- let mut silk = ec_opus::SilkDecoder::new(16000, 1);
3818- let mut results = Vec::new();
3819- let mut silk_pcm = vec![0i16; 320]; // 20ms at 16kHz
3820- for pkt in packets {
3821- if pkt.len() <= 1 {
3822- continue; // DTX / empty
3823- }
3824- let parsed = match ec_opus::Packet::parse(pkt, false) {
3825- Ok(p) => p,
3826- Err(_) => continue,
3827- };
3828- let toc = parsed.toc;
3829- let mode = toc.mode();
3830- if mode == ec_opus::Mode::Celt {
3831- continue;
3832- }
3833- let internal_rate = if mode == ec_opus::Mode::Hybrid {
3834- 16000
3835- } else {
3836- match toc.bandwidth() {
3837- ec_opus::Bandwidth::Narrow => 8000,
3838- ec_opus::Bandwidth::Medium => 12000,
3839- _ => 16000,
3840- }
3841- };
3842- let payload_ms = (toc.frame_size_48k() / 48).max(10);
3843- let mut first = true;
3844- for frame_data in &parsed.frames {
3845- if frame_data.len() <= 1 {
3846- first = false;
3847- continue;
3848- }
3849- let mut dec = ec_opus::RangeDecoder::new(frame_data);
3850- let _ = silk.decode(
3851- &mut dec,
3852- &mut silk_pcm,
3853- payload_ms,
3854- internal_rate,
3855- 1,
3856- first,
3857- ec_opus::SilkFrameMode::Normal,
3858- );
3859- let ix = silk.last_indices();
3860- let bytes = frame_data.len();
3861- results.push((ix, bytes));
3862- first = false;
3863- }
3864- }
3865- results
3866-}
3867-
3868-// ---------------------------------------------------------------------------
3869-// SILK 12k spectral divergence: WHERE the 12 kbps Voip err_ratio outlier
3870-// carries its error. Same machinery as spectral_divergence_vs_libopus, but
3871-// mono/Application::Voip/12 kbps on reelm.wav, both sides decoded through
3872-// ffmpeg libopus (gate symmetry), with the index oracle on the worst frames.
3873-// Run:
3874-// cargo test -p ec-opus --release --test conformance \
3875-// silk_spectral_divergence_12k -- --ignored --nocapture
3876-// Writes lanes/opus-silkq-r2.bands.txt.
3877-// ---------------------------------------------------------------------------
3878-
3879-#[test]
3880-#[ignore = "probe: per-band spectral divergence dump at 12k; unblocks when ~/Music/reelm.wav is back in the corpus (hard-asserts src.exists)"]
3881-fn silk_spectral_divergence_12k() {
3882- let _timing = timing_shared();
3883- const SECS: f64 = 120.0;
3884- const FRAME: usize = 960; // 20 ms at 48 kHz
3885- const CHANNELS: usize = 1;
3886- const MAX_LAG: usize = 2000;
3887- const KBPS: u32 = 12;
3888-
3889- let src = shellexpand("~/Music/reelm.wav");
3890- assert!(src.exists(), "source missing: {}", src.display());
3891- let source_pcm = ffmpeg_decode_pcm_mono(&src, SECS);
3892- let source_frames = source_pcm.len() / CHANNELS;
3893- assert!(source_frames > 48_000, "source too short");
3894- let seconds = source_frames as f64 / 48000.0;
3895-
3896- let lanes_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes");
3897- fs::create_dir_all(&lanes_dir).unwrap();
3898- let ref_ogg = temp_path("opus-silkq-r2-ref.opus");
3899- let ours_ogg = temp_path("opus-silkq-r2-ours.opus");
3900-
3901- // Reference: ffmpeg libopus mono voip at 12k, decoded by ffmpeg libopus.
3902- ffmpeg_encode_libopus_mono_voip(&src, KBPS, &ref_ogg, SECS);
3903- let ref_bytes = fs::metadata(&ref_ogg)
3904- .map(|m| m.len() as usize)
3905- .unwrap_or(0);
3906- let ref_kbps = ref_bytes as f64 * 8.0 / seconds / 1000.0;
3907- let ref_dec = ffmpeg_decode(&ref_ogg, CHANNELS).expect("ffmpeg libopus decode of ref");
3908- let ref_trim: Vec<f32> = ref_dec.into_iter().take(source_frames * CHANNELS).collect();
3909- let (_, ref_aligned) = align_to_source(&source_pcm, &ref_trim, CHANNELS, MAX_LAG);
3910- let ref_ogg_bytes = fs::read(&ref_ogg).expect("read ref ogg");
3911- let ref_packets: Vec<Vec<u8>> = ogg_packets(&ref_ogg_bytes)
3912- .into_iter()
3913- .skip(2)
3914- .filter(|p| !p.is_empty())
3915- .collect();
3916- let _ = fs::remove_file(&ref_ogg);
3917-
3918- // Ours: ec-opus Voip at the reference's realised rate; our packets
3919- // re-decoded through ffmpeg libopus so both sides cross the same decoder.
3920- let mut enc = Encoder::new(48000, CHANNELS, Application::Voip).expect("encoder");
3921- enc.set_bitrate((ref_kbps * 1000.0).round() as u32);
3922- enc.set_vbr_constrained(true);
3923- let pre_skip = enc.look_ahead(FRAME) as i64;
3924- let mut out = vec![0u8; 1500];
3925- let mut ours_packets: Vec<Vec<u8>> = Vec::new();
3926- let mut padded = Vec::new();
3927- for block in source_pcm.chunks(FRAME * CHANNELS) {
3928- let block = if block.len() < FRAME * CHANNELS {
3929- padded.clear();
3930- padded.extend_from_slice(block);
3931- padded.resize(FRAME * CHANNELS, 0.0);
3932- &padded[..]
3933- } else {
3934- block
3935- };
3936- let len = enc.encode_float(block, FRAME, &mut out).expect("encode");
3937- ours_packets.push(out[..len].to_vec());
3938- }
3939- write_ogg_opus(
3940- &ours_ogg,
3941- &ours_packets,
3942- opus_head(CHANNELS, pre_skip as u16, None),
3943- CHANNELS,
3944- source_frames,
3945- pre_skip,
3946- );
3947- let ours_bytes: usize = ours_packets.iter().map(|p| p.len()).sum();
3948- let ours_kbps = ours_bytes as f64 * 8.0 / seconds / 1000.0;
3949- let ours_dec = ffmpeg_decode(&ours_ogg, CHANNELS).expect("ffmpeg libopus decode of ours");
3950- let _ = fs::remove_file(&ours_ogg);
3951- let ours_trim: Vec<f32> = ours_dec
3952- .into_iter()
3953- .take(source_frames * CHANNELS)
3954- .collect();
3955- let (_, ours_aligned) = align_to_source(&source_pcm, &ours_trim, CHANNELS, MAX_LAG);
3956-
3957- // opus_compare totals, per-band eb², per-frame ef² — both vs the source.
3958- let cmp_frames = source_frames
3959- .min(ours_aligned.len() / CHANNELS)
3960- .min(ref_aligned.len() / CHANNELS);
3961- let take = |v: &[f32]| -> Vec<i16> { to_i16(&v[..cmp_frames * CHANNELS]) };
3962- let s_i = take(&source_pcm);
3963- let o_i = take(&ours_aligned);
3964- let r_i = take(&ref_aligned);
3965- let (err_o, eb2_o, ef2_o) = opus_compare_err_parts(&s_i, &o_i, CHANNELS);
3966- let (err_r, eb2_r, ef2_r) = opus_compare_err_parts(&s_i, &r_i, CHANNELS);
3967- let nframes = ef2_o.len();
3968- assert_eq!(nframes, ef2_r.len(), "frame counts differ");
3969-
3970- // Raw (unmasked) band energies: spectral shape + dominant-band lookup.
3971- let as_f64 = |v: &[i16]| -> Vec<f64> { v.iter().map(|&x| x as f64).collect() };
3972- let mut bands_s = Vec::new();
3973- let mut bands_o = Vec::new();
3974- let mut bands_r = Vec::new();
3975- let mut scratch_ps = Vec::new();
3976- band_energy(
3977- &as_f64(&s_i),
3978- CHANNELS,
3979- nframes,
3980- &mut Some(&mut bands_s),
3981- &mut scratch_ps,
3982- );
3983- band_energy(
3984- &as_f64(&o_i),
3985- CHANNELS,
3986- nframes,
3987- &mut Some(&mut bands_o),
3988- &mut scratch_ps,
3989- );
3990- band_energy(
3991- &as_f64(&r_i),
3992- CHANNELS,
3993- nframes,
3994- &mut Some(&mut bands_r),
3995- &mut scratch_ps,
3996- );
3997-
3998- // Oracle indices both sides; FFT frame xi -> 20 ms packet index.
3999- let ours_ix = collect_indices(&ours_packets);
4000- let ref_ix = collect_indices(&ref_packets);
4001- let pkt_of = |xi: usize| xi * WIN_STEP / (FRAME * CHANNELS);
4002-
4003- let mut report = String::new();
4004- report.push_str("# reelm@12k SILK per-band divergence: ours vs ffmpeg-libopus (r2)\n");
4005- report.push_str("# mono, 120s, 20ms frames, VBR constrained, 48kHz, Application::Voip\n");
4006- report.push_str(&format!(
4007- "# rates: ours {ours_kbps:.2} kbps, ref {ref_kbps:.2} kbps; \
4008- err ours={err_o:.3} ref={err_r:.3} ratio={:.2}; nframes={nframes}\n",
4009- err_o / err_r
4010- ));
4011-
4012- // (1) 21-band table: which bands carry the error.
4013- let sum_o: f64 = eb2_o.iter().sum();
4014- let sum_r: f64 = eb2_r.iter().sum();
4015- report.push_str(
4016- "# eb2 = band's mean share of the pre-squared frame error; \
4017- dln = mean ln(E_test/E_src); band i ends at CELT_EBANDS[i+1]*240 Hz\n",
4018- );
4019- report.push_str("# band lo_hz hi_hz dln_o dln_r eb2_o eb2_r ratio share_o share_r\n");
4020- for bi in 0..NBANDS {
4021- let (mut dol, mut drl) = (0.0f64, 0.0f64);
4022- for xi in 0..nframes {
4023- let sl = bands_s[(xi * NBANDS + bi) * CHANNELS].ln();
4024- dol += bands_o[(xi * NBANDS + bi) * CHANNELS].ln() - sl;
4025- drl += bands_r[(xi * NBANDS + bi) * CHANNELS].ln() - sl;
4026- }
4027- dol /= nframes as f64;
4028- drl /= nframes as f64;
4029- let ratio = if eb2_r[bi] > 0.0 {
4030- eb2_o[bi] / eb2_r[bi]
4031- } else {
4032- f64::INFINITY
4033- };
4034- report.push_str(&format!(
4035- "{:5} {:5} {:6} {:+.3} {:+.3} {:.3e} {:.3e} {:>7} {:5.1}% {:5.1}%\n",
4036- bi,
4037- CELT_EBANDS[bi] * 240,
4038- CELT_EBANDS[bi + 1] * 240,
4039- dol,
4040- drl,
4041- eb2_o[bi],
4042- eb2_r[bi],
4043- ratio,
4044- 100.0 * eb2_o[bi] / sum_o,
4045- 100.0 * eb2_r[bi] / sum_r,
4046- ));
4047- }
4048-
4049- // (2) top-15 frames by ef2(ours), with the dominant band and the oracle.
4050- let mut by_ef2: Vec<usize> = (0..nframes).collect();
4051- by_ef2.sort_by(|&a, &b| ef2_o[b].partial_cmp(&ef2_o[a]).unwrap());
4052- report.push_str(
4053- "\n# top-15 frames by ef2(ours) (ef2 = frame's squared opus_compare error); \
4054- dom = argmax_b (lnE_o - lnE_s)^2, raw bands\n",
4055- );
4056- report.push_str(
4057- "# t(s) fft pkt ef2_o ef2_r dom domband_hz | side sig qoff gains[4] nlsf_i lag cont per ltp[4] ltpscl seed bytes\n",
4058- );
4059- for &xi in by_ef2.iter().take(15) {
4060- let pkt = pkt_of(xi);
4061- let t = (xi * WIN_STEP) as f64 / 48000.0;
4062- let (mut dom, mut dom_v) = (0usize, -1.0f64);
4063- for bi in 0..NBANDS {
4064- let sl = bands_s[(xi * NBANDS + bi) * CHANNELS].ln();
4065- let d = bands_o[(xi * NBANDS + bi) * CHANNELS].ln() - sl;
4066- if d * d > dom_v {
4067- dom_v = d * d;
4068- dom = bi;
4069- }
4070- }
4071- report.push_str(&format!(
4072- "{:7.3} {:5} {:4} {:.3e} {:.3e} {:2} {}-{}Hz\n",
4073- t,
4074- xi,
4075- pkt,
4076- ef2_o[xi],
4077- ef2_r[xi],
4078- dom,
4079- CELT_EBANDS[dom] * 240,
4080- CELT_EBANDS[dom + 1] * 240
4081- ));
4082- for (side, ixv) in [(" O", ours_ix.get(pkt)), (" R", ref_ix.get(pkt))] {
4083- match ixv {
4084- Some((ix, bytes)) => {
4085- let voiced = ix.signal_type == 2;
4086- let opt = |v: String, on: bool| if on { v } else { "-".to_owned() };
4087- report.push_str(&format!(
4088- " {side} sig={} qoff={} gains=[{},{},{},{}] nlsf_i={} lag={} cont={} per={} ltp=[{},{},{},{}] ltpscl={} seed={} bytes={}\n",
4089- ix.signal_type,
4090- ix.quant_offset_type,
4091- ix.gains[0],
4092- ix.gains[1],
4093- ix.gains[2],
4094- ix.gains[3],
4095- ix.nlsf_interp_coef_q2,
4096- opt(format!("{}", ix.lag_index), voiced),
4097- opt(format!("{}", ix.contour_index), voiced),
4098- opt(format!("{}", ix.per_index), voiced),
4099- opt(format!("{}", ix.ltp_index[0]), voiced),
4100- opt(format!("{}", ix.ltp_index[1]), voiced),
4101- opt(format!("{}", ix.ltp_index[2]), voiced),
4102- opt(format!("{}", ix.ltp_index[3]), voiced),
4103- opt(format!("{}", ix.ltp_scale_index), voiced),
4104- ix.seed,
4105- bytes
4106- ));
4107- }
4108- None => report.push_str(&format!(" {side} -- missing --\n")),
4109- }
4110- }
4111- }
4112-
4113- // (3) tail vs body: how much of the total error the worst frames carry,
4114- // and whether the 11x ratio survives de-tailing (err = (Σef2/n)^(1/16)).
4115- let tail = |ef2: &[f64]| -> (usize, f64, f64, usize, f64) {
4116- let mut s = ef2.to_vec();
4117- s.sort_by(|a, b| b.partial_cmp(a).unwrap());
4118- let tot: f64 = s.iter().sum();
4119- let k = (s.len() / 100).max(1);
4120- let top1: f64 = s[..k].iter().sum();
4121- let (mut half, mut acc) = (s.len(), 0.0);
4122- for (i, v) in s.iter().enumerate() {
4123- acc += v;
4124- if acc >= 0.5 * tot {
4125- half = i + 1;
4126- break;
4127- }
4128- }
4129- (k, top1 / tot, half as f64 / s.len() as f64, half, tot)
4130- };
4131- let root16 = |tot: f64, n: usize| tot.powf(1.0 / 16.0) / (n as f64).powf(1.0 / 16.0);
4132- let (k, sh1_o, halff_o, half_o, _tot_o) = tail(&ef2_o);
4133- let (_, sh1_r, halff_r, half_r, _tot_r) = tail(&ef2_r);
4134- report.push_str(&format!(
4135- "# tail: top-1% ({k} frames) carry {:.2}% of ours' Σef2 vs {:.2}% of ref's; \
4136- 50% of ours' err sits in the worst {half_o} frames ({:.2}%) \
4137- vs ref's worst {half_r} ({:.2}%)\n",
4138- 100.0 * sh1_o,
4139- 100.0 * sh1_r,
4140- 100.0 * halff_o,
4141- 100.0 * halff_r
4142- ));
4143- // De-tailed: drop each side's worst 50 frames (of 24k FFT frames/pkt-mapped).
4144- let clip50 = |ef2: &[f64]| -> f64 {
4145- let mut s = ef2.to_vec();
4146- s.sort_by(|a, b| b.partial_cmp(a).unwrap());
4147- s[50..].iter().sum()
4148- };
4149- let err_o_clip = root16(clip50(&ef2_o), nframes);
4150- let err_r_clip = root16(clip50(&ef2_r), nframes);
4151- report.push_str(&format!(
4152- "# de-tailed (worst 50 of {nframes} FFT frames dropped per side): \
4153- err ours={err_o_clip:.3} ref={err_r_clip:.3} ratio={:.2} (was {err_o:.3}/{err_r:.3}/{:.2})\n",
4154- err_o_clip / err_r_clip,
4155- err_o / err_r
4156- ));
4157- // Burst signature: per 20 ms packet, does first-subframe gain >= 60 or a
4158- // starved packet (<= 20 bytes) line up with the packet's mean ef2?
4159- let mut pkt_ef2 = vec![0.0f64; ours_packets.len()];
4160- let mut pkt_cnt = vec![0u32; ours_packets.len()];
4161- // Index loop kept: the index also drives other lookups or parallel arrays.
4162- #[allow(clippy::needless_range_loop)]
4163- for xi in 0..nframes {
4164- let p = pkt_of(xi).min(pkt_ef2.len() - 1);
4165- pkt_ef2[p] += ef2_o[xi];
4166- pkt_cnt[p] += 1;
4167- }
4168- let mut g_hi = (0.0f64, 0usize); // (sum, count) packets with gains[0] >= 60
4169- let mut g_lo = (0.0f64, 0usize);
4170- let mut b_lo = (0.0f64, 0usize); // bytes <= 20
4171- let mut b_hi = (0.0f64, 0usize);
4172- for (i, (ix, bytes)) in ours_ix.iter().enumerate() {
4173- if i >= pkt_ef2.len() {
4174- break;
4175- }
4176- let mean = if pkt_cnt[i] > 0 {
4177- pkt_ef2[i] / pkt_cnt[i] as f64
4178- } else {
4179- 0.0
4180- };
4181- if ix.gains[0] >= 60 {
4182- g_hi.0 += mean;
4183- g_hi.1 += 1;
4184- } else {
4185- g_lo.0 += mean;
4186- g_lo.1 += 1;
4187- }
4188- if *bytes <= 20 {
4189- b_lo.0 += mean;
4190- b_lo.1 += 1;
4191- } else {
4192- b_hi.0 += mean;
4193- b_hi.1 += 1;
4194- }
4195- }
4196- report.push_str(&format!(
4197- "# burst signature: packets with gains[0]>=60: {}/{}, mean ef2 {:.3e}; \
4198- gains[0]<60: mean ef2 {:.3e} || packets <=20 bytes: {}/{}, mean ef2 {:.3e}; \
4199- >20 bytes: mean ef2 {:.3e}\n",
4200- g_hi.1,
4201- g_hi.1 + g_lo.1,
4202- if g_hi.1 > 0 {
4203- g_hi.0 / g_hi.1 as f64
4204- } else {
4205- f64::NAN
4206- },
4207- if g_lo.1 > 0 {
4208- g_lo.0 / g_lo.1 as f64
4209- } else {
4210- f64::NAN
4211- },
4212- b_lo.1,
4213- b_lo.1 + b_hi.1,
4214- if b_lo.1 > 0 {
4215- b_lo.0 / b_lo.1 as f64
4216- } else {
4217- f64::NAN
4218- },
4219- if b_hi.1 > 0 {
4220- b_hi.0 / b_hi.1 as f64
4221- } else {
4222- f64::NAN
4223- },
4224- ));
4225-
4226- let out_path = lanes_dir.join("opus-silkq-r2.bands.txt");
4227- fs::write(&out_path, &report).unwrap();
4228- println!("wrote {}", out_path.display());
4229- print!("{}", report);
4230-}
4231-
4232-// ---------------------------------------------------------------------------
4233-// Harness: feed identical raw PCM (.sw, s16le interleaved) to our opus_compare
4234-// so it can be checked against the C `opus_compare` tool on the SAME bytes.
4235-// Run: SW_REF=a.sw SW_TEST=b.sw SW_CH=2 cargo test -p ec-opus --release \
4236-// opus_compare_harness -- --ignored --nocapture
4237-// ---------------------------------------------------------------------------
4238-#[test]
4239-#[ignore = "probe: needs hand-supplied SW_REF/SW_TEST .sw files to cross-check our opus_compare against the C tool; asserts nothing without those env vars"]
4240-fn opus_compare_harness() {
4241- let _timing = timing_shared();
4242- let ref_path = std::env::var("SW_REF").expect("SW_REF");
4243- let test_path = std::env::var("SW_TEST").expect("SW_TEST");
4244- let channels: usize = std::env::var("SW_CH")
4245- .ok()
4246- .and_then(|s| s.parse().ok())
4247- .unwrap_or(2);
4248- let x = read_i16(Path::new(&ref_path));
4249- let y = read_i16(Path::new(&test_path));
4250- assert_eq!(
4251- x.len(),
4252- y.len(),
4253- "sample counts differ: {} ({} samples) vs {} ({} samples)",
4254- ref_path,
4255- x.len() / channels,
4256- test_path,
4257- y.len() / channels
4258- );
4259- let err = opus_compare_err(&x, &y, channels);
4260- let q = opus_compare(&x, &y, channels);
4261- println!(
4262- "HARNESS err={err:.6} Q={q:.4} ch={channels} n={}",
crates/ec-pcm-ext/Cargo.tomlmodified+1 -0
@@ -10,5 +10,6 @@ authors.workspace = true
10 ec-core = { workspace = true }10 ec-core = { workspace = true }
11 11
12 [dev-dependencies]12 [dev-dependencies]
13+ec-testkit.workspace = true
13 ec-mp4 = { workspace = true }14 ec-mp4 = { workspace = true }
14 ec-riff = { workspace = true }15 ec-riff = { workspace = true }
crates/ec-pcm-ext/tests/oracle.rsmodified+24 -34
@@ -1,31 +1,16 @@
1 //! Bit-exact oracle: fixtures are generated with ffmpeg from synthetic lavfi1 //! Bit-exact oracle: fixtures are generated with ffmpeg from synthetic lavfi
2 //! sources, decoded here and by ffmpeg (`-f s16le`), and must match exactly.2 //! sources, decoded here and by ffmpeg (`-f s16le`), and must match exactly.
3 //!3 //!
4-//! Without ffmpeg the tests skip loudly; with `EC_REQUIRE_FIXTURES=1` a
5-//! missing ffmpeg is a failure.
6 4
7 use std::fs::File;5 use std::fs::File;
8 use std::io::BufReader;6 use std::io::BufReader;
9 use std::path::{Path, PathBuf};7 use std::path::{Path, PathBuf};
10-use std::process::Command;
11 8
12-use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Demuxer, MediaParameters};
13 use ec_core::frame::{ChannelLayout, SampleFormat};9 use ec_core::frame::{ChannelLayout, SampleFormat};
14 use ec_core::packet::Buf;10 use ec_core::packet::Buf;
11+use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Demuxer, MediaParameters};
15 use ec_pcm_ext::PcmExtDecoder;12 use ec_pcm_ext::PcmExtDecoder;
16 13
17-fn have_ffmpeg() -> bool {
18- let ok = Command::new("ffmpeg").arg("-version").output().is_ok();
19- if !ok {
20- assert!(
21- std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
22- "EC_REQUIRE_FIXTURES=1 but ffmpeg is not installed"
23- );
24- eprintln!("ffmpeg absent - skipping");
25- }
26- ok
27-}
28-
29 fn tmpdir(tag: &str) -> PathBuf {14 fn tmpdir(tag: &str) -> PathBuf {
30 let d = std::env::temp_dir().join(format!("ec-pcm-ext-{tag}-{}", std::process::id()));15 let d = std::env::temp_dir().join(format!("ec-pcm-ext-{tag}-{}", std::process::id()));
31 std::fs::create_dir_all(&d).expect("tmp");16 std::fs::create_dir_all(&d).expect("tmp");
@@ -35,9 +20,7 @@ fn tmpdir(tag: &str) -> PathBuf {
35 /// Synthetic source: `kind` 0 = tones with a chirp, 1 = noise.20 /// Synthetic source: `kind` 0 = tones with a chirp, 1 = noise.
36 fn source(kind: u32, channels: u32, rate: u32) -> String {21 fn source(kind: u32, channels: u32, rate: u32) -> String {
37 match (kind, channels) {22 match (kind, channels) {
38- (0, 1) => format!(23+ (0, 1) => format!("aevalsrc='0.6*sin(2*PI*440*t)+0.25*sin(2*PI*1234*t*t)':s={rate}:d=1.3"),
39- "aevalsrc='0.6*sin(2*PI*440*t)+0.25*sin(2*PI*1234*t*t)':s={rate}:d=1.3"
40- ),
41 (0, _) => format!(24 (0, _) => format!(
42 "aevalsrc='0.6*sin(2*PI*440*t)+0.25*sin(2*PI*1234*t*t)|0.5*sin(2*PI*660*t)':s={rate}:d=1.3"25 "aevalsrc='0.6*sin(2*PI*440*t)+0.25*sin(2*PI*1234*t*t)|0.5*sin(2*PI*660*t)':s={rate}:d=1.3"
43 ),26 ),
@@ -51,21 +34,27 @@ fn source(kind: u32, channels: u32, rate: u32) -> String {
51 fn make(dir: &Path, name: &str, codec: &str, kind: u32, channels: u32, rate: u32) -> PathBuf {34 fn make(dir: &Path, name: &str, codec: &str, kind: u32, channels: u32, rate: u32) -> PathBuf {
52 let out = dir.join(name);35 let out = dir.join(name);
53 let src = source(kind, channels, rate);36 let src = source(kind, channels, rate);
54- let mut cmd = Command::new("ffmpeg");37+ let mut cmd = ec_testkit::ffmpeg();
55 cmd.args(["-nostdin", "-y", "-v", "error", "-f", "lavfi"]);38 cmd.args(["-nostdin", "-y", "-v", "error", "-f", "lavfi"]);
56 if src.contains(';') {39 if src.contains(';') {
57- cmd.args(["-i", "anullsrc=d=0.01", "-filter_complex"]).arg(&src);40+ cmd.args(["-i", "anullsrc=d=0.01", "-filter_complex"])
41+ .arg(&src);
58 } else {42 } else {
59 cmd.arg("-i").arg(&src);43 cmd.arg("-i").arg(&src);
60 }44 }
61- cmd.args(["-ac", &channels.to_string(), "-c:a", codec]).arg(&out);45+ cmd.args(["-ac", &channels.to_string(), "-c:a", codec])
46+ .arg(&out);
62 let o = cmd.output().expect("ffmpeg");47 let o = cmd.output().expect("ffmpeg");
63- assert!(o.status.success(), "{name}: {}", String::from_utf8_lossy(&o.stderr));48+ assert!(
49+ o.status.success(),
50+ "{name}: {}",
51+ String::from_utf8_lossy(&o.stderr)
52+ );
64 out53 out
65 }54 }
66 55
67 fn ffmpeg_pcm(path: &Path) -> Vec<u8> {56 fn ffmpeg_pcm(path: &Path) -> Vec<u8> {
68- let o = Command::new("ffmpeg")57+ let o = ec_testkit::ffmpeg()
69 .args(["-nostdin", "-v", "error", "-i"])58 .args(["-nostdin", "-v", "error", "-i"])
70 .arg(path)59 .arg(path)
71 .args(["-f", "s16le", "-"])60 .args(["-f", "s16le", "-"])
@@ -114,7 +103,8 @@ fn decode_demuxer(mut d: impl Demuxer, want: CodecId) -> Vec<u8> {
114 }103 }
115 104
116 fn decode_wav(path: &Path) -> Vec<u8> {105 fn decode_wav(path: &Path) -> Vec<u8> {
117- let mut r = ec_riff::WavReader::new(BufReader::new(File::open(path).expect("open"))).expect("wav");106+ let mut r =
107+ ec_riff::WavReader::new(BufReader::new(File::open(path).expect("open"))).expect("wav");
118 let c = r.compressed().expect("compressed wav").clone();108 let c = r.compressed().expect("compressed wav").clone();
119 let spec = r.spec();109 let spec = r.spec();
120 let codec = ec_riff::WavCompressed::codec_of(c.tag).expect("codec");110 let codec = ec_riff::WavCompressed::codec_of(c.tag).expect("codec");
@@ -157,9 +147,6 @@ fn check(name: &str, got: Vec<u8>, path: &Path) {
157 147
158 #[test]148 #[test]
159 fn every_format_is_bit_exact_against_ffmpeg() {149 fn every_format_is_bit_exact_against_ffmpeg() {
160- if !have_ffmpeg() {
161- return;
162- }
163 let dir = tmpdir("oracle");150 let dir = tmpdir("oracle");
164 let mut n = 0;151 let mut n = 0;
165 // (ffmpeg encoder, codec id, containers)152 // (ffmpeg encoder, codec id, containers)
@@ -194,23 +181,26 @@ fn every_format_is_bit_exact_against_ffmpeg() {
194 /// All 256 G.711 code points decode like ffmpeg's tables.181 /// All 256 G.711 code points decode like ffmpeg's tables.
195 #[test]182 #[test]
196 fn g711_tables_match_ffmpeg() {183 fn g711_tables_match_ffmpeg() {
197- if !have_ffmpeg() {
198- return;
199- }
200 let dir = tmpdir("g711");184 let dir = tmpdir("g711");
201 let raw: Vec<u8> = (0..=255u8).collect();185 let raw: Vec<u8> = (0..=255u8).collect();
202 for (fmt, codec) in [("alaw", CodecId::PcmAlaw), ("mulaw", CodecId::PcmMulaw)] {186 for (fmt, codec) in [("alaw", CodecId::PcmAlaw), ("mulaw", CodecId::PcmMulaw)] {
203 let p = dir.join(format!("all.{fmt}"));187 let p = dir.join(format!("all.{fmt}"));
204 std::fs::write(&p, &raw).expect("write");188 std::fs::write(&p, &raw).expect("write");
205- let o = Command::new("ffmpeg")189+ let o = ec_testkit::ffmpeg()
206- .args(["-nostdin", "-v", "error", "-f", fmt, "-ar", "8000", "-ac", "1", "-i"])190+ .args([
191+ "-nostdin", "-v", "error", "-f", fmt, "-ar", "8000", "-ac", "1", "-i",
192+ ])
207 .arg(&p)193 .arg(&p)
208 .args(["-f", "s16le", "-"])194 .args(["-f", "s16le", "-"])
209 .output()195 .output()
210 .expect("ffmpeg");196 .expect("ffmpeg");
211 assert!(o.status.success());197 assert!(o.status.success());
212 let mut dec = PcmExtDecoder::from_parameters(params(codec, 1, 8000, &[])).expect("dec");198 let mut dec = PcmExtDecoder::from_parameters(params(codec, 1, 8000, &[])).expect("dec");
213- assert_eq!(to_bytes(dec.decode(&raw).expect("decode")), o.stdout, "{fmt}");199+ assert_eq!(
200+ to_bytes(dec.decode(&raw).expect("decode")),
201+ o.stdout,
202+ "{fmt}"
203+ );
214 }204 }
215 std::fs::remove_dir_all(&dir).ok();205 std::fs::remove_dir_all(&dir).ok();
216 }206 }
crates/ec-truehd/Cargo.tomlmodified+1 -0
@@ -10,4 +10,5 @@ authors.workspace = true
10 ec-core = { workspace = true }10 ec-core = { workspace = true }
11 11
12 [dev-dependencies]12 [dev-dependencies]
13+ec-testkit.workspace = true
13 ec-matroska = { workspace = true }14 ec-matroska = { workspace = true }
crates/ec-truehd/fuzz/seed.shmodified+4 -3
@@ -13,7 +13,8 @@ set -euo pipefail
13 13
14 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)14 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
15 ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd)15 ROOT=$(cd -- "$FUZZ_DIR/../../.." && pwd)
16-FIXTURES="$ROOT/fixtures"16+FIXTURES=${EC_FIXTURES:-$ROOT/fixtures}
17+FF=${EC_FFMPEG:-$HOME/.cache/ec-ffmpeg/ffmpeg}
17 18
18 STREAM_DIR="$FUZZ_DIR/corpus/decode_stream"19 STREAM_DIR="$FUZZ_DIR/corpus/decode_stream"
19 SYNC_DIR="$FUZZ_DIR/corpus/parse_sync"20 SYNC_DIR="$FUZZ_DIR/corpus/parse_sync"
@@ -22,9 +23,9 @@ mkdir -p "$STREAM_DIR" "$SYNC_DIR"
22 GEN=$(mktemp -d "${TMPDIR:-$HOME}/ec-truehd-seed.XXXXXX")23 GEN=$(mktemp -d "${TMPDIR:-$HOME}/ec-truehd-seed.XXXXXX")
23 trap 'rm -rf "$GEN"' EXIT24 trap 'rm -rf "$GEN"' EXIT
24 25
25-command -v ffmpeg >/dev/null || { echo "seed.sh: ffmpeg not found" >&2; exit 2; }26+[ -x "$FF" ] || { echo "seed.sh: ffmpeg not found at $FF" >&2; exit 2; }
26 gen() { # name channels codec muxer27 gen() { # name channels codec muxer
27- ffmpeg -hide_banner -loglevel error -y -f lavfi -i "sine=frequency=440:duration=1" \28+ "$FF" -hide_banner -loglevel error -y -f lavfi -i "sine=frequency=440:duration=1" \
28 -ac "$2" -c:a "$3" -strict -2 -t 1 -f "$4" "$GEN/$1"29 -ac "$2" -c:a "$3" -strict -2 -t 1 -f "$4" "$GEN/$1"
29 }30 }
30 gen stereo.thd 2 truehd truehd31 gen stereo.thd 2 truehd truehd
crates/ec-truehd/tests/it/atmos_synth.rsmodified+12 -76
@@ -1,8 +1,5 @@
1 //! Atmos backward compatibility, tested on a synthetic 4-substream stream.1 //! Atmos backward compatibility, tested on a synthetic 4-substream stream.
2 //!2 //!
3-//! No real Atmos TrueHD stream is available to this build, so the stream is
4-//! built from the real 7.1 Blu-ray remux's own access units (the first
5-//! [`AUS`] of its TrueHD track, 3 substreams each). For every access unit,
6 //! [`with_object_substream`] rebuilds it with a 4th directory entry: the3 //! [`with_object_substream`] rebuilds it with a 4th directory entry: the
7 //! object-audio substream, here a run of [`FILLER_WORDS`] stand-in words4 //! object-audio substream, here a run of [`FILLER_WORDS`] stand-in words
8 //! appended after substream 2's coded data. The rebuilt access unit is:5 //! appended after substream 2's coded data. The rebuilt access unit is:
@@ -31,21 +28,15 @@
31 //! `ffmpeg -f truehd -i <path> -f s32le` can be compared against this28 //! `ffmpeg -f truehd -i <path> -f s32le` can be compared against this
32 //! decoder's output (ffmpeg decodes the same 8-channel presentation).29 //! decoder's output (ffmpeg decodes the same 8-channel presentation).
33 //!30 //!
34-//! Needs the 7.1 remux under `~/Downloads`. Absent, the tests skip loudly; with
35-//! `EC_REQUIRE_FIXTURES=1` an absent remux is a hard failure.
36 31
37-use std::fs::File;32+use std::path::Path;
38-use std::io::BufReader;
39-use std::path::{Path, PathBuf};
40 33
41-use ec_core::CodecId;
42-use ec_core::Demuxer;
43 use ec_core::frame::ChannelLayout;34 use ec_core::frame::ChannelLayout;
44-use ec_matroska::MatroskaDemuxer;
45 use ec_truehd::TrueHdDecoder;35 use ec_truehd::TrueHdDecoder;
46 use ec_truehd::sync::AccessUnitHeader;36 use ec_truehd::sync::AccessUnitHeader;
47 37
48-/// Access units taken from the start of the remux: 1 s of 48 kHz audio, one38+use crate::common::raw_access_units;
39+
49 /// major sync among them.40 /// major sync among them.
50 const AUS: usize = 1200;41 const AUS: usize = 1200;
51 /// Length of the object-audio stand-in, in 16-bit words.42 /// Length of the object-audio stand-in, in 16-bit words.
@@ -54,66 +45,15 @@ const FILLER_WORDS: u16 = 4;
54 const MAX_AU_WORDS: usize = 0x0FFF;45 const MAX_AU_WORDS: usize = 0x0FFF;
55 const MAJOR_SYNC_LEN: usize = 28;46 const MAJOR_SYNC_LEN: usize = 28;
56 47
57-fn find_file() -> Option<PathBuf> {48+fn truehd_access_units() -> Vec<Vec<u8>> {
58- fn walk(dir: &Path, out: &mut Vec<PathBuf>) {49+ let data =
59- let Ok(entries) = std::fs::read_dir(dir) else {50+ std::fs::read(ec_testkit::fixture("open/fate/truehd/atmos.thd")).expect("read atmos.thd");
60- return;51+ let aus = raw_access_units(&data);
61- };
62- for e in entries.flatten() {
63- let p = e.path();
64- if p.is_dir() {
65- walk(&p, out);
66- } else {
67- out.push(p);
68- }
69- }
70- }
71- let home = std::env::var("HOME").ok()?;
72- let mut all = Vec::new();
73- walk(&PathBuf::from(home).join("Downloads"), &mut all);
74- all.into_iter().find(|p| {
75- p.file_name()
76- .and_then(|n| n.to_str())
77- .is_some_and(|n| n.contains("ReelR") && n.ends_with(".mkv"))
78- })
79-}
80-
81-/// The first [`AUS`] access units of the remux's TrueHD track, or `None`
82-/// (after a loud skip, or a hard failure under `EC_REQUIRE_FIXTURES`).
83-fn truehd_access_units() -> Option<Vec<Vec<u8>>> {
84- let Some(path) = find_file() else {
85 assert!(52 assert!(
86- std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),53+ aus.len() >= AUS,
87- "EC_REQUIRE_FIXTURES=1 but the 7.1 TrueHD remux is absent under ~/Downloads"54+ "atmos.thd has fewer than {AUS} access units"
88 );55 );
89- eprintln!("skip: no 'ReelR ... TrueHD ...mkv' under ~/Downloads");56+ aus.into_iter().take(AUS).collect()
90- return None;
91- };
92- let file = File::open(&path).expect("open the remux");
93- let mut demux = MatroskaDemuxer::new(BufReader::new(file)).expect("open the container");
94- let stream_index = demux
95- .streams()
96- .iter()
97- .find(|s| s.params.codec == CodecId::TrueHd)
98- .expect("a TrueHD track")
99- .index;
100- let mut aus = Vec::with_capacity(AUS);
101- while aus.len() < AUS {
102- let packet = match demux.next_packet() {
103- Ok(p) => p,
104- Err(e) if e.is_eof() => break,
105- Err(e) => panic!("demux error: {e}"),
106- };
107- if packet.stream == stream_index {
108- aus.push(packet.data.as_ref().to_vec());
109- }
110- }
111- assert_eq!(
112- aus.len(),
113- AUS,
114- "the remux has at least {AUS} TrueHD access units"
115- );
116- Some(aus)
117 }57 }
118 58
119 /// The major sync's CRC-16 (poly `0x002D`, MSB-first table form), the same59 /// The major sync's CRC-16 (poly `0x002D`, MSB-first table form), the same
@@ -246,9 +186,7 @@ fn decode_all(aus: &[Vec<u8>]) -> (Decoded, ec_truehd::CheckStats) {
246 186
247 #[test]187 #[test]
248 fn synthetic_atmos_decodes_bit_exact_to_the_original_7_1() {188 fn synthetic_atmos_decodes_bit_exact_to_the_original_7_1() {
249- let Some(originals) = truehd_access_units() else {189+ let originals = truehd_access_units();
250- return;
251- };
252 let synthetic: Vec<Vec<u8>> = originals190 let synthetic: Vec<Vec<u8>> = originals
253 .iter()191 .iter()
254 .map(|au| with_object_substream(au, 0xA5))192 .map(|au| with_object_substream(au, 0xA5))
@@ -293,9 +231,7 @@ fn synthetic_atmos_decodes_bit_exact_to_the_original_7_1() {
293 231
294 #[test]232 #[test]
295 fn object_substream_contents_do_not_change_the_pcm_output() {233 fn object_substream_contents_do_not_change_the_pcm_output() {
296- let Some(originals) = truehd_access_units() else {234+ let originals = truehd_access_units();
297- return;
298- };
299 // Filler bytes are never read, so any value must decode identically.235 // Filler bytes are never read, so any value must decode identically.
300 let zeros: Vec<Vec<u8>> = originals236 let zeros: Vec<Vec<u8>> = originals
301 .iter()237 .iter()
crates/ec-truehd/tests/it/common.rsmodified+11 -7
@@ -1,9 +1,13 @@
1-use std::process::Command;1+use ec_truehd::sync::AccessUnitHeader;
2 2
3-/// Whether `ffmpeg -version` runs successfully.3+pub fn raw_access_units(data: &[u8]) -> Vec<Vec<u8>> {
4-pub fn have_ffmpeg() -> bool {4+ let mut aus = Vec::new();
5- Command::new("ffmpeg")5+ let mut pos = 0;
6- .arg("-version")6+ while pos < data.len() {
7- .output()7+ let header = AccessUnitHeader::parse(&data[pos..])
8- .is_ok_and(|o| o.status.success())8+ .unwrap_or_else(|e| panic!("access unit {}: {e}", aus.len()));
9+ aus.push(data[pos..pos + header.length].to_vec());
10+ pos += header.length;
11+ }
12+ aus
9 }13 }
crates/ec-truehd/tests/it/fixture_exact.rsmodified+40 -69
@@ -1,29 +1,19 @@
1 //! Sample-for-sample equality with ffmpeg's TrueHD decoder on the committed1 //! Sample-for-sample equality with ffmpeg's TrueHD decoder on the committed
2-//! fixtures in `crates/ec-truehd/fixtures/`.
3 //!2 //!
4 //! The committed fixtures are made with ffmpeg's own TrueHD encoder3 //! The committed fixtures are made with ffmpeg's own TrueHD encoder
5 //! (`-c:a truehd -strict -2`): 2.0 and 5.1 at 16-bit (s16p input) and 24-bit4 //! (`-c:a truehd -strict -2`): 2.0 and 5.1 at 16-bit (s16p input) and 24-bit
6 //! (s32p input), 48 kHz. The file name carries the channel count: `2ch` or `51`.5 //! (s32p input), 48 kHz. The file name carries the channel count: `2ch` or `51`.
7 //!6 //!
8-//! The 8-channel (7.1) case is not committed: ffmpeg's encoder refuses 7.1, and
9-//! the only real 7.1 TrueHD source is a copyrighted remux. It is tested by
10-//! [`remux_71_is_bit_exact_against_ffmpeg`], which reads the remux from its
11-//! local path (env `EC_TRUEHD_71_REMUX`, or the `truehd_71_remux` key of
12-//! `real_library.toml`) and skips loudly when it is absent.
13-//!
14 //! Each file is decoded here and by ffmpeg (`-f s32le`), and every sample must7 //! Each file is decoded here and by ffmpeg (`-f s32le`), and every sample must
15-//! be equal. Lossless decoding has no tolerance. ffmpeg is test tooling and is
16-//! driven through `std::process`; without it the test skips loudly.
17 8
18 use std::fs::File;9 use std::fs::File;
19 use std::io::BufReader;10 use std::io::BufReader;
20 use std::path::{Path, PathBuf};11 use std::path::{Path, PathBuf};
21-use std::process::Command;
22 12
13+use crate::common::raw_access_units;
23 use ec_core::{CodecId, Demuxer};14 use ec_core::{CodecId, Demuxer};
24 use ec_matroska::MatroskaDemuxer;15 use ec_matroska::MatroskaDemuxer;
25 use ec_truehd::TrueHdDecoder;16 use ec_truehd::TrueHdDecoder;
26-use crate::common::have_ffmpeg;
27 17
28 fn fixtures() -> PathBuf {18 fn fixtures() -> PathBuf {
29 Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures")19 Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures")
@@ -82,16 +72,26 @@ fn decode_ours(path: &Path) -> (u32, Vec<i32>, usize, u32) {
82 }72 }
83 }73 }
84 let stats = decoder.check_stats();74 let stats = decoder.check_stats();
85- assert_eq!(stats.lossless_check_failures, 0, "{}: {stats:?}", path.display());75+ assert_eq!(
76+ stats.lossless_check_failures,
77+ 0,
78+ "{}: {stats:?}",
79+ path.display()
80+ );
86 assert_eq!(stats.parity_failures, 0, "{}: {stats:?}", path.display());81 assert_eq!(stats.parity_failures, 0, "{}: {stats:?}", path.display());
87- assert_eq!(stats.restart_crc_failures, 0, "{}: {stats:?}", path.display());82+ assert_eq!(
83+ stats.restart_crc_failures,
84+ 0,
85+ "{}: {stats:?}",
86+ path.display()
87+ );
88 assert_eq!(stats.length_mismatches, 0, "{}: {stats:?}", path.display());88 assert_eq!(stats.length_mismatches, 0, "{}: {stats:?}", path.display());
89 (stream, samples, channels, rate)89 (stream, samples, channels, rate)
90 }90 }
91 91
92 /// ffmpeg's decode of track `stream` as interleaved S32 little-endian.92 /// ffmpeg's decode of track `stream` as interleaved S32 little-endian.
93 fn decode_ffmpeg(path: &Path, stream: u32) -> Vec<i32> {93 fn decode_ffmpeg(path: &Path, stream: u32) -> Vec<i32> {
94- let out = Command::new("ffmpeg")94+ let out = ec_testkit::ffmpeg()
95 .args(["-v", "error", "-nostdin", "-i"])95 .args(["-v", "error", "-nostdin", "-i"])
96 .arg(path)96 .arg(path)
97 .args(["-map", &format!("0:{stream}"), "-f", "s32le", "-"])97 .args(["-map", &format!("0:{stream}"), "-f", "s32le", "-"])
@@ -109,10 +109,6 @@ fn decode_ffmpeg(path: &Path, stream: u32) -> Vec<i32> {
109 #[test]109 #[test]
110 fn fixtures_are_bit_exact_against_ffmpeg() {110 fn fixtures_are_bit_exact_against_ffmpeg() {
111 let dir = fixtures();111 let dir = fixtures();
112- if !have_ffmpeg() {
113- eprintln!("skip: ffmpeg not on PATH");
114- return;
115- }
116 let mut paths: Vec<PathBuf> = std::fs::read_dir(&dir)112 let mut paths: Vec<PathBuf> = std::fs::read_dir(&dir)
117 .expect("fixtures dir")113 .expect("fixtures dir")
118 .flatten()114 .flatten()
@@ -138,7 +134,8 @@ fn fixtures_are_bit_exact_against_ffmpeg() {
138 );134 );
139 let mismatch = ours.iter().zip(&reference).position(|(a, b)| a != b);135 let mismatch = ours.iter().zip(&reference).position(|(a, b)| a != b);
140 assert_eq!(136 assert_eq!(
141- mismatch, None,137+ mismatch,
138+ None,
142 "{name}: first mismatch at sample {mismatch:?} (channel {:?})",139 "{name}: first mismatch at sample {mismatch:?} (channel {:?})",
143 mismatch.map(|i| i % channels)140 mismatch.map(|i| i % channels)
144 );141 );
@@ -150,68 +147,42 @@ fn fixtures_are_bit_exact_against_ffmpeg() {
150 }147 }
151 }148 }
152 149
153-/// The local 7.1 remux: env `EC_TRUEHD_71_REMUX`, else the `truehd_71_remux`
154-/// key of `real_library.toml` (env `EC_REAL_LIBRARY`, default under
155-/// `~/Documents/Code/Rust/edith`).
156-fn remux_path() -> Option<PathBuf> {
157- if let Ok(p) = std::env::var("EC_TRUEHD_71_REMUX") {
158- return Some(PathBuf::from(p));
159- }
160- let toml = std::env::var("EC_REAL_LIBRARY").map(PathBuf::from).unwrap_or_else(|_| {
161- let home = std::env::var("HOME").unwrap_or_default();
162- PathBuf::from(home).join("Documents/Code/Rust/edith/real_library.toml")
163- });
164- let text = std::fs::read_to_string(toml).ok()?;
165- text.lines().find_map(|line| {
166- let (key, value) = line.trim().split_once('=')?;
167- if key.trim() != "truehd_71_remux" {
168- return None;
169- }
170- Some(PathBuf::from(value.trim().strip_prefix('"')?.strip_suffix('"')?))
171- })
172-}
173-
174-/// The first 2 s of a real 7.1 TrueHD remux, decoded from the start of the
175-/// file and compared sample-for-sample with ffmpeg's decode of the same span.
176 #[test]150 #[test]
177-fn remux_71_is_bit_exact_against_ffmpeg() {151+fn atmos_71_is_bit_exact_against_ffmpeg() {
178- let Some(path) = remux_path() else {152+ let path = ec_testkit::fixture("open/fate/truehd/atmos.thd");
179- eprintln!("skip: no 7.1 remux (set EC_TRUEHD_71_REMUX or truehd_71_remux in real_library.toml)");153+ let data = std::fs::read(&path).expect("read atmos.thd");
180- return;154+ let mut decoder = TrueHdDecoder::new();
181- };155+ let mut ours = Vec::new();
182- if !path.exists() {156+ let mut channels = 0;
183- eprintln!("skip: 7.1 remux {} not on disk", path.display());157+ for au in raw_access_units(&data) {
184- return;158+ if let Some(f) = decoder.decode_access_unit(&au).expect("decode") {
159+ channels = f.channels();
160+ ours.extend(s32le(&f.data[0]));
185 }161 }
186- if !have_ffmpeg() {
187- eprintln!("skip: ffmpeg not on PATH");
188- return;
189 }162 }
190- const SECONDS: usize = 2;163+ assert_eq!(channels, 8, "atmos.thd channels");
191- let (stream, ours, channels, rate) = decode_ours(&path);164+ let out = ec_testkit::ffmpeg()
192- assert_eq!(channels, 8, "remux channels");
193- assert_eq!(rate, 48_000, "remux rate");
194- let want = SECONDS * 48_000 * channels;
195- assert!(ours.len() >= want, "only {} samples decoded", ours.len());
196- let ours = &ours[..want];
197-
198- let out = Command::new("ffmpeg")
199 .args(["-v", "error", "-nostdin", "-i"])165 .args(["-v", "error", "-nostdin", "-i"])
200 .arg(&path)166 .arg(&path)
201- .args(["-map", &format!("0:{stream}"), "-t", &SECONDS.to_string(), "-f", "s32le", "-"])167+ .args(["-f", "s32le", "-"])
202 .output()168 .output()
203 .expect("run ffmpeg");169 .expect("run ffmpeg");
204- assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));170+ assert!(
171+ out.status.success(),
172+ "ffmpeg: {}",
173+ String::from_utf8_lossy(&out.stderr)
174+ );
205 let reference = s32le(&out.stdout);175 let reference = s32le(&out.stdout);
206- assert!(reference.len() >= want, "ffmpeg gave {} samples", reference.len());176+ assert_eq!(ours.len(), reference.len(), "sample count vs ffmpeg");
207- let reference = &reference[..want];177+ let mismatch = ours.iter().zip(&reference).position(|(a, b)| a != b);
208-
209- let mismatch = ours.iter().zip(reference).position(|(a, b)| a != b);
210 assert_eq!(178 assert_eq!(
211 mismatch,179 mismatch,
212 None,180 None,
213 "first mismatch at sample {mismatch:?} (channel {:?})",181 "first mismatch at sample {mismatch:?} (channel {:?})",
214 mismatch.map(|i| i % channels)182 mismatch.map(|i| i % channels)
215 );183 );
216- eprintln!("7.1 remux: {channels} ch, {SECONDS} s, {want} samples, bit-exact");184+ eprintln!(
185+ "atmos 7.1: {channels} ch, {} samples, bit-exact",
186+ ours.len()
187+ );
217 }188 }
crates/ec-truehd/tests/it/library.rsmodified+19 -130
@@ -1,140 +1,29 @@
1-//! Walks a real Blu-ray remux's TrueHD track and parses every access unit --1+use crate::common::raw_access_units;
2-//! a live discovery over `~/Downloads`, absent files skip loudly, nothing is
3-//! generated or bundled.
4 2
5-use std::fs::File;3+#[test]
6-use std::io::BufReader;4+fn walks_every_truehd_access_unit_of_atmos() {
7-use std::path::PathBuf;5+ let path = ec_testkit::fixture("open/fate/truehd/atmos.thd");
8-use std::process::Command;6+ let data = std::fs::read(&path).expect("read atmos.thd");
9-7+ let aus = raw_access_units(&data);
10-use ec_core::{CodecId, Demuxer};8+ assert!(!aus.is_empty(), "found no TrueHD access units at all");
11-use ec_matroska::MatroskaDemuxer;9+ let out = ec_testkit::ffprobe()
12-use ec_truehd::sync::AccessUnitHeader;
13-
14-/// The user's own library, not a fixture: a glob over `~/Downloads` for a
15-/// known 7.1 TrueHD Blu-ray remux.
16-fn find_file() -> Option<PathBuf> {
17- let home = std::env::var("HOME").ok()?;
18- let downloads = PathBuf::from(home).join("Downloads");
19- for entry in glob_dir(&downloads) {
20- let name = entry.file_name()?.to_str()?;
21- if name.contains("ReelR") && name.ends_with(".mkv") {
22- return Some(entry);
23- }
24- }
25- None
26-}
27-
28-/// A one-level-deep, non-recursive-but-good-enough directory walk (the file
29-/// this test wants sits in a subdirectory of `~/Downloads`) -- no `glob`
30-/// crate in this family, so a plain `read_dir` walk stands in for one.
31-fn glob_dir(dir: &std::path::Path) -> Vec<PathBuf> {
32- let mut out = Vec::new();
33- let Ok(entries) = std::fs::read_dir(dir) else {
34- return out;
35- };
36- for entry in entries.flatten() {
37- let path = entry.path();
38- if path.is_dir() {
39- out.extend(glob_dir(&path));
40- } else {
41- out.push(path);
42- }
43- }
44- out
45-}
46-
47-fn have_ffprobe() -> bool {
48- Command::new("ffprobe")
49- .arg("-version")
50- .output()
51- .map(|o| o.status.success())
52- .unwrap_or(false)
53-}
54-
55-/// ffprobe's own packet count for the file's TrueHD stream, by absolute
56-/// stream index.
57-fn ffprobe_packet_count(path: &std::path::Path, stream: usize) -> Option<u64> {
58- let out = Command::new("ffprobe")
59- .args(["-v", "error", "-select_streams"])
60- .arg(stream.to_string())
61 .args([10 .args([
11+ "-v",
12+ "error",
13+ "-select_streams",
14+ "a:0",
62 "-count_packets",15 "-count_packets",
63 "-show_entries",16 "-show_entries",
64 "stream=nb_read_packets",17 "stream=nb_read_packets",
65 "-of",18 "-of",
66 "csv=p=0",19 "csv=p=0",
67 ])20 ])
68- .arg(path)21+ .arg(&path)
69 .output()22 .output()
70- .ok()?;23+ .expect("run ffprobe");
71- if !out.status.success() {24+ let expected: usize = String::from_utf8_lossy(&out.stdout)
72- return None;25+ .trim()
73- }26+ .parse()
74- String::from_utf8_lossy(&out.stdout).trim().parse().ok()27+ .expect("ffprobe packet count");
75-}28+ assert_eq!(aus.len(), expected, "AU count vs ffprobe's packet count");
76-
77-#[test]
78-fn walks_every_truehd_access_unit_of_a_real_7_1_remux() {
79- let Some(path) = find_file() else {
80- eprintln!("skip: no 'ReelR ... TrueHD ...mkv' under ~/Downloads");
81- return;
82- };
83-
84- let file = File::open(&path).expect("open the file");
85- let mut demux = MatroskaDemuxer::new(BufReader::new(file)).expect("open the container");
86-
87- let track = demux
88- .streams()
89- .iter()
90- .find(|s| s.params.codec == CodecId::TrueHd)
91- .expect("a TrueHD track");
92- let stream_index = track.index;
93- let audio = track.params.audio().expect("audio parameters");
94- assert_eq!(audio.sample_rate, 48_000, "rate");
95- assert_eq!(audio.layout.channel_count(), 8, "channels");
96- // Matroska's `BitDepth` element is optional and this remux's TrueHD
97- // track does not carry one; report what the container states rather
98- // than asserting a value it never claimed.
99- eprintln!("container-reported bit depth: {:?}", audio.bits_per_sample);
100-
101- let mut au_count = 0u64;
102- let mut major_syncs = 0u64;
103- loop {
104- let packet = match demux.next_packet() {
105- Ok(p) => p,
106- Err(e) if e.is_eof() => break,
107- Err(e) => panic!("demux error: {e}"),
108- };
109- if packet.stream != stream_index {
110- continue;
111- }
112- let header = AccessUnitHeader::parse(&packet.data)
113- .unwrap_or_else(|e| panic!("access unit {au_count}: {e}"));
114- assert_eq!(
115- header.length,
116- packet.data.len(),
117- "access unit {au_count} claims a length that does not match its packet"
118- );
119- if header.major_sync.is_some() {
120- major_syncs += 1;
121- }
122- au_count += 1;
123- }
124-
125- eprintln!("{au_count} access units, {major_syncs} carrying a major sync");
126- assert!(au_count > 0, "found no TrueHD access units at all");
127-
128- if have_ffprobe() {
129- // Absolute demuxer stream index in the file, for ffprobe's own
130- // `-select_streams`: the track this family's stream list found.
131- let absolute = stream_index as usize;
132- if let Some(expected) = ffprobe_packet_count(&path, absolute) {
133- assert_eq!(au_count, expected, "AU count vs ffprobe's packet count");
134- } else {
135- eprintln!("skip: ffprobe packet count unavailable for stream {absolute}");
136- }
137- } else {
138- eprintln!("skip: ffprobe not on PATH, no oracle comparison");
139- }
140 }29 }
crates/ec-truehd/tests/it/oracle.rsmodified+9 -75
@@ -1,46 +1,9 @@
1-//! Bit-exactness against an external decoder: the first 60 s of a real 7.1
2-//! Blu-ray TrueHD remux (3 substreams, noise type 1 matrices), and
3-//! externally encoded MLP/TrueHD streams (mono, stereo, 5.1 pink noise —
4-//! every codebook, matrices with the 2-channel noise generator, two
5-//! substreams). Both need `ffmpeg` on PATH and skip loudly without it; the
6-//! remux is a live discovery over `~/Downloads`.
7-
8-use std::fs::File;
9-use std::io::BufReader;
10-use std::path::{Path, PathBuf};
11-use std::process::Command;
12-
13-use ec_core::{CodecId, Demuxer};
14-use ec_matroska::MatroskaDemuxer;
15 use ec_truehd::{TrueHdDecoder, TrueHdEncoder, frame_length};1 use ec_truehd::{TrueHdDecoder, TrueHdEncoder, frame_length};
16-use crate::common::have_ffmpeg;
17 2
18-fn find_file() -> Option<PathBuf> {3+use crate::common::raw_access_units;
19- fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
20- let Ok(entries) = std::fs::read_dir(dir) else {
21- return;
22- };
23- for e in entries.flatten() {
24- let p = e.path();
25- if p.is_dir() {
26- walk(&p, out);
27- } else {
28- out.push(p);
29- }
30- }
31- }
32- let home = std::env::var("HOME").ok()?;
33- let mut all = Vec::new();
34- walk(&PathBuf::from(home).join("Downloads"), &mut all);
35- all.into_iter().find(|p| {
36- p.file_name()
37- .and_then(|n| n.to_str())
38- .is_some_and(|n| n.contains("ReelR") && n.ends_with(".mkv"))
39- })
40-}
41 4
42 fn ffmpeg(args: &[&str]) -> Vec<u8> {5 fn ffmpeg(args: &[&str]) -> Vec<u8> {
43- let out = Command::new("ffmpeg")6+ let out = ec_testkit::ffmpeg()
44 .args(["-v", "error", "-nostdin"])7 .args(["-v", "error", "-nostdin"])
45 .args(args)8 .args(args)
46 .output()9 .output()
@@ -79,29 +42,12 @@ fn compare(ours: &[i32], reference: &[i32]) -> (usize, usize, Option<usize>) {
79 }42 }
80 43
81 #[test]44 #[test]
82-fn first_60_seconds_of_a_real_7_1_remux_are_bit_exact() {45+fn first_60_seconds_of_atmos_are_bit_exact() {
83- let Some(path) = find_file() else {
84- eprintln!("skip: no 'ReelR ... TrueHD ...mkv' under ~/Downloads");
85- return;
86- };
87- if !have_ffmpeg() {
88- eprintln!("skip: ffmpeg not on PATH");
89- return;
90- }
91 const SECONDS: usize = 60;46 const SECONDS: usize = 60;
92- let mut demux = MatroskaDemuxer::new(BufReader::new(File::open(&path).unwrap())).unwrap();47+ let path = ec_testkit::fixture("open/fate/truehd/atmos.thd");
93- let track = demux
94- .streams()
95- .iter()
96- .find(|s| s.params.codec == CodecId::TrueHd)
97- .expect("a TrueHD track");
98- let stream_index = track.index;
99-
100 let reference = s32le(&ffmpeg(&[48 let reference = s32le(&ffmpeg(&[
101 "-i",49 "-i",
102 path.to_str().unwrap(),50 path.to_str().unwrap(),
103- "-map",
104- &format!("0:{stream_index}"),
105 "-t",51 "-t",
106 &SECONDS.to_string(),52 &SECONDS.to_string(),
107 "-f",53 "-f",
@@ -110,21 +56,17 @@ fn first_60_seconds_of_a_real_7_1_remux_are_bit_exact() {
110 ]));56 ]));
111 let channels = 8;57 let channels = 8;
112 let wanted = SECONDS * 48_000 * channels;58 let wanted = SECONDS * 48_000 * channels;
59+ let data = std::fs::read(&path).expect("read atmos.thd");
113 60
114 let mut decoder = TrueHdDecoder::new();61 let mut decoder = TrueHdDecoder::new();
115 let mut ours: Vec<i32> = Vec::with_capacity(wanted);62 let mut ours: Vec<i32> = Vec::with_capacity(wanted);
116 let mut aus = 0;63 let mut aus = 0;
117- while ours.len() < wanted {64+ for au in raw_access_units(&data) {
118- let packet = match demux.next_packet() {65+ if ours.len() >= wanted {
119- Ok(p) => p,66+ break;
120- Err(e) if e.is_eof() => break,
121- Err(e) => panic!("demux: {e}"),
122- };
123- if packet.stream != stream_index {
124- continue;
125 }67 }
126 let frame = decoder68 let frame = decoder
127- .decode_access_unit(&packet.data)69+ .decode_access_unit(&au)
128 .unwrap_or_else(|e| panic!("AU {aus}: {e}"));70 .unwrap_or_else(|e| panic!("AU {aus}: {e}"));
129 aus += 1;71 aus += 1;
130 if let Some(f) = frame {72 if let Some(f) = frame {
@@ -165,10 +107,6 @@ fn first_60_seconds_of_a_real_7_1_remux_are_bit_exact() {
165 /// codebook and a wide range of LSB widths.107 /// codebook and a wide range of LSB widths.
166 #[test]108 #[test]
167 fn externally_encoded_mlp_round_trips_bit_exact() {109 fn externally_encoded_mlp_round_trips_bit_exact() {
168- if !have_ffmpeg() {
169- eprintln!("skip: ffmpeg not on PATH");
170- return;
171- }
172 let dir = std::env::temp_dir().join(format!("ec-truehd-oracle-{}", std::process::id()));110 let dir = std::env::temp_dir().join(format!("ec-truehd-oracle-{}", std::process::id()));
173 std::fs::create_dir_all(&dir).unwrap();111 std::fs::create_dir_all(&dir).unwrap();
174 let mut failures = Vec::new();112 let mut failures = Vec::new();
@@ -242,10 +180,6 @@ fn externally_encoded_mlp_round_trips_bit_exact() {
242 /// other.180 /// other.
243 #[test]181 #[test]
244 fn ffmpeg_decodes_our_encoder_bit_exact() {182 fn ffmpeg_decodes_our_encoder_bit_exact() {
245- if !have_ffmpeg() {
246- eprintln!("ffmpeg not found, skipping");
247- return;
248- }
249 use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat};183 use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat};
250 use ec_core::packet::Buf;184 use ec_core::packet::Buf;
251 use ec_core::registry::Encoder;185 use ec_core::registry::Encoder;
crates/ec-vorbis/Cargo.tomlmodified+1 -0
@@ -11,4 +11,5 @@ ec-core.workspace = true
11 ec-dsp.workspace = true11 ec-dsp.workspace = true
12 12
13 [dev-dependencies]13 [dev-dependencies]
14+ec-testkit.workspace = true
14 ec-ogg = { path = "../ec-ogg", version = "0.1.0" }15 ec-ogg = { path = "../ec-ogg", version = "0.1.0" }
crates/ec-vorbis/fuzz/seed.shmodified+2 -2
@@ -14,8 +14,8 @@ set -euo pipefail
14 14
15 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)15 FUZZ_DIR=$(cd -- "$(dirname -- "$0")" && pwd)
16 REPO=$(cd -- "$FUZZ_DIR/../../.." && pwd)16 REPO=$(cd -- "$FUZZ_DIR/../../.." && pwd)
17-FIXTURES="$REPO/fixtures"17+FIXTURES=${EC_FIXTURES:-$REPO/fixtures}
18-[ -d "$FIXTURES/audio" ] || { echo "seed.sh: $FIXTURES/audio missing; run scripts/link-fixtures.sh" >&2; exit 2; }18+[ -d "$FIXTURES/audio" ] || { echo "seed.sh: $FIXTURES/audio missing; run scripts/fixtures.sh" >&2; exit 2; }
19 19
20 HEADERS_DIR="$FUZZ_DIR/headers"20 HEADERS_DIR="$FUZZ_DIR/headers"
21 SETUP_DIR="$FUZZ_DIR/corpus/setup"21 SETUP_DIR="$FUZZ_DIR/corpus/setup"
crates/ec-vorbis/tests/oracle.rsmodified+7 -971
@@ -8,14 +8,13 @@
8 8
9 use std::fs::File;9 use std::fs::File;
10 use std::path::{Path, PathBuf};10 use std::path::{Path, PathBuf};
11-use std::process::Command;
12 11
13 use ec_core::{Decoder, Demuxer, Frame};12 use ec_core::{Decoder, Demuxer, Frame};
14 use ec_ogg::{OggDemuxer, granule_of};13 use ec_ogg::{OggDemuxer, granule_of};
15-use ec_vorbis::{BlockLog, EncoderConfig, VorbisDecoder, VorbisEncoder};14+use ec_vorbis::{EncoderConfig, VorbisDecoder, VorbisEncoder};
16 15
17 fn fixtures() -> PathBuf {16 fn fixtures() -> PathBuf {
18- PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")17+ ec_testkit::root()
19 }18 }
20 19
21 fn scratch() -> PathBuf {20 fn scratch() -> PathBuf {
@@ -37,7 +36,7 @@ fn ffmpeg_decode(path: &Path) -> Option<(Vec<Vec<f32>>, u32)> {
37 let channels: usize = probe_field(path, "channels")?.parse().ok()?;36 let channels: usize = probe_field(path, "channels")?.parse().ok()?;
38 let rate: u32 = probe_field(path, "sample_rate")?.parse().ok()?;37 let rate: u32 = probe_field(path, "sample_rate")?.parse().ok()?;
39 38
40- let out = Command::new("ffmpeg")39+ let out = ec_testkit::ffmpeg()
41 .args(["-v", "error", "-i"])40 .args(["-v", "error", "-i"])
42 .arg(path)41 .arg(path)
43 .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])42 .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])
@@ -62,7 +61,7 @@ fn ffmpeg_decode(path: &Path) -> Option<(Vec<Vec<f32>>, u32)> {
62 61
63 /// One `stream=` field of the first audio stream.62 /// One `stream=` field of the first audio stream.
64 fn probe_field(path: &Path, field: &str) -> Option<String> {63 fn probe_field(path: &Path, field: &str) -> Option<String> {
65- let out = Command::new("ffprobe")64+ let out = ec_testkit::ffprobe()
66 .args([65 .args([
67 "-v",66 "-v",
68 "error",67 "error",
@@ -356,39 +355,6 @@ fn encode_to_file(source: &[Vec<f32>], rate: u32, bitrate: i32, name: &str) -> P
356 path355 path
357 }356 }
358 357
359-/// Like [`encode_to_file`] but also returns the per-block rate-loop log.
360-fn encode_to_file_with_log(
361- source: &[Vec<f32>],
362- rate: u32,
363- bitrate: i32,
364- name: &str,
365-) -> (PathBuf, Vec<BlockLog>) {
366- let channels = source.len() as u16;
367- let mut encoder = VorbisEncoder::new(EncoderConfig {
368- sample_rate: rate,
369- channels,
370- bitrate_bps: bitrate,
371- quality: 0.6,
372- })
373- .expect("encoder");
374- encoder.enable_block_log();
375- let borrowed: Vec<&[f32]> = source.iter().map(|c| &c[..]).collect();
376- encoder.push_planar(&borrowed).expect("push");
377- encoder.finish();
378- let mut packets = Vec::new();
379- loop {
380- match encoder.next_packet() {
381- Ok(packet) => packets.push((packet.data, packet.granule)),
382- Err(e) if e.is_eof() => break,
383- Err(e) => panic!("encode: {e}"),
384- }
385- }
386- let log = encoder.take_block_log();
387- let path = scratch().join(name);
388- mux(&path, &encoder, &packets, rate, channels);
389- (path, log)
390-}
391-
392 /// Duration ffprobe reports, in samples of the stream's own rate.358 /// Duration ffprobe reports, in samples of the stream's own rate.
393 fn probed_samples(path: &Path) -> i64 {359 fn probed_samples(path: &Path) -> i64 {
394 probe_field(path, "duration_ts")360 probe_field(path, "duration_ts")
@@ -633,18 +599,17 @@ fn onset_after_silence_has_no_pre_echo() {
633 599
634 // The reference oracle must decode the short-block stream600 // The reference oracle must decode the short-block stream
635 // cleanly: no warnings, let alone errors.601 // cleanly: no warnings, let alone errors.
636- let warn = Command::new("ffmpeg")602+ let out = ec_testkit::ffmpeg()
637 .args(["-v", "warning", "-i"])603 .args(["-v", "warning", "-i"])
638 .arg(&path)604 .arg(&path)
639 .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])605 .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])
640- .output();606+ .output()
641- if let Ok(out) = warn {607+ .expect("ffmpeg runs");
642 assert!(608 assert!(
643 out.stderr.is_empty(),609 out.stderr.is_empty(),
644 "{name}: oracle decode warnings: {}",610 "{name}: oracle decode warnings: {}",
645 String::from_utf8_lossy(&out.stderr)611 String::from_utf8_lossy(&out.stderr)
646 );612 );
647- }
648 613
649 let tone_rms = rms(&source[0][onset..]);614 let tone_rms = rms(&source[0][onset..]);
650 let check = |label: &str, planes: &[Vec<f32>]| {615 let check = |label: &str, planes: &[Vec<f32>]| {
@@ -804,932 +769,3 @@ fn quiet_content_reaches_the_target_or_is_transparent() {
804 }769 }
805 }770 }
806 }771 }
807-
808-/// Per-Bark-band quantised-residue histogram comparison: ours vs libvorbis
809-/// reference. We encode the source with our encoder (capturing residue), then
810-/// encode the same source with libvorbis and decode that stream with our own
811-/// decoder, capturing its decoded residue (after inverse coupling, before
812-/// floor multiply — the same domain as the encoder's `quantised`). The
813-/// reference is libvorbis's own residue, so per-band divergence names where
814-/// our psy spends differently from libvorbis.
815-#[test]
816-#[ignore = "slow: encodes 7 sources × 128k, needs ffmpeg/libvorbis"]
817-fn residue_histogram_vs_reference() {
818- use std::io::Write;
819-
820- let sources: &[(&str, &str)] = &[
821- ("nik", "~/Music/reeln.mp4"),
822- ("reelo", "~/Music/reelo.mp3"),
823- ("her", "~/Music/reeli.mp3"),
824- ("reell", "~/Music/reell.mp4"),
825- ("reelm", "~/Music/reelm.wav"),
826- ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),
827- (
828- "hein",
829- "~/Downloads/reelm.mp3",
830- ),
831- ];
832- let bitrate = 128_000i32;
833- let rate = 48_000u32;
834- let channels = 2u16;
835- // Limit to ~12 s for speed — enough blocks for a stable histogram.
836- let max_samples = rate as usize * 12;
837-
838- let out_dir = scratch().join("vorbis7");
839- std::fs::create_dir_all(&out_dir).expect("out dir");
840- let mut report = String::new();
841- report.push_str("# Residue histogram: ours vs libvorbis reference\n\n");
842- report.push_str(&format!(
843- "Bitrate: {} kbps, {} Hz, {}ch, {} s max\n\n",
844- bitrate / 1000,
845- rate,
846- channels,
847- max_samples / rate as usize
848- ));
849- let mut total_ours_bytes = 0u64;
850- let mut total_ref_bytes = 0u64;
851-
852- let mut rows = 0usize;
853- for &(name, src_path) in sources {
854- let expanded = shellexpand(src_path);
855- let src = PathBuf::from(&expanded);
856- if !src.exists() {
857- report.push_str(&format!("## {name}: SKIP (file not found: {expanded})\n\n"));
858- continue;
859- }
860- rows += 1;
861- // Decode source with ffmpeg, limit duration.
862- let Some((source_pcm, src_rate)) = ffmpeg_decode_limited(&src, rate, max_samples) else {
863- report.push_str(&format!("## {name}: SKIP (ffmpeg decode failed)\n\n"));
864- continue;
865- };
866- if source_pcm.len() < 2 || source_pcm[0].is_empty() {
867- report.push_str(&format!("## {name}: SKIP (empty decode)\n\n"));
868- continue;
869- }
870- // Resample to 48k if needed — ffmpeg_decode_limited already targets 48k.
871- let _ = src_rate;
872-
873- // --- Ours: encode source with our encoder, capture residue, keep the ogg ---
874- let ours_ogg = out_dir.join(format!("ours-{name}-128k.ogg"));
875- let (ours_residue, ours_bytes) =
876- encode_and_capture(&source_pcm, rate, channels, bitrate, &ours_ogg);
877-
878- // --- Sanity: decoding our own ogg with capture on must reproduce the
879- // encoder's capture band for band, or the two captures are not in the
880- // same domain and the table below means nothing. ---
881- let (roundtrip, ours_split) = decode_capture_with_bits(&ours_ogg);
882- let (sanity_ok, sanity_detail) = compare_captures(&ours_residue, &roundtrip, rate);
883- let ours_bits = bit_split_summary(&ours_split, &roundtrip);
884-
885- // --- Reference: encode with libvorbis, decode with OUR decoder, capture ---
886- let ref_ogg = out_dir.join(format!("ref-{name}-128k.ogg"));
887- let ref_status = Command::new("ffmpeg")
888- // `-vn`: with the video stream still attached (reell, h264+aac mp4)
889- // ffmpeg's libvorbis wrapper ignores -b:a and encodes at ~3.2x the
890- // target; audio-only input encodes at the requested rate.
891- .args(["-y", "-v", "error", "-i"])
892- .arg(&src)
893- .args([
894- "-vn",
895- "-t",
896- &format!("{}", max_samples / rate as usize),
897- "-ac",
898- "2",
899- "-ar",
900- "48000",
901- "-c:a",
902- "libvorbis",
903- "-b:a",
904- "128k",
905- ])
906- .arg(&ref_ogg)
907- .status();
908- let (ref_residue, ref_split) = match ref_status {
909- Ok(s) if s.success() => decode_capture_with_bits(&ref_ogg),
910- _ => {
911- report.push_str(&format!("## {name}: libvorbis encode failed\n\n"));
912- continue;
913- }
914- };
915- let ref_bytes = std::fs::metadata(&ref_ogg).expect("ref ogg").len();
916- total_ours_bytes += ours_bytes;
917- total_ref_bytes += ref_bytes;
918-
919- // --- Build per-Bark-band histograms ---
920- let bins = 6; // |q|: 0, 1, 2, 3-4, 5-8, 9+
921- let max_bark = 25;
922- let mut ours_hist = vec![vec![0u64; bins]; max_bark];
923- let mut ref_hist = vec![vec![0u64; bins]; max_bark];
924- for (half, quantised) in &ours_residue {
925- accumulate(quantised, *half, rate, &mut ours_hist, max_bark);
926- }
927- for (half, quantised) in &ref_residue {
928- accumulate(quantised, *half, rate, &mut ref_hist, max_bark);
929- }
930-
931- report.push_str(&format!(
932- "## {name} — sanity {}: {} — ours {} B vs ref {} B ({:.2}x)\n\n",
933- if sanity_ok { "PASS" } else { "FAIL" },
934- sanity_detail,
935- ours_bytes,
936- ref_bytes,
937- ours_bytes as f64 / ref_bytes as f64
938- ));
939- let ref_bits = bit_split_summary(&ref_split, &ref_residue);
940- for (who, b) in [("ours", ours_bits), ("ref", ref_bits)] {
941- let (f, r, p, nz) = b;
942- report.push_str(&format!(
943- "bits {who}: floor {f} ({:.1}%), residue {r} ({:.1}%), other {}, packet {p}; non-zero {nz}, residue bits/non-zero {:.2}\n",
944- 100.0 * f as f64 / p.max(1) as f64,
945- 100.0 * r as f64 / p.max(1) as f64,
946- p.saturating_sub(f + r),
947- r as f64 / nz.max(1) as f64
948- ));
949- }
950- report.push('\n');
951- report.push_str("| Bark | q=0 ours/ref | q=1 | q=2 | q=3-4 | q=5-8 | q=9+ | total ours/ref | spend ratio |\n");
952- report.push_str("|------|-------------|-----|-----|-------|-------|------|-----------------|-------------|\n");
953- for band in 0..max_bark {
954- let o = &ours_hist[band];
955- let r = &ref_hist[band];
956- let o_total: u64 = o.iter().sum();
957- let r_total: u64 = r.iter().sum();
958- if o_total == 0 && r_total == 0 {
959- continue;
960- }
961- // "Spend" = non-zero entries (bins 1..) — proxy for bits spent.
962- let o_spend: u64 = o[1..].iter().sum();
963- let r_spend: u64 = r[1..].iter().sum();
964- let ratio = if r_spend > 0 {
965- o_spend as f64 / r_spend as f64
966- } else {
967- f64::INFINITY
968- };
969- report.push_str(&format!(
970- "| {} | {}/{} | {}/{} | {}/{} | {}/{} | {}/{} | {}/{} | {}/{} | {:.2} |\n",
971- band,
972- o[0],
973- r[0],
974- o[1],
975- r[1],
976- o[2],
977- r[2],
978- o[3],
979- r[3],
980- o[4],
981- r[4],
982- o[5],
983- r[5],
984- o_total,
985- r_total,
986- ratio,
987- ));
988- }
989-
990- // Fraction table: per-band share of entries in each |q| class and the
991- // shape distance = sum |f_ours - f_ref| over the four classes
992- // (0 = identical spend shape; convergence target < 0.15 in Bark 3-22).
993- report.push_str("| Bark | f0 ours | f0 ref | f1 ours | f1 ref | f2 ours | f2 ref | f3+ ours | f3+ ref | dist |\n");
994- report.push_str("|------|---------|--------|---------|--------|---------|--------|----------|---------|------|\n");
995- let frac = |h: &[u64], total: u64| {
996- vec![
997- h[0] as f64 / total as f64,
998- h[1] as f64 / total as f64,
999- h[2] as f64 / total as f64,
1000- (h[3] + h[4] + h[5]) as f64 / total as f64,
1001- ]
1002- };
1003- let mut band_dist: Vec<(usize, f64)> = Vec::new();
1004- for band in 0..max_bark {
1005- let o_total: u64 = ours_hist[band].iter().sum();
1006- let r_total: u64 = ref_hist[band].iter().sum();
1007- if o_total == 0 || r_total == 0 {
1008- continue;
1009- }
1010- let fo = frac(&ours_hist[band], o_total);
1011- let fr = frac(&ref_hist[band], r_total);
1012- let dist: f64 = fo.iter().zip(&fr).map(|(a, b)| (a - b).abs()).sum();
1013- band_dist.push((band, dist));
1014- report.push_str(&format!(
1015- "| {} | {:.3} | {:.3} | {:.3} | {:.3} | {:.3} | {:.3} | {:.3} | {:.3} | {:.3} |\n",
1016- band, fo[0], fr[0], fo[1], fr[1], fo[2], fr[2], fo[3], fr[3], dist,
1017- ));
1018- }
1019- let in_scope: Vec<(usize, f64)> = band_dist
1020- .iter()
1021- .filter(|(b, _)| (3..=22).contains(b))
1022- .cloned()
1023- .collect();
1024- if !in_scope.is_empty() {
1025- let max_d = in_scope.iter().map(|(_, d)| *d).fold(f64::MIN, f64::max);
1026- let over = in_scope.iter().filter(|(_, d)| *d >= 0.15).count();
1027- report.push_str(&format!(
1028- "\nshape Bark 3-22: max dist {max_d:.3}, bands >= 0.15: {over}/{} — {}\n",
1029- in_scope.len(),
1030- if over == 0 {
1031- "SHAPE PASS"
1032- } else {
1033- "shape fail"
1034- },
1035- ));
1036- }
1037- report.push('\n');
1038- }
1039-
1040- // The seven sources are the user's own library, so each may be absent on a
1041- // given host -- but a run that encoded none of them is a measurement of
1042- // nothing, and the report it writes looks the same as a real one.
1043- assert!(rows > 0, "no library sources were readable");
1044- report.push_str(&format!(
1045- "\nTotal bytes: ours {total_ours_bytes} vs ref {total_ref_bytes} ({:.2}x)\n",
1046- total_ours_bytes as f64 / total_ref_bytes as f64,
1047- ));
1048- let report_path =
1049- PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../lanes/vorbis-psy-r1.histogram.txt");
1050- let mut f = File::create(&report_path).expect("create report");
1051- f.write_all(report.as_bytes()).expect("write report");
1052- println!("Histogram report: {}", report_path.display());
1053- // Also print to stdout for immediate viewing.
1054- print!("{report}");
1055-}
1056-
1057-/// Encode PCM with our encoder, capturing per-block quantised residue, and mux
1058-/// Per-block residue of one stream: (block size, one residue vector per channel).
1059-type ResidueCapture = Vec<(usize, Vec<Vec<i32>>)>;
1060-
1061-/// the result to `out` so it can be decoded back (sanity check + rate).
1062-fn encode_and_capture(
1063- source: &[Vec<f32>],
1064- rate: u32,
1065- channels: u16,
1066- bitrate: i32,
1067- out: &Path,
1068-) -> (ResidueCapture, u64) {
1069- let mut encoder = VorbisEncoder::new(EncoderConfig {
1070- sample_rate: rate,
1071- channels,
1072- bitrate_bps: bitrate,
1073- quality: 0.6,
1074- })
1075- .expect("encoder");
1076- encoder.enable_residue_capture();
1077- let borrowed: Vec<&[f32]> = source.iter().map(|c| &c[..]).collect();
1078- encoder.push_planar(&borrowed).expect("push");
1079- encoder.finish();
1080- let mut packets = Vec::new();
1081- loop {
1082- match encoder.next_packet() {
1083- Ok(packet) => packets.push((packet.data, packet.granule)),
1084- Err(e) if e.is_eof() => break,
1085- Err(e) => panic!("encode: {e}"),
1086- }
1087- }
1088- mux(out, &encoder, &packets, rate, channels);
1089- let bytes = std::fs::metadata(out).expect("muxed file").len();
1090- (encoder.take_residue_capture(), bytes)
1091-}
1092-
1093-/// Bit split summed over the stream: (floor bits, residue bits, packet bits,
1094-/// non-zero residue count) — bits per coded value is the coding-efficiency oracle.
1095-fn bit_split_summary(
1096- split: &[(u64, u64, u64)],
1097- residue: &[(usize, Vec<Vec<i32>>)],
1098-) -> (u64, u64, u64, u64) {
1099- let (mut f, mut r, mut p) = (0u64, 0u64, 0u64);
1100- for &(a, b, c) in split {
1101- f += a;
1102- r += b;
1103- p += c;
1104- }
1105- let nz: u64 = residue
1106- .iter()
1107- .map(|(_, chs)| {
1108- chs.iter()
1109- .map(|c| c.iter().filter(|&&v| v != 0).count() as u64)
1110- .sum::<u64>()
1111- })
1112- .sum();
1113- (f, r, p, nz)
1114-}
1115-
1116-fn decode_capture_with_bits(path: &Path) -> (ResidueCapture, Vec<(u64, u64, u64)>) {
1117- let mut demuxer = OggDemuxer::open(File::open(path).expect("open")).expect("ogg");
1118- let stream = demuxer
1119- .streams()
1120- .iter()
1121- .find(|s| s.params.codec == ec_core::CodecId::Vorbis)
1122- .expect("a Vorbis stream")
1123- .clone();
1124- let extradata = stream.params.extradata.clone().expect("headers");
1125- let mut decoder = VorbisDecoder::from_extradata(&extradata).expect("headers parse");
1126- decoder.enable_residue_capture();
1127- loop {
1128- let packet = match demuxer.next_packet() {
1129- Ok(packet) => packet,
1130- Err(e) if e.is_eof() => break,
1131- Err(e) => panic!("demux {}: {e}", path.display()),
1132- };
1133- if packet.stream != stream.index {
1134- continue;
1135- }
1136- // A packet the decoder cannot use is skipped, like in `our_decode`.
1137- if decoder.decode_audio(&packet.data).is_err() {
1138- continue;
1139- }
1140- }
1141- let residue = decoder.take_residue_capture();
1142- let bits = decoder.take_bit_split();
1143- (residue, bits)
1144-}
1145-
1146-/// Bin two captures by Bark and compare every histogram cell.
1147-fn compare_captures(
1148- a: &[(usize, Vec<Vec<i32>>)],
1149- b: &[(usize, Vec<Vec<i32>>)],
1150- rate: u32,
1151-) -> (bool, String) {
1152- let bins = 6;
1153- let max_bark = 25;
1154- let mut ha = vec![vec![0u64; bins]; max_bark];
1155- let mut hb = vec![vec![0u64; bins]; max_bark];
1156- for (half, q) in a {
1157- accumulate(q, *half, rate, &mut ha, max_bark);
1158- }
1159- for (half, q) in b {
1160- accumulate(q, *half, rate, &mut hb, max_bark);
1161- }
1162- let mut diffs = Vec::new();
1163- for band in 0..max_bark {
1164- for bucket in 0..bins {
1165- if ha[band][bucket] != hb[band][bucket] {
1166- diffs.push(format!(
1167- "bark {band} q{bucket}: {} vs {}",
1168- ha[band][bucket], hb[band][bucket]
1169- ));
1170- }
1171- }
1172- }
1173- if diffs.is_empty() {
1174- (
1175- true,
1176- format!("identical histograms ({} vs {} blocks)", a.len(), b.len()),
1177- )
1178- } else {
1179- (
1180- false,
1181- format!(
1182- "{} vs {} blocks; first diffs: {}",
1183- a.len(),
1184- b.len(),
1185- diffs.iter().take(5).cloned().collect::<Vec<_>>().join("; ")
1186- ),
1187- )
1188- }
1189-}
1190-
1191-/// Decode with ffmpeg into planar f32, resampled to `rate`, limited to `max_samples`.
1192-fn ffmpeg_decode_limited(
1193- path: &Path,
1194- rate: u32,
1195- max_samples: usize,
1196-) -> Option<(Vec<Vec<f32>>, u32)> {
1197- let out = Command::new("ffmpeg")
1198- .args(["-v", "error", "-i"])
1199- .arg(path)
1200- .args([
1201- "-t",
1202- &format!("{}", max_samples / rate as usize),
1203- "-ac",
1204- "2",
1205- "-ar",
1206- &rate.to_string(),
1207- "-f",
1208- "f32le",
1209- "-acodec",
1210- "pcm_f32le",
1211- "-",
1212- ])
1213- .output()
1214- .expect("ffmpeg runs");
1215- if !out.stderr.is_empty() {
1216- eprintln!("ffmpeg stderr: {}", String::from_utf8_lossy(&out.stderr));
1217- return None;
1218- }
1219- let channels = 2usize;
1220- let interleaved: Vec<f32> = out
1221- .stdout
1222- .as_chunks::<4>()
1223- .0
1224- .iter()
1225- .map(|b| f32::from_le_bytes(*b))
1226- .collect();
1227- let n = interleaved.len() / channels;
1228- let n = n.min(max_samples);
1229- let mut planes: Vec<Vec<f32>> = (0..channels).map(|_| Vec::with_capacity(n)).collect();
1230- for (i, value) in interleaved.into_iter().enumerate().take(n * channels) {
1231- planes[i % channels].push(value);
1232- }
1233- Some((planes, rate))
1234-}
1235-
1236-/// Accumulate per-Bark-band |q| histograms from quantised residue.
1237-fn accumulate(
1238- quantised: &[Vec<i32>],
1239- half: usize,
1240- rate: u32,
1241- hist: &mut [Vec<u64>],
1242- max_bark: usize,
1243-) {
1244- for channel in quantised {
1245- for (bin, &q) in channel.iter().enumerate() {
1246- if bin >= half {
1247- break;
1248- }
1249- let hz = bin as f64 * f64::from(rate) / (2.0 * half as f64);
1250- let bark = VorbisEncoder::bark_hz(hz) as usize;
1251- let band = bark.min(max_bark - 1);
1252- let bucket = match q.abs() {
1253- 0 => 0,
1254- 1 => 1,
1255- 2 => 2,
1256- 3..=4 => 3,
1257- 5..=8 => 4,
1258- _ => 5,
1259- };
1260- hist[band][bucket] += 1;
1261- }
1262- }
1263-}
1264-
1265-/// Expand `~` in a path string.
1266-fn shellexpand(path: &str) -> String {
1267- if let Some(rest) = path.strip_prefix("~/") {
1268- let home = std::env::var("HOME").unwrap_or_else(|_| "/home".to_string());
1269- format!("{home}/{rest}")
1270- } else {
1271- path.to_string()
1272- }
1273-}
1274-
1275-/// Full-file sweep over the user's library at the two managed rates: ours
1276-/// encoded at the size libvorbis actually produced (ffmpeg's -b:a is
1277-/// unmanaged VBR, 10-30% under nominal on real music), bytes within ±3% of
1278-/// it and correlation-to-source within .005 of it. Both encodes decode
1279-/// through our decoder so the gap measures the encoders, not the decoders.
1280-/// Writes `lanes/vorbis-psy-r1.sweep.txt`.
1281-#[test]
1282-#[ignore = "slow: encodes 7 full sources × 2 rates, needs ffmpeg/libvorbis"]
1283-fn real_library_sweep_vs_reference() {
1284- let sources: &[(&str, &str)] = &[
1285- ("nik", "~/Music/reeln.mp4"),
1286- ("reelo", "~/Music/reelo.mp3"),
1287- ("her", "~/Music/reeli.mp3"),
1288- ("reell", "~/Music/reell.mp4"),
1289- ("reelm", "~/Music/reelm.wav"),
1290- ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),
1291- (
1292- "hein",
1293- "~/Downloads/reelm.mp3",
1294- ),
1295- ];
1296- let rate = 48_000u32;
1297- let max_samples = rate as usize * 600;
1298- let out_dir = scratch().join("vorbis7-sweep");
1299- std::fs::create_dir_all(&out_dir).expect("out dir");
1300- let mut table = String::from(
1301- "source kbps ours_kbps ref_kbps rate% corr_ours corr_ref gap minsec_o minsec_r drops verdict\n",
1302- );
1303- let mut failures = Vec::new();
1304- let only = std::env::var("SWEEP_ONLY").ok();
1305- let dump_drops = std::env::var("DROPS_DUMP").is_ok();
1306- let mut drops = String::new();
1307- let mut rows = 0usize;
1308- for &(name, src_path) in sources {
1309- if only
1310- .as_deref()
1311- .is_some_and(|o| !o.split(',').any(|n| n == name))
1312- {
1313- continue;
1314- }
1315- let src = PathBuf::from(shellexpand(src_path));
1316- if !src.exists() {
1317- table.push_str(&format!("{name:<7} - SKIP (missing)\n"));
1318- continue;
1319- }
1320- rows += 1;
1321- let Some((source_pcm, _)) = ffmpeg_decode_limited(&src, rate, max_samples) else {
1322- table.push_str(&format!("{name:<7} - SKIP (decode)\n"));
1323- continue;
1324- };
1325- let seconds = source_pcm[0].len() as f64 / f64::from(rate);
1326- for &kbps in &[96i32, 128] {
1327- // libvorbis under ffmpeg's -b:a runs unmanaged VBR and lands
1328- // 10-30% under the nominal rate on real music, so ours is asked
1329- // for the bytes it actually produced: quality at equal size.
1330- let reference = out_dir.join(format!("ref-{name}-{kbps}k.ogg"));
1331- let status = Command::new("ffmpeg")
1332- .args(["-y", "-v", "error", "-i"])
1333- .arg(&src)
1334- .args([
1335- "-vn",
1336- "-t",
1337- "600",
1338- "-ac",
1339- "2",
1340- "-ar",
1341- "48000",
1342- "-c:a",
1343- "libvorbis",
1344- "-b:a",
1345- &format!("{kbps}k"),
1346- ])
1347- .arg(&reference)
1348- .status()
1349- .expect("ffmpeg runs");
1350- assert!(status.success(), "libvorbis encode of {name} at {kbps}k");
1351- let bytes = |p: &Path| std::fs::metadata(p).expect("size").len() as f64;
1352- let ref_kbps = bytes(&reference) * 8.0 / seconds / 1000.0;
1353- let (ours, block_log) = encode_to_file_with_log(
1354- &source_pcm,
1355- rate,
1356- (ref_kbps * 1000.0).round() as i32,
1357- &format!("vorbis7-sweep/ours-{name}-{kbps}k.ogg"),
1358- );
1359- let ours_kbps = bytes(&ours) * 8.0 / seconds / 1000.0;
1360- let rate_pct = (ours_kbps / ref_kbps - 1.0) * 100.0;
1361- // Whole-file corr plus a per-second trace: a dropout (the
1362- // rate-loop windup class, 200 ms silences after transients) is
1363- // invisible in the mean and bimodal per second, so it is gated
1364- // as "seconds where ours is under 0.9 and the reference is not".
1365- let corr_of = |p: &Path| -> (f64, Vec<f64>) {
1366- let (pcm, _) = our_decode(p);
1367- let n = pcm[0].len().min(source_pcm[0].len());
1368- let mean = (0..2)
1369- .map(|c| correlation(&pcm[c][..n], &source_pcm[c][..n]))
1370- .sum::<f64>()
1371- / 2.0;
1372- let step = rate as usize;
1373- let per_second = (0..n / step)
1374- .map(|s| {
1375- let r = s * step..(s + 1) * step;
1376- (0..2)
1377- .map(|c| correlation(&pcm[c][r.clone()], &source_pcm[c][r.clone()]))
1378- .sum::<f64>()
1379- / 2.0
1380- })
1381- .collect();
1382- (mean, per_second)
1383- };
1384- let (corr_ours, sec_ours) = corr_of(&ours);
1385- let (corr_ref, sec_ref) = corr_of(&reference);
1386- let gap = corr_ref - corr_ours;
1387- let min_of = |v: &[f64]| v.iter().copied().fold(1.0f64, f64::min);
1388- let (min_ours, min_ref) = (min_of(&sec_ours), min_of(&sec_ref));
1389- let dropouts = sec_ours
1390- .iter()
1391- .zip(&sec_ref)
1392- .filter(|(o, r)| **o < 0.9 && **r >= 0.9)
1393- .count();
1394- let dropout_secs: Vec<usize> = sec_ours
1395- .iter()
1396- .zip(&sec_ref)
1397- .enumerate()
1398- .filter(|(_, (o, r))| **o < 0.9 && **r >= 0.9)
1399- .map(|(s, _)| s)
1400- .collect();
1401- let pass = rate_pct.abs() <= 3.0 && gap <= 0.005 && dropouts == 0;
1402- if !pass {
1403- failures.push(format!(
1404- "{name}@{kbps}k rate {rate_pct:+.2}% gap {gap:.4} dropouts {dropouts}"
1405- ));
1406- }
1407- table.push_str(&format!(
1408- "{name:<7} {kbps:<6} {ours_kbps:<9.1} {ref_kbps:<8.1} {rate_pct:+6.2} {corr_ours:<9.4} {corr_ref:<8.4} {gap:<7.4} {min_ours:<8.3} {min_ref:<7.3} {dropouts:<5} {}\n",
1409- if pass { "PASS" } else { "FAIL" }
1410- ));
1411- eprintln!("{}", table.lines().last().unwrap());
1412- if dump_drops {
1413- drops.push_str(&format!(
1414- "\n=== {name}@{kbps}k rate {rate_pct:+.2}% gap {gap:.4} dropouts {dropouts} ===\n"
1415- ));
1416- for &s in &dropout_secs {
1417- let lo = (s.saturating_sub(2)) as i64 * rate as i64;
1418- let hi = (s + 3) as i64 * rate as i64;
1419- drops.push_str(&format!(
1420- " sec {s}: ours {:.3} ref {:.3}\n",
1421- sec_ours[s], sec_ref[s]
1422- ));
1423- drops.push_str(" idx centre_s n kind steady bits headroom rate_hr reservoir target\n");
1424- for (i, b) in block_log.iter().enumerate() {
1425- if b.centre < lo || b.centre >= hi {
1426- continue;
1427- }
1428- drops.push_str(&format!(
1429- " {i:<4} {:>8.2} {:<5} {:<5} {:<6} {:<6} {:>8.1} {:>7.1} {:>9.1} {:>7.1}\n",
1430- b.centre as f64 / rate as f64,
1431- b.n,
1432- if b.is_long { "L" } else { "S" },
1433- b.steady,
1434- b.bits,
1435- b.headroom,
1436- b.rate_headroom,
1437- b.reservoir,
1438- b.target,
1439- ));
1440- }
1441- }
1442- }
1443- }
1444- }
1445- eprintln!("\n{table}");
1446- if dump_drops {
1447- let _ = std::fs::write(
1448- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes/vorbis-hf-r2.drops.txt"),
1449- &drops,
1450- );
1451- }
1452- let _ = std::fs::write(
1453- Path::new(env!("CARGO_MANIFEST_DIR")).join("../../lanes/vorbis-psy-r1.sweep.txt"),
1454- &table,
1455- );
1456- assert!(rows > 0, "no library sources were readable");
1457- assert!(failures.is_empty(), "sweep failures: {failures:?}");
1458-}
1459-
1460-/// In-place radix-2 FFT. Only magnitudes and differences of identically
1461-/// transformed spectra are used, so the twiddle sign convention is irrelevant.
1462-fn fft(re: &mut [f64], im: &mut [f64]) {
1463- let n = re.len();
1464- assert!(n.is_power_of_two());
1465- let bits = n.trailing_zeros();
1466- for i in 0..n {
1467- let j = ((i as u32).reverse_bits() >> (32 - bits)) as usize;
1468- if j > i {
1469- re.swap(i, j);
1470- im.swap(i, j);
1471- }
1472- }
1473- let mut len = 2;
1474- while len <= n {
1475- let half = len / 2;
1476- let step = std::f64::consts::TAU / len as f64;
1477- for start in (0..n).step_by(len) {
1478- for k in 0..half {
1479- let angle = step * k as f64;
1480- let (wr, wi) = (angle.cos(), angle.sin());
1481- let i = start + k;
1482- let j = i + half;
1483- let tr = re[j] * wr - im[j] * wi;
1484- let ti = re[j] * wi + im[j] * wr;
1485- re[j] = re[i] - tr;
1486- im[j] = im[i] - ti;
1487- re[i] += tr;
1488- im[i] += ti;
1489- }
1490- }
1491- len *= 2;
1492- }
1493-}
1494-
1495-/// Per-Bark-band spectral error, ours vs libvorbis, both decoded through our
1496-/// decoder (so the gap measures encoders, not decoders): every 2048-sample
1497-/// Hann frame (hop 1024) of the 48 kHz source, band edges in Hz (25 edges →
1498-/// 24 bands), energies summed over frames and both channels.
1499-/// NSR = 10log10(Σ|X_sig−X_src|²/Σ|X_src|²), E = 10log10(Σ|X_sig|²/Σ|X_src|²).
1500-/// The same pass records the bit split of both streams (the decode-side
1501-/// capture `decode_capture_with_bits` provides), so the bits table covers the
1502-/// same rows without a second encode pass. Writes
1503-/// `lanes/vorbis-psy-r1.bands.txt` and `lanes/vorbis-psy-r1.bits.txt`.
1504-#[test]
1505-#[ignore = "slow: encodes 7 full sources × 2 rates, needs ffmpeg/libvorbis"]
1506-fn band_error_vs_reference() {
1507- use std::io::Write;
1508-
1509- let sources: &[(&str, &str)] = &[
1510- ("nik", "~/Music/reeln.mp4"),
1511- ("reelo", "~/Music/reelo.mp3"),
1512- ("her", "~/Music/reeli.mp3"),
1513- ("reell", "~/Music/reell.mp4"),
1514- ("reelm", "~/Music/reelm.wav"),
1515- ("dl8a", "~/Downloads/8a3b6d1d19.mp3"),
1516- (
1517- "hein",
1518- "~/Downloads/reelm.mp3",
1519- ),
1520- ];
1521- let rate = 48_000u32;
1522- let max_samples = rate as usize * 600;
1523- let out_dir = scratch().join("vorbis7-bands");
1524- std::fs::create_dir_all(&out_dir).expect("out dir");
1525-
1526- const FRAME: usize = 2048;
1527- const HOP: usize = 1024;
1528- const EDGES: [f64; 25] = [
1529- 100.0, 200.0, 300.0, 400.0, 510.0, 630.0, 770.0, 920.0, 1080.0, 1270.0, 1480.0, 1720.0,
1530- 2000.0, 2320.0, 2700.0, 3150.0, 3700.0, 4400.0, 5300.0, 6400.0, 7700.0, 9500.0, 12000.0,
1531- 15500.0, 24000.0,
1532- ];
1533- let band_of: Vec<Option<usize>> = (0..=FRAME / 2)
1534- .map(|bin| {
1535- let hz = bin as f64 * f64::from(rate) / FRAME as f64;
1536- EDGES.windows(2).position(|w| hz >= w[0] && hz < w[1])
1537- })
1538- .collect();
1539- let window: Vec<f64> = (0..FRAME)
1540- .map(|i| 0.5 - 0.5 * (std::f64::consts::TAU * i as f64 / FRAME as f64).cos())
1541- .collect();
1542-
1543- let mut bands = String::from("# Band error: ours vs libvorbis, both via our decoder\n\n");
1544- let mut bits = String::from("# Bit split over full sources, same rows as the band error\n\n");
1545- let only = std::env::var("SWEEP_ONLY").ok();
1546- let mut rows = 0usize;
1547- for &(name, src_path) in sources {
1548- if only
1549- .as_deref()
1550- .is_some_and(|o| !o.split(',').any(|n| n == name))
1551- {
1552- continue;
1553- }
1554- let src = PathBuf::from(shellexpand(src_path));
1555- if !src.exists() {
1556- bands.push_str(&format!("## {name}: SKIP (missing)\n\n"));
1557- continue;
1558- }
1559- rows += 1;
1560- let Some((source_pcm, _)) = ffmpeg_decode_limited(&src, rate, max_samples) else {
1561- bands.push_str(&format!("## {name}: SKIP (decode)\n\n"));
1562- continue;
1563- };
1564- let seconds = source_pcm[0].len() as f64 / f64::from(rate);
1565- let bytes = |p: &Path| std::fs::metadata(p).expect("size").len() as f64;
1566- for &kbps in &[96i32, 128] {
1567- let t0 = std::time::Instant::now();
1568- let reference = out_dir.join(format!("ref-{name}-{kbps}k.ogg"));
1569- let status = Command::new("ffmpeg")
1570- .args(["-y", "-v", "error", "-i"])
1571- .arg(&src)
1572- .args([
1573- "-vn",
1574- "-t",
1575- "600",
1576- "-ac",
1577- "2",
1578- "-ar",
1579- "48000",
1580- "-c:a",
1581- "libvorbis",
1582- "-b:a",
1583- &format!("{kbps}k"),
1584- ])
1585- .arg(&reference)
1586- .status()
1587- .expect("ffmpeg runs");
1588- assert!(status.success(), "libvorbis encode of {name} at {kbps}k");
1589- let ref_kbps = bytes(&reference) * 8.0 / seconds / 1000.0;
1590- // Ours at the size libvorbis actually produced, exactly as the sweep.
1591- let ours = encode_to_file(
1592- &source_pcm,
1593- rate,
1594- (ref_kbps * 1000.0).round() as i32,
1595- &format!("vorbis7-bands/ours-{name}-{kbps}k.ogg"),
1596- );
1597- let ours_kbps = bytes(&ours) * 8.0 / seconds / 1000.0;
1598-
1599- // PCM through our decoder for the band error; bit split from the
1600- // same file's residue-domain capture (decode twice — the capture
1601- // path returns no PCM).
1602- let (ours_pcm, ours_split) = {
1603- let (residue, split) = decode_capture_with_bits(&ours);
1604- (our_decode(&ours).0, bit_split_summary(&split, &residue))
1605- };
1606- let (ref_pcm, ref_split) = {
1607- let (residue, split) = decode_capture_with_bits(&reference);
1608- (
1609- our_decode(&reference).0,
1610- bit_split_summary(&split, &residue),
1611- )
1612- };
1613-
1614- // Bit-split block: (floor, residue, packet, non-zero) per stream.
1615- let (of, ores, op, onz) = ours_split;
1616- let (rf, rres, rp, rnz) = ref_split;
1617- bits.push_str(&format!(
1618- "## {name} @ {kbps}k (ours {ours_kbps:.1} vs ref {ref_kbps:.1} kbps)\n"
1619- ));
1620- for (who, f, r, p, nz) in [("ours", of, ores, op, onz), ("ref ", rf, rres, rp, rnz)] {
1621- bits.push_str(&format!(
1622- "{who} floor {fb:>10.1}/s ({fpc:5.1}%) residue {rb:>10.1}/s ({rpc:5.1}%) other {ob:>8.1}/s nz {nz:>10} bits/nz {bnz:.2}\n",
1623- fb = f as f64 / seconds,
1624- fpc = 100.0 * f as f64 / p.max(1) as f64,
1625- rb = r as f64 / seconds,
1626- rpc = 100.0 * r as f64 / p.max(1) as f64,
1627- ob = p.saturating_sub(f + r) as f64 / seconds,
1628- bnz = r as f64 / nz.max(1) as f64,
1629- ));
1630- }
1631- bits.push_str(&format!(
1632- "ratio floor {:.3} residue {:.3} bits/nz {:.3}\n\n",
1633- of as f64 / rf.max(1) as f64,
1634- ores as f64 / rres.max(1) as f64,
1635- (ores as f64 / onz.max(1) as f64) / (rres as f64 / rnz.max(1) as f64),
1636- ));
1637-
1638- // Band error: align to the source exactly as the sweep does —
1639- // common length from sample 0 (pre-roll trim inside `our_decode`).
1640- let n = source_pcm[0]
1641- .len()
1642- .min(ours_pcm[0].len())
1643- .min(ref_pcm[0].len());
1644- let nb = EDGES.len() - 1;
1645- let (mut e_src, mut e_ours, mut e_ref) =
1646- (vec![0f64; nb], vec![0f64; nb], vec![0f64; nb]);
1647- let (mut err_ours, mut err_ref) = (vec![0f64; nb], vec![0f64; nb]);
1648- let mut spec: Vec<(Vec<f64>, Vec<f64>)> = (0..3)
1649- .map(|_| (vec![0.0; FRAME], vec![0.0; FRAME]))
1650- .collect();
1651- let mut start = 0;
1652- while start + FRAME <= n {
1653- for ch in 0..2 {
1654- for (sig, pcm) in [&source_pcm, &ours_pcm, &ref_pcm].iter().enumerate() {
1655- let s = &mut spec[sig];
1656- for i in 0..FRAME {
1657- s.0[i] = f64::from(pcm[ch][start + i]) * window[i];
1658- s.1[i] = 0.0;
1659- }
1660- fft(&mut s.0, &mut s.1);
1661- }
1662- for (k, band) in band_of.iter().enumerate().take(FRAME / 2 + 1) {
1663- let Some(b) = *band else { continue };
1664- let (sr, si) = (spec[0].0[k], spec[0].1[k]);
1665- e_src[b] += sr * sr + si * si;
1666- let (ur, ui) = (spec[1].0[k], spec[1].1[k]);
1667- e_ours[b] += ur * ur + ui * ui;
1668- let (dr, di) = (ur - sr, ui - si);
1669- err_ours[b] += dr * dr + di * di;
1670- let (vr, vi) = (spec[2].0[k], spec[2].1[k]);
1671- e_ref[b] += vr * vr + vi * vi;
1672- let (er, ei) = (vr - sr, vi - si);
1673- err_ref[b] += er * er + ei * ei;
1674- }
1675- }
1676- start += HOP;
1677- }
1678- let db = |e: f64, s: f64| {
1679- if s > 0.0 {
1680- 10.0 * (e / s).log10()
1681- } else {
1682- f64::NAN
1683- }
1684- };
1685- bands.push_str(&format!(
1686- "## {name} @ {kbps}k (ours {ours_kbps:.1} vs ref {ref_kbps:.1} kbps)\n"
1687- ));
1688- bands.push_str("band NSR_ours NSR_ref dNSR E_ours E_ref\n");
1689- for b in 0..nb {
1690- if e_src[b] == 0.0 {
1691- continue; // no source energy: NSR/E undefined
1692- }
1693- let (nsr_o, nsr_r) = (db(err_ours[b], e_src[b]), db(err_ref[b], e_src[b]));
1694- bands.push_str(&format!(
1695- "{:<8} {:7.1} {:7.1} {:6.1} {:7.1} {:7.1}\n",
1696- format!("{}-{}", EDGES[b] as usize, EDGES[b + 1] as usize),
1697- nsr_o,
1698- nsr_r,
1699- nsr_o - nsr_r,
1700- db(e_ours[b], e_src[b]),
1701- db(e_ref[b], e_src[b]),
1702- ));
1703- }
1704- let corr = |pcm: &[Vec<f32>]| {
1705- (0..2)
1706- .map(|c| correlation(&pcm[c][..n], &source_pcm[c][..n]))
1707- .sum::<f64>()
1708- / 2.0
1709- };
1710- bands.push_str(&format!(
1711- "broadband corr: ours {:.4} ref {:.4}\n\n",
1712- corr(&ours_pcm),
1713- corr(&ref_pcm),
1714- ));
1715- eprintln!(
1716- "{name}@{kbps}k: ours {ours_kbps:.1} ref {ref_kbps:.1} kbps, {:.1} s",
1717- t0.elapsed().as_secs_f32()
1718- );
1719- }
1720- }
1721- // Both report files above are written unconditionally, so a run that
1722- // measured no source writes a report indistinguishable from a real one.
1723- assert!(rows > 0, "no library sources were readable");
1724- for (text, file) in [
1725- (&bands, "vorbis-psy-r1.bands.txt"),
1726- (&bits, "vorbis-psy-r1.bits.txt"),
1727- ] {
1728- let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1729- .join("../../lanes")
1730- .join(file);
1731- let mut f = File::create(&path).expect("create report");
1732- f.write_all(text.as_bytes()).expect("write report");
1733- println!("{file}: {}", path.display());
1734- }
1735-}
crates/ec-vorbis/tests/trim.rsmodified+2 -3
@@ -7,7 +7,6 @@
7 7
8 use std::fs::File;8 use std::fs::File;
9 use std::path::{Path, PathBuf};9 use std::path::{Path, PathBuf};
10-use std::process::Command;
11 10
12 use ec_core::{Buf, Decoder, Demuxer, Frame, Packet, TimeBase};11 use ec_core::{Buf, Decoder, Demuxer, Frame, Packet, TimeBase};
13 use ec_ogg::{OggDemuxer, granule_of, granule_side_data};12 use ec_ogg::{OggDemuxer, granule_of, granule_side_data};
@@ -22,7 +21,7 @@ fn scratch() -> PathBuf {
22 /// A sine of `seconds` at `rate`, libvorbis-encoded to `path`. Returns the21 /// A sine of `seconds` at `rate`, libvorbis-encoded to `path`. Returns the
23 /// number of sample frames the source holds.22 /// number of sample frames the source holds.
24 fn encode(path: &Path, rate: u32, channels: u32, seconds: f64) -> usize {23 fn encode(path: &Path, rate: u32, channels: u32, seconds: f64) -> usize {
25- let status = Command::new("ffmpeg")24+ let status = ec_testkit::ffmpeg()
26 .args(["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i"])25 .args(["-nostdin", "-v", "error", "-y", "-f", "lavfi", "-i"])
27 .arg(format!(26 .arg(format!(
28 "sine=frequency=440:sample_rate={rate}:duration={seconds}"27 "sine=frequency=440:sample_rate={rate}:duration={seconds}"
@@ -48,7 +47,7 @@ fn encode(path: &Path, rate: u32, channels: u32, seconds: f64) -> usize {
48 47
49 /// ffmpeg's own decode, planar f32, one vector per channel.48 /// ffmpeg's own decode, planar f32, one vector per channel.
50 fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<Vec<f32>> {49 fn ffmpeg_decode(path: &Path, channels: usize) -> Vec<Vec<f32>> {
51- let out = Command::new("ffmpeg")50+ let out = ec_testkit::ffmpeg()
52 .args(["-nostdin", "-v", "error", "-i"])51 .args(["-nostdin", "-v", "error", "-i"])
53 .arg(path)52 .arg(path)
54 .args(["-map", "0:a:0", "-f", "f32le", "-"])53 .args(["-map", "0:a:0", "-f", "f32le", "-"])