forge
Explore
Log in

Don't you dare go Hollow

U9: ec-flac delete level_depth_parity test (unit scope; its level and depth matrix is not covered by encode_matrix)

Browse files at this commit

73ae26042f1f92cad384f01a064a14db8082d5c8Ahmet Kaan GümüşParent: 5d133f9
crates/ec-flac/tests/level_depth_parity.rsdeleted+0 -330
@@ -1,330 +0,0 @@
1-//! Parity with the flacenc export that ec-flac replaced.
2-//!
3-//! edith's old writer ran `flacenc::config::Encoder::default()` (4096-sample
4-//! fixed blocks, LPC to order 12, Rice partitions to order 6) on 16-bit input,
5-//! and `engine::flac_write` still asks for 16 bits. The 24-bit path is reachable
6-//! through the writer, so it is covered too.
7-//!
8-//! For every ec-flac level in [`levels`] and every case in [`CASES`], a
9-//! sine-plus-noise signal generated by ffmpeg (2.0 and 5.1) goes through
10-//! `ec_flac::encode` and is checked three ways:
11-//!
12-//! (a) ffmpeg decodes our stream back to the input PCM byte for byte;
13-//! (b) STREAMINFO carries the right rate, channels, bit depth and length, and
14-//! the MD5 of the input PCM (the MD5 is computed by `md5sum`, not by us);
15-//! (c) our size is at most [`MARGIN`] times the size ffmpeg's own FLAC encoder
16-//! produces at the matching `-compression_level`.
17-//!
18-//! ec-flac has no compression-level enum. Its levels are [`EncoderConfig`]
19-//! presets, paired with the ffmpeg level they sit nearest to (see [`levels`]).
20-//!
21-//! Run the table:
22-//! cargo test -p ec-flac --release --test level_depth_parity -- --nocapture
23-
24-use std::fs;
25-use std::path::{Path, PathBuf};
26-use std::process::Command;
27-
28-use ec_flac::decode::FlacReader;
29-use ec_flac::encode::{EncoderConfig, encode};
30-
31-/// Largest accepted ratio of our size to ffmpeg's size at the matching level.
32-const MARGIN: f64 = 1.05;
33-
34-/// Seconds of signal per case.
35-const SECONDS: u32 = 5;
36-
37-/// (label, ec-flac settings, matching ffmpeg `-compression_level`).
38-fn levels() -> Vec<(&'static str, EncoderConfig, u8)> {
39- vec![
40- (
41- "ec L0 fixed",
42- EncoderConfig {
43- max_lpc_order: 0,
44- max_partition_order: 3,
45- ..EncoderConfig::default()
46- },
47- 0,
48- ),
49- ("ec default (edith)", EncoderConfig::default(), 5),
50- (
51- "ec L8 max",
52- EncoderConfig {
53- max_lpc_order: 32,
54- max_partition_order: 6,
55- ..EncoderConfig::default()
56- },
57- 8,
58- ),
59- ]
60-}
61-
62-struct Case {
63- name: &'static str,
64- layout: &'static str,
65- channels: usize,
66- rate: u32,
67- bits: u32,
68-}
69-
70-const CASES: [Case; 4] = [
71- Case {
72- name: "16-bit 2.0 44.1k",
73- layout: "stereo",
74- channels: 2,
75- rate: 44100,
76- bits: 16,
77- },
78- Case {
79- name: "16-bit 5.1 48k",
80- layout: "5.1",
81- channels: 6,
82- rate: 48000,
83- bits: 16,
84- },
85- Case {
86- name: "24-bit 2.0 48k",
87- layout: "stereo",
88- channels: 2,
89- rate: 48000,
90- bits: 24,
91- },
92- Case {
93- name: "24-bit 5.1 48k",
94- layout: "5.1",
95- channels: 6,
96- rate: 48000,
97- bits: 24,
98- },
99-];
100-
101-fn ffmpeg(args: &[&str]) {
102- let status = ec_testkit::ffmpeg()
103- .args(["-hide_banner", "-loglevel", "error", "-y"])
104- .args(args)
105- .status()
106- .expect("run ffmpeg (is it installed?)");
107- assert!(status.success(), "ffmpeg {args:?} failed");
108-}
109-
110-fn ffprobe_stream(path: &Path) -> (u32, u32, u32) {
111- let out = ec_testkit::ffprobe()
112- .args([
113- "-v",
114- "error",
115- "-select_streams",
116- "a:0",
117- "-show_entries",
118- "stream=sample_rate,channels,bits_per_raw_sample",
119- "-of",
120- "csv=p=0",
121- ])
122- .arg(path)
123- .output()
124- .expect("run ffprobe");
125- assert!(out.status.success(), "ffprobe failed on {}", path.display());
126- let text = String::from_utf8(out.stdout).expect("ffprobe utf8");
127- let fields: Vec<u32> = text
128- .trim()
129- .split(',')
130- .map(|f| f.parse().expect("ffprobe numeric field"))
131- .collect();
132- // csv order: sample_rate, channels, bits_per_raw_sample
133- (fields[0], fields[1], fields[2])
134-}
135-
136-fn md5_hex(path: &Path) -> String {
137- let out = Command::new("md5sum")
138- .arg(path)
139- .output()
140- .expect("run md5sum");
141- assert!(out.status.success(), "md5sum failed");
142- String::from_utf8_lossy(&out.stdout)
143- .split_whitespace()
144- .next()
145- .expect("md5sum digest")
146- .to_string()
147-}
148-
149-fn fmt_for(bits: u32) -> &'static str {
150- match bits {
151- 16 => "s16le",
152- 24 => "s24le",
153- _ => panic!("unsupported bit depth {bits}"),
154- }
155-}
156-
157-/// Sine plus noise, one sine per channel, generated by ffmpeg as raw PCM.
158-fn generate(dir: &Path, c: &Case) -> PathBuf {
159- let exprs: Vec<String> = (0..c.channels)
160- .map(|i| {
161- let f = 220.0 * (i as f64 + 1.0);
162- format!("0.4*sin(2*PI*{f}*t)+0.08*(random({i})*2-1)")
163- })
164- .collect();
165- let src = format!(
166- "aevalsrc=exprs={}:s={}:d={}:c={}",
167- exprs.join("|"),
168- c.rate,
169- SECONDS,
170- c.layout
171- );
172- let path = dir.join(format!("in-{}-{}-{}.raw", c.channels, c.bits, c.rate));
173- ffmpeg(&[
174- "-f",
175- "lavfi",
176- "-i",
177- &src,
178- "-f",
179- fmt_for(c.bits),
180- path.to_str().unwrap(),
181- ]);
182- path
183-}
184-
185-/// Little-endian signed PCM bytes to sign-extended samples.
186-fn to_samples(pcm: &[u8], bits: u32) -> Vec<i32> {
187- match bits {
188- 16 => pcm
189- .as_chunks::<2>()
190- .0
191- .iter()
192- .map(|b| i16::from_le_bytes(*b) as i32)
193- .collect(),
194- 24 => pcm
195- .as_chunks::<3>()
196- .0
197- .iter()
198- .map(|b| (((b[0] as i32) | ((b[1] as i32) << 8) | ((b[2] as i32) << 16)) << 8) >> 8)
199- .collect(),
200- _ => panic!("unsupported bit depth {bits}"),
201- }
202-}
203-
204-fn ffmpeg_reference_size(raw: &Path, c: &Case, level: u8, out: &Path) -> u64 {
205- ffmpeg(&[
206- "-f",
207- fmt_for(c.bits),
208- "-ar",
209- &c.rate.to_string(),
210- "-ac",
211- &c.channels.to_string(),
212- "-i",
213- raw.to_str().unwrap(),
214- "-c:a",
215- "flac",
216- "-compression_level",
217- &level.to_string(),
218- out.to_str().unwrap(),
219- ]);
220- fs::metadata(out).expect("reference size").len()
221-}
222-
223-#[test]
224-fn level_and_depth_parity_with_ffmpeg_flac() {
225- let dir = std::env::temp_dir().join(format!("ec-flac-parity-{}", std::process::id()));
226- fs::create_dir_all(&dir).expect("create work dir");
227-
228- println!();
229- println!(
230- "| case | ec-flac level | ec-flac bytes | ffmpeg -compression_level | ffmpeg bytes | ratio | verdict |"
231- );
232- println!("|---|---|---|---|---|---|---|");
233-
234- let mut failures: Vec<String> = Vec::new();
235-
236- for c in &CASES {
237- let raw = generate(&dir, c);
238- let pcm = fs::read(&raw).expect("read generated pcm");
239- let samples = to_samples(&pcm, c.bits);
240- let frames = (samples.len() / c.channels) as u64;
241- let md5_expected = md5_hex(&raw);
242-
243- for (label, config, ff_level) in levels() {
244- let tag = format!("{}-{}", c.bits, c.channels);
245- let flac_path = dir.join(format!("ours-{tag}-{ff_level}.flac"));
246- let back_path = dir.join(format!("back-{tag}-{ff_level}.raw"));
247- let ref_path = dir.join(format!("ref-{tag}-{ff_level}.flac"));
248-
249- // Encode.
250- let stream = encode(&config, &samples, c.channels, c.bits, c.rate)
251- .unwrap_or_else(|e| panic!("encode {} {label}: {e:?}", c.name));
252- fs::write(&flac_path, &stream).expect("write our flac");
253- let our_size = stream.len() as u64;
254-
255- // (b) STREAMINFO, read by our own parser.
256- let reader = FlacReader::new(&stream).expect("open our stream");
257- let info = reader.stream_info().expect("streaminfo").clone();
258- let mut bad = Vec::new();
259- if info.sample_rate != c.rate {
260- bad.push(format!("rate {} != {}", info.sample_rate, c.rate));
261- }
262- if usize::from(info.channels) != c.channels {
263- bad.push(format!("channels {} != {}", info.channels, c.channels));
264- }
265- if u32::from(info.bits_per_sample) != c.bits {
266- bad.push(format!("bits {} != {}", info.bits_per_sample, c.bits));
267- }
268- if info.total_samples != frames {
269- bad.push(format!("total_samples {} != {frames}", info.total_samples));
270- }
271- if info.md5.iter().all(|&b| b == 0) {
272- bad.push("md5 is zero".to_string());
273- }
274- let md5_stream: String = info.md5.iter().map(|b| format!("{b:02x}")).collect();
275- if md5_stream != md5_expected {
276- bad.push(format!("md5 {md5_stream} != input {md5_expected}"));
277- }
278-
279- // (b) cross-checked by ffprobe on the file itself.
280- let (p_rate, p_ch, p_bits) = ffprobe_stream(&flac_path);
281- if (p_rate, p_ch as usize, p_bits) != (c.rate, c.channels, c.bits) {
282- bad.push(format!(
283- "ffprobe rate/ch/bits {p_rate}/{p_ch}/{p_bits} != {}/{}/{}",
284- c.rate, c.channels, c.bits
285- ));
286- }
287-
288- // (a) ffmpeg decodes our stream back to the input, byte for byte.
289- ffmpeg(&[
290- "-i",
291- flac_path.to_str().unwrap(),
292- "-f",
293- fmt_for(c.bits),
294- back_path.to_str().unwrap(),
295- ]);
296- let back = fs::read(&back_path).expect("read decoded pcm");
297- if back != pcm {
298- let first = back.iter().zip(&pcm).position(|(a, b)| a != b);
299- bad.push(format!(
300- "not bit-exact: lengths {} vs {}, first diff at byte {first:?}",
301- back.len(),
302- pcm.len()
303- ));
304- }
305-
306- // (c) size against ffmpeg's FLAC encoder at the matching level.
307- let ref_size = ffmpeg_reference_size(&raw, c, ff_level, &ref_path);
308- let ratio = our_size as f64 / ref_size as f64;
309- if ratio > MARGIN {
310- bad.push(format!("size ratio {ratio:.4} > {MARGIN}"));
311- }
312-
313- let verdict = if bad.is_empty() { "PASS" } else { "FAIL" };
314- println!(
315- "| {} | {} | {} | {} | {} | {:.4} | {} |",
316- c.name, label, our_size, ff_level, ref_size, ratio, verdict
317- );
318- for b in bad {
319- failures.push(format!("{} / {label}: {b}", c.name));
320- }
321- }
322- }
323-
324- let _ = fs::remove_dir_all(&dir);
325- assert!(
326- failures.is_empty(),
327- "parity failures:\n{}",
328- failures.join("\n")
329- );
330-}