diff --git a/crates/ec-flac/tests/level_depth_parity.rs b/crates/ec-flac/tests/level_depth_parity.rs deleted file mode 100644 index 4db4a706..00000000 --- a/crates/ec-flac/tests/level_depth_parity.rs +++ /dev/null @@ -1,330 +0,0 @@ -//! Parity with the flacenc export that ec-flac replaced. -//! -//! edith's old writer ran `flacenc::config::Encoder::default()` (4096-sample -//! fixed blocks, LPC to order 12, Rice partitions to order 6) on 16-bit input, -//! and `engine::flac_write` still asks for 16 bits. The 24-bit path is reachable -//! through the writer, so it is covered too. -//! -//! For every ec-flac level in [`levels`] and every case in [`CASES`], a -//! sine-plus-noise signal generated by ffmpeg (2.0 and 5.1) goes through -//! `ec_flac::encode` and is checked three ways: -//! -//! (a) ffmpeg decodes our stream back to the input PCM byte for byte; -//! (b) STREAMINFO carries the right rate, channels, bit depth and length, and -//! the MD5 of the input PCM (the MD5 is computed by `md5sum`, not by us); -//! (c) our size is at most [`MARGIN`] times the size ffmpeg's own FLAC encoder -//! produces at the matching `-compression_level`. -//! -//! ec-flac has no compression-level enum. Its levels are [`EncoderConfig`] -//! presets, paired with the ffmpeg level they sit nearest to (see [`levels`]). -//! -//! Run the table: -//! cargo test -p ec-flac --release --test level_depth_parity -- --nocapture - -use std::fs; -use std::path::{Path, PathBuf}; -use std::process::Command; - -use ec_flac::decode::FlacReader; -use ec_flac::encode::{EncoderConfig, encode}; - -/// Largest accepted ratio of our size to ffmpeg's size at the matching level. -const MARGIN: f64 = 1.05; - -/// Seconds of signal per case. -const SECONDS: u32 = 5; - -/// (label, ec-flac settings, matching ffmpeg `-compression_level`). -fn levels() -> Vec<(&'static str, EncoderConfig, u8)> { - vec![ - ( - "ec L0 fixed", - EncoderConfig { - max_lpc_order: 0, - max_partition_order: 3, - ..EncoderConfig::default() - }, - 0, - ), - ("ec default (edith)", EncoderConfig::default(), 5), - ( - "ec L8 max", - EncoderConfig { - max_lpc_order: 32, - max_partition_order: 6, - ..EncoderConfig::default() - }, - 8, - ), - ] -} - -struct Case { - name: &'static str, - layout: &'static str, - channels: usize, - rate: u32, - bits: u32, -} - -const CASES: [Case; 4] = [ - Case { - name: "16-bit 2.0 44.1k", - layout: "stereo", - channels: 2, - rate: 44100, - bits: 16, - }, - Case { - name: "16-bit 5.1 48k", - layout: "5.1", - channels: 6, - rate: 48000, - bits: 16, - }, - Case { - name: "24-bit 2.0 48k", - layout: "stereo", - channels: 2, - rate: 48000, - bits: 24, - }, - Case { - name: "24-bit 5.1 48k", - layout: "5.1", - channels: 6, - rate: 48000, - bits: 24, - }, -]; - -fn ffmpeg(args: &[&str]) { - let status = ec_testkit::ffmpeg() - .args(["-hide_banner", "-loglevel", "error", "-y"]) - .args(args) - .status() - .expect("run ffmpeg (is it installed?)"); - assert!(status.success(), "ffmpeg {args:?} failed"); -} - -fn ffprobe_stream(path: &Path) -> (u32, u32, u32) { - let out = ec_testkit::ffprobe() - .args([ - "-v", - "error", - "-select_streams", - "a:0", - "-show_entries", - "stream=sample_rate,channels,bits_per_raw_sample", - "-of", - "csv=p=0", - ]) - .arg(path) - .output() - .expect("run ffprobe"); - assert!(out.status.success(), "ffprobe failed on {}", path.display()); - let text = String::from_utf8(out.stdout).expect("ffprobe utf8"); - let fields: Vec = text - .trim() - .split(',') - .map(|f| f.parse().expect("ffprobe numeric field")) - .collect(); - // csv order: sample_rate, channels, bits_per_raw_sample - (fields[0], fields[1], fields[2]) -} - -fn md5_hex(path: &Path) -> String { - let out = Command::new("md5sum") - .arg(path) - .output() - .expect("run md5sum"); - assert!(out.status.success(), "md5sum failed"); - String::from_utf8_lossy(&out.stdout) - .split_whitespace() - .next() - .expect("md5sum digest") - .to_string() -} - -fn fmt_for(bits: u32) -> &'static str { - match bits { - 16 => "s16le", - 24 => "s24le", - _ => panic!("unsupported bit depth {bits}"), - } -} - -/// Sine plus noise, one sine per channel, generated by ffmpeg as raw PCM. -fn generate(dir: &Path, c: &Case) -> PathBuf { - let exprs: Vec = (0..c.channels) - .map(|i| { - let f = 220.0 * (i as f64 + 1.0); - format!("0.4*sin(2*PI*{f}*t)+0.08*(random({i})*2-1)") - }) - .collect(); - let src = format!( - "aevalsrc=exprs={}:s={}:d={}:c={}", - exprs.join("|"), - c.rate, - SECONDS, - c.layout - ); - let path = dir.join(format!("in-{}-{}-{}.raw", c.channels, c.bits, c.rate)); - ffmpeg(&[ - "-f", - "lavfi", - "-i", - &src, - "-f", - fmt_for(c.bits), - path.to_str().unwrap(), - ]); - path -} - -/// Little-endian signed PCM bytes to sign-extended samples. -fn to_samples(pcm: &[u8], bits: u32) -> Vec { - match bits { - 16 => pcm - .as_chunks::<2>() - .0 - .iter() - .map(|b| i16::from_le_bytes(*b) as i32) - .collect(), - 24 => pcm - .as_chunks::<3>() - .0 - .iter() - .map(|b| (((b[0] as i32) | ((b[1] as i32) << 8) | ((b[2] as i32) << 16)) << 8) >> 8) - .collect(), - _ => panic!("unsupported bit depth {bits}"), - } -} - -fn ffmpeg_reference_size(raw: &Path, c: &Case, level: u8, out: &Path) -> u64 { - ffmpeg(&[ - "-f", - fmt_for(c.bits), - "-ar", - &c.rate.to_string(), - "-ac", - &c.channels.to_string(), - "-i", - raw.to_str().unwrap(), - "-c:a", - "flac", - "-compression_level", - &level.to_string(), - out.to_str().unwrap(), - ]); - fs::metadata(out).expect("reference size").len() -} - -#[test] -fn level_and_depth_parity_with_ffmpeg_flac() { - let dir = std::env::temp_dir().join(format!("ec-flac-parity-{}", std::process::id())); - fs::create_dir_all(&dir).expect("create work dir"); - - println!(); - println!( - "| case | ec-flac level | ec-flac bytes | ffmpeg -compression_level | ffmpeg bytes | ratio | verdict |" - ); - println!("|---|---|---|---|---|---|---|"); - - let mut failures: Vec = Vec::new(); - - for c in &CASES { - let raw = generate(&dir, c); - let pcm = fs::read(&raw).expect("read generated pcm"); - let samples = to_samples(&pcm, c.bits); - let frames = (samples.len() / c.channels) as u64; - let md5_expected = md5_hex(&raw); - - for (label, config, ff_level) in levels() { - let tag = format!("{}-{}", c.bits, c.channels); - let flac_path = dir.join(format!("ours-{tag}-{ff_level}.flac")); - let back_path = dir.join(format!("back-{tag}-{ff_level}.raw")); - let ref_path = dir.join(format!("ref-{tag}-{ff_level}.flac")); - - // Encode. - let stream = encode(&config, &samples, c.channels, c.bits, c.rate) - .unwrap_or_else(|e| panic!("encode {} {label}: {e:?}", c.name)); - fs::write(&flac_path, &stream).expect("write our flac"); - let our_size = stream.len() as u64; - - // (b) STREAMINFO, read by our own parser. - let reader = FlacReader::new(&stream).expect("open our stream"); - let info = reader.stream_info().expect("streaminfo").clone(); - let mut bad = Vec::new(); - if info.sample_rate != c.rate { - bad.push(format!("rate {} != {}", info.sample_rate, c.rate)); - } - if usize::from(info.channels) != c.channels { - bad.push(format!("channels {} != {}", info.channels, c.channels)); - } - if u32::from(info.bits_per_sample) != c.bits { - bad.push(format!("bits {} != {}", info.bits_per_sample, c.bits)); - } - if info.total_samples != frames { - bad.push(format!("total_samples {} != {frames}", info.total_samples)); - } - if info.md5.iter().all(|&b| b == 0) { - bad.push("md5 is zero".to_string()); - } - let md5_stream: String = info.md5.iter().map(|b| format!("{b:02x}")).collect(); - if md5_stream != md5_expected { - bad.push(format!("md5 {md5_stream} != input {md5_expected}")); - } - - // (b) cross-checked by ffprobe on the file itself. - let (p_rate, p_ch, p_bits) = ffprobe_stream(&flac_path); - if (p_rate, p_ch as usize, p_bits) != (c.rate, c.channels, c.bits) { - bad.push(format!( - "ffprobe rate/ch/bits {p_rate}/{p_ch}/{p_bits} != {}/{}/{}", - c.rate, c.channels, c.bits - )); - } - - // (a) ffmpeg decodes our stream back to the input, byte for byte. - ffmpeg(&[ - "-i", - flac_path.to_str().unwrap(), - "-f", - fmt_for(c.bits), - back_path.to_str().unwrap(), - ]); - let back = fs::read(&back_path).expect("read decoded pcm"); - if back != pcm { - let first = back.iter().zip(&pcm).position(|(a, b)| a != b); - bad.push(format!( - "not bit-exact: lengths {} vs {}, first diff at byte {first:?}", - back.len(), - pcm.len() - )); - } - - // (c) size against ffmpeg's FLAC encoder at the matching level. - let ref_size = ffmpeg_reference_size(&raw, c, ff_level, &ref_path); - let ratio = our_size as f64 / ref_size as f64; - if ratio > MARGIN { - bad.push(format!("size ratio {ratio:.4} > {MARGIN}")); - } - - let verdict = if bad.is_empty() { "PASS" } else { "FAIL" }; - println!( - "| {} | {} | {} | {} | {} | {:.4} | {} |", - c.name, label, our_size, ff_level, ref_size, ratio, verdict - ); - for b in bad { - failures.push(format!("{} / {label}: {b}", c.name)); - } - } - } - - let _ = fs::remove_dir_all(&dir); - assert!( - failures.is_empty(), - "parity failures:\n{}", - failures.join("\n") - ); -}