forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB35bdf35Tahinli2 months ago3757 commits

encode_matrix.rs308 lines, 10.6 KiBHistoryRawDownload
1//! Our encoder against the fixture matrix, proven the only way a lossless
2//! codec can be: encode, decode the result with ffmpeg, compare with the input
3//! byte for byte.
4//!
5//! The size column is informational — it is the same corpus measured against
6//! `ffmpeg -c:a flac` at its default compression level.
7//!
8//! Run the table:
9//! cargo test -p ec-flac --release --test encode_matrix -- --nocapture
10
11use std::path::{Path, PathBuf};
12use std::process::Command;
13
14use ec_flac::encode::{EncoderConfig, encode};
15
16struct Source {
17 path: PathBuf,
18 channels: usize,
19 rate: u32,
20 bits: u32,
21}
22
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.
33fn 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
47fn 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 one
52/// process, so a shared temp directory would have them deleting each other's
53/// files.
54fn workdir(test: &str) -> PathBuf {
55 let dir = std::env::temp_dir().join(format!("ec-flac-{}-{test}", std::process::id()));
56 std::fs::create_dir_all(&dir).expect("create work dir");
57 dir
58}
59
60fn probe(path: &Path) -> Option<Source> {
61 let out = Command::new("ffprobe")
62 .args([
63 "-v",
64 "error",
65 "-select_streams",
66 "a:0",
67 "-show_entries",
68 "stream=channels,sample_rate,bits_per_raw_sample,sample_fmt",
69 "-of",
70 "default=noprint_wrappers=1",
71 ])
72 .arg(path)
73 .output()
74 .ok()?;
75 // Key=value, because ffprobe prints its own field order, not the requested
76 // one — a positional parse silently swaps rate and channels.
77 let text = String::from_utf8_lossy(&out.stdout);
78 let field = |key: &str| {
79 text.lines()
80 .find_map(|l| l.strip_prefix(key)?.strip_prefix('='))
81 .map(str::trim)
82 };
83 let bits = match field("bits_per_raw_sample").and_then(|v| v.parse::<u32>().ok()) {
84 Some(n) => n,
85 // WAV states no `bits_per_raw_sample`; its sample format carries it.
86 None => match field("sample_fmt")? {
87 "s16" | "s16p" => 16,
88 "s32" | "s32p" => 32,
89 "u8" | "u8p" => 8,
90 _ => return None,
91 },
92 };
93 Some(Source {
94 path: path.to_path_buf(),
95 channels: field("channels")?.parse().ok()?,
96 rate: field("sample_rate")?.parse().ok()?,
97 bits,
98 })
99}
100
101fn ffmpeg_pcm(path: &Path, bits: u32) -> Vec<u8> {
102 let format = if bits <= 16 { "s16le" } else { "s32le" };
103 let out = Command::new("ffmpeg")
104 .args(["-v", "error", "-i"])
105 .arg(path)
106 .args(["-f", format, "-"])
107 .output()
108 .expect("run ffmpeg");
109 assert!(
110 out.status.success(),
111 "ffmpeg failed on {}: {}",
112 path.display(),
113 String::from_utf8_lossy(&out.stderr)
114 );
115 out.stdout
116}
117
118/// Raw PCM as the samples FLAC codes: the container shift undone.
119fn samples_from_pcm(pcm: &[u8], bits: u32) -> Vec<i32> {
120 match bits <= 16 {
121 true => pcm
122 .chunks_exact(2)
123 .map(|c| i32::from(i16::from_le_bytes([c[0], c[1]])) >> (16 - bits))
124 .collect(),
125 false => pcm
126 .chunks_exact(4)
127 .map(|c| i32::from_le_bytes([c[0], c[1], c[2], c[3]]) >> (32 - bits))
128 .collect(),
129 }
130}
131
132fn ffmpeg_flac_size(src: &Path, out: &Path) -> Option<u64> {
133 let _ = std::fs::remove_file(out);
134 let status = Command::new("ffmpeg")
135 .args(["-v", "error", "-y", "-i"])
136 .arg(src)
137 .args(["-c:a", "flac"])
138 .arg(out)
139 .status()
140 .ok()?;
141 match status.success() {
142 true => std::fs::metadata(out).ok().map(|m| m.len()),
143 false => None,
144 }
145}
146
147fn matrix() -> Vec<Source> {
148 let audio = fixtures().join("audio");
149 let vectors = fixtures().join("vectors/flac-xiph/flac-test-files-main/subset");
150 let mut paths: Vec<PathBuf> = Vec::new();
151 // Probe first, assert inside the helper, and only then take the empty-list
152 // branch: under EC_REQUIRE_FIXTURES the assert fires instead of a silent
153 // skip that leaves every loop below running zero times.
154 if require_fixture(&audio, "scripts/gen-fixtures.sh") {
155 let entries = std::fs::read_dir(&audio)
156 .unwrap_or_else(|e| panic!("read fixture dir {}: {e}", audio.display()));
157 let mut found: Vec<PathBuf> = entries
158 .filter_map(|e| e.ok().map(|e| e.path()))
159 .filter(|p| {
160 let name = p.file_name().unwrap_or_default().to_string_lossy();
161 name.starts_with("flac-") || name.starts_with("wav16-")
162 })
163 .collect();
164 found.sort();
165 paths.append(&mut found);
166 }
167 // Depth coverage the generated fixtures do not have: 24- and 20-bit.
168 if require_fixture(&vectors, "scripts/fetch-vectors.sh") {
169 for name in [
170 "28 - high resolution audio, default settings.flac",
171 "37 - 20 bit per sample.flac",
172 ] {
173 let p = vectors.join(name);
174 if p.exists() {
175 paths.push(p);
176 }
177 }
178 }
179 paths.iter().filter_map(|p| probe(p)).collect()
180}
181
182#[test]
183fn encoded_streams_decode_back_bit_exact_through_ffmpeg() {
184 let sources = matrix();
185 if sources.is_empty() {
186 eprintln!("skipped: fixtures not generated");
187 return;
188 }
189 // Non-empty floor: the loop below must run, not zero times.
190 assert!(
191 sources.len() >= 5,
192 "encoder matrix holds {} usable sources, expected at least 5",
193 sources.len()
194 );
195 let dir = workdir("roundtrip");
196 let config = EncoderConfig::default();
197 let mut failures = Vec::new();
198 let (mut ours_total, mut theirs_total) = (0u64, 0u64);
199 println!(
200 "{:<34} {:>3} {:>3} {:>7} {:>10} {:>10} {:>6}",
201 "fixture", "ch", "bit", "rate", "ours", "ffmpeg", "ratio"
202 );
203 for source in &sources {
204 let name = source
205 .path
206 .file_name()
207 .unwrap_or_default()
208 .to_string_lossy()
209 .to_string();
210 let pcm = ffmpeg_pcm(&source.path, source.bits);
211 let samples = samples_from_pcm(&pcm, source.bits);
212 let encoded = match encode(&config, &samples, source.channels, source.bits, source.rate) {
213 Ok(bytes) => bytes,
214 Err(e) => {
215 failures.push(format!("{name}: encode failed: {e}"));
216 continue;
217 }
218 };
219 let out = dir.join(format!("{name}.ours.flac"));
220 std::fs::write(&out, &encoded).expect("write encoded");
221 let decoded = ffmpeg_pcm(&out, source.bits);
222 if decoded != pcm {
223 let at = decoded
224 .iter()
225 .zip(&pcm)
226 .position(|(a, b)| a != b)
227 .map_or_else(|| "length only".to_string(), |i| format!("byte {i}"));
228 failures.push(format!(
229 "{name}: ffmpeg decoded our stream differently at {at} ({} vs {} bytes)",
230 decoded.len(),
231 pcm.len()
232 ));
233 continue;
234 }
235 let theirs = ffmpeg_flac_size(&source.path, &dir.join(format!("{name}.ffmpeg.flac")));
236 ours_total += encoded.len() as u64;
237 theirs_total += theirs.unwrap_or(0);
238 println!(
239 "{:<34} {:>3} {:>3} {:>7} {:>10} {:>10} {:>6}",
240 name,
241 source.channels,
242 source.bits,
243 source.rate,
244 encoded.len(),
245 theirs.map_or("-".to_string(), |n| n.to_string()),
246 theirs.map_or("-".to_string(), |n| format!(
247 "{:.3}",
248 encoded.len() as f64 / n as f64
249 )),
250 );
251 }
252 println!(
253 "totals: ours {ours_total}, ffmpeg {theirs_total}, ratio {:.3}",
254 ours_total as f64 / theirs_total.max(1) as f64
255 );
256 assert!(failures.is_empty(), "{}", failures.join("\n"));
257 // Informational bar from the slice charter: within 10% of ffmpeg's default.
258 assert!(
259 ours_total as f64 <= theirs_total as f64 * 1.10,
260 "corpus is {:.1}% larger than ffmpeg's default FLAC",
261 (ours_total as f64 / theirs_total as f64 - 1.0) * 100.0
262 );
263}
264
265#[test]
266fn our_streams_survive_a_probe_and_state_their_shape() {
267 // The 5.1 source this test needs is a named fixture, not a shape we hope the
268 // matrix happens to contain: probe it first so EC_REQUIRE_FIXTURES fails on
269 // a drifted library instead of skipping.
270 let surround = fixtures().join("audio/flac-5.1-44100.flac");
271 if !require_fixture(&surround, "scripts/gen-fixtures.sh") {
272 return;
273 }
274 let source = matrix()
275 .into_iter()
276 .find(|s| s.channels == 6)
277 .or_else(|| probe(&surround))
278 .expect("5.1 source in the encoder matrix");
279 let dir = workdir("probe");
280 let pcm = ffmpeg_pcm(&source.path, source.bits);
281 let samples = samples_from_pcm(&pcm, source.bits);
282 let encoded = encode(
283 &EncoderConfig::default(),
284 &samples,
285 source.channels,
286 source.bits,
287 source.rate,
288 )
289 .expect("encode");
290 let out = dir.join("surround.flac");
291 std::fs::write(&out, &encoded).expect("write");
292 let probed = probe(&out).expect("ffprobe our own output");
293 assert_eq!(probed.channels, source.channels);
294 assert_eq!(probed.rate, source.rate);
295 assert_eq!(probed.bits, source.bits);
296 // `-v error` clean: ffmpeg must find nothing to complain about.
297 let out_err = Command::new("ffmpeg")
298 .args(["-v", "error", "-i"])
299 .arg(&out)
300 .args(["-f", "null", "-"])
301 .output()
302 .expect("run ffmpeg");
303 assert!(
304 out_err.stderr.is_empty(),
305 "ffmpeg complained: {}",
306 String::from_utf8_lossy(&out_err.stderr)
307 );
308}