forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust376.2 MiBa69dfabTahinli5 hours ago4073 commits

encode_matrix.rs260 lines, 8.5 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};
12
13use ec_flac::encode::{EncoderConfig, encode};
14
15struct Source {
16 path: PathBuf,
17 channels: usize,
18 rate: u32,
19 bits: u32,
20}
21
22/// A working directory keyed by test name: these tests are threads of one
23/// process, so a shared temp directory would have them deleting each other's
24/// files.
25fn workdir(test: &str) -> PathBuf {
26 let dir = std::env::temp_dir().join(format!("ec-flac-{}-{test}", std::process::id()));
27 std::fs::create_dir_all(&dir).expect("create work dir");
28 dir
29}
30
31fn probe(path: &Path) -> Option<Source> {
32 let out = ec_testkit::ffprobe()
33 .args([
34 "-v",
35 "error",
36 "-select_streams",
37 "a:0",
38 "-show_entries",
39 "stream=channels,sample_rate,bits_per_raw_sample,sample_fmt",
40 "-of",
41 "default=noprint_wrappers=1",
42 ])
43 .arg(path)
44 .output()
45 .expect("run ffprobe");
46 // Key=value, because ffprobe prints its own field order, not the requested
47 // one — a positional parse silently swaps rate and channels.
48 let text = String::from_utf8_lossy(&out.stdout);
49 let field = |key: &str| {
50 text.lines()
51 .find_map(|l| l.strip_prefix(key)?.strip_prefix('='))
52 .map(str::trim)
53 };
54 let bits = match field("bits_per_raw_sample").and_then(|v| v.parse::<u32>().ok()) {
55 Some(n) => n,
56 // WAV states no `bits_per_raw_sample`; its sample format carries it.
57 None => match field("sample_fmt")? {
58 "s16" | "s16p" => 16,
59 "s32" | "s32p" => 32,
60 "u8" | "u8p" => 8,
61 _ => return None,
62 },
63 };
64 Some(Source {
65 path: path.to_path_buf(),
66 channels: field("channels")?.parse().ok()?,
67 rate: field("sample_rate")?.parse().ok()?,
68 bits,
69 })
70}
71
72fn ffmpeg_pcm(path: &Path, bits: u32) -> Vec<u8> {
73 let format = if bits <= 16 { "s16le" } else { "s32le" };
74 let out = ec_testkit::ffmpeg()
75 .args(["-v", "error", "-i"])
76 .arg(path)
77 .args(["-f", format, "-"])
78 .output()
79 .expect("run ffmpeg");
80 assert!(
81 out.status.success(),
82 "ffmpeg failed on {}: {}",
83 path.display(),
84 String::from_utf8_lossy(&out.stderr)
85 );
86 out.stdout
87}
88
89/// Raw PCM as the samples FLAC codes: the container shift undone.
90fn samples_from_pcm(pcm: &[u8], bits: u32) -> Vec<i32> {
91 match bits <= 16 {
92 true => pcm
93 .as_chunks::<2>()
94 .0
95 .iter()
96 .map(|c| i32::from(i16::from_le_bytes(*c)) >> (16 - bits))
97 .collect(),
98 false => pcm
99 .as_chunks::<4>()
100 .0
101 .iter()
102 .map(|c| i32::from_le_bytes(*c) >> (32 - bits))
103 .collect(),
104 }
105}
106
107fn ffmpeg_flac_size(src: &Path, out: &Path) -> Option<u64> {
108 let _ = std::fs::remove_file(out);
109 let status = ec_testkit::ffmpeg()
110 .args(["-v", "error", "-y", "-i"])
111 .arg(src)
112 .args(["-c:a", "flac"])
113 .arg(out)
114 .status()
115 .expect("run ffmpeg");
116 match status.success() {
117 true => std::fs::metadata(out).ok().map(|m| m.len()),
118 false => None,
119 }
120}
121
122fn matrix() -> Vec<Source> {
123 let mut paths: Vec<PathBuf> = std::fs::read_dir(ec_testkit::root().join("audio"))
124 .expect("fixture audio directory")
125 .map(|e| e.expect("fixture entry").path())
126 .filter(|p| {
127 let name = p.file_name().unwrap_or_default().to_string_lossy();
128 name.starts_with("flac-") || name.starts_with("wav16-")
129 })
130 .collect();
131 paths.sort();
132 // Depth coverage the generated fixtures do not have: 24- and 20-bit.
133 for name in [
134 "28 - high resolution audio, default settings.flac",
135 "37 - 20 bit per sample.flac",
136 ] {
137 paths.push(ec_testkit::fixture(&format!(
138 "vectors/flac-xiph/flac-test-files-main/subset/{name}"
139 )));
140 }
141 paths.iter().filter_map(|p| probe(p)).collect()
142}
143
144#[test]
145fn encoded_streams_decode_back_bit_exact_through_ffmpeg() {
146 let sources = matrix();
147 // Non-empty floor: the loop below must run, not zero times.
148 assert!(
149 sources.len() >= 5,
150 "encoder matrix holds {} usable sources, expected at least 5",
151 sources.len()
152 );
153 let dir = workdir("roundtrip");
154 let config = EncoderConfig::default();
155 let mut failures = Vec::new();
156 let (mut ours_total, mut theirs_total) = (0u64, 0u64);
157 println!(
158 "{:<34} {:>3} {:>3} {:>7} {:>10} {:>10} {:>6}",
159 "fixture", "ch", "bit", "rate", "ours", "ffmpeg", "ratio"
160 );
161 for source in &sources {
162 let name = source
163 .path
164 .file_name()
165 .unwrap_or_default()
166 .to_string_lossy()
167 .to_string();
168 let pcm = ffmpeg_pcm(&source.path, source.bits);
169 let samples = samples_from_pcm(&pcm, source.bits);
170 let encoded = match encode(&config, &samples, source.channels, source.bits, source.rate) {
171 Ok(bytes) => bytes,
172 Err(e) => {
173 failures.push(format!("{name}: encode failed: {e}"));
174 continue;
175 }
176 };
177 let out = dir.join(format!("{name}.ours.flac"));
178 std::fs::write(&out, &encoded).expect("write encoded");
179 let decoded = ffmpeg_pcm(&out, source.bits);
180 if decoded != pcm {
181 let at = decoded
182 .iter()
183 .zip(&pcm)
184 .position(|(a, b)| a != b)
185 .map_or_else(|| "length only".to_string(), |i| format!("byte {i}"));
186 failures.push(format!(
187 "{name}: ffmpeg decoded our stream differently at {at} ({} vs {} bytes)",
188 decoded.len(),
189 pcm.len()
190 ));
191 continue;
192 }
193 let theirs = ffmpeg_flac_size(&source.path, &dir.join(format!("{name}.ffmpeg.flac")));
194 ours_total += encoded.len() as u64;
195 theirs_total += theirs.unwrap_or(0);
196 println!(
197 "{:<34} {:>3} {:>3} {:>7} {:>10} {:>10} {:>6}",
198 name,
199 source.channels,
200 source.bits,
201 source.rate,
202 encoded.len(),
203 theirs.map_or("-".to_string(), |n| n.to_string()),
204 theirs.map_or("-".to_string(), |n| format!(
205 "{:.3}",
206 encoded.len() as f64 / n as f64
207 )),
208 );
209 }
210 println!(
211 "totals: ours {ours_total}, ffmpeg {theirs_total}, ratio {:.3}",
212 ours_total as f64 / theirs_total.max(1) as f64
213 );
214 assert!(failures.is_empty(), "{}", failures.join("\n"));
215 // Informational bar from the slice charter: within 10% of ffmpeg's default.
216 assert!(
217 ours_total as f64 <= theirs_total as f64 * 1.10,
218 "corpus is {:.1}% larger than ffmpeg's default FLAC",
219 (ours_total as f64 / theirs_total as f64 - 1.0) * 100.0
220 );
221}
222
223#[test]
224fn our_streams_survive_a_probe_and_state_their_shape() {
225 let surround = ec_testkit::fixture("audio/flac-5.1-44100.flac");
226 let source = matrix()
227 .into_iter()
228 .find(|s| s.channels == 6)
229 .or_else(|| probe(&surround))
230 .expect("5.1 source in the encoder matrix");
231 let dir = workdir("probe");
232 let pcm = ffmpeg_pcm(&source.path, source.bits);
233 let samples = samples_from_pcm(&pcm, source.bits);
234 let encoded = encode(
235 &EncoderConfig::default(),
236 &samples,
237 source.channels,
238 source.bits,
239 source.rate,
240 )
241 .expect("encode");
242 let out = dir.join("surround.flac");
243 std::fs::write(&out, &encoded).expect("write");
244 let probed = probe(&out).expect("ffprobe our own output");
245 assert_eq!(probed.channels, source.channels);
246 assert_eq!(probed.rate, source.rate);
247 assert_eq!(probed.bits, source.bits);
248 // `-v error` clean: ffmpeg must find nothing to complain about.
249 let out_err = ec_testkit::ffmpeg()
250 .args(["-v", "error", "-i"])
251 .arg(&out)
252 .args(["-f", "null", "-"])
253 .output()
254 .expect("run ffmpeg");
255 assert!(
256 out_err.stderr.is_empty(),
257 "ffmpeg complained: {}",
258 String::from_utf8_lossy(&out_err.stderr)
259 );
260}