//! Our encoder measured the only way a lossy one can be: encode, decode the //! result with ffmpeg, correlate against the samples that went in. use std::path::{Path, PathBuf}; use ec_mp3::{Mp3Encoder, Mp3EncoderConfig}; fn workdir(test: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("ec-mp3-{}-{test}", std::process::id())); std::fs::create_dir_all(&dir).expect("create work dir"); dir } /// Reads a WAV fixture as interleaved f32 plus its rate and channel count. fn read_wav(path: &Path) -> (Vec, u32, usize) { let out = ec_testkit::ffmpeg() .args(["-v", "error", "-i"]) .arg(path) .args(["-f", "f32le", "-"]) .output() .expect("run ffmpeg"); assert!( out.status.success(), "ffmpeg could not read {}", path.display() ); let samples = out .stdout .as_chunks::<4>() .0 .iter() .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) .collect(); let probe = ec_testkit::ffprobe() .args([ "-v", "error", "-select_streams", "a:0", "-show_entries", "stream=channels,sample_rate", "-of", "default=noprint_wrappers=1", ]) .arg(path) .output() .expect("run ffprobe"); let text = String::from_utf8_lossy(&probe.stdout); let field = |key: &str| { text.lines() .find_map(|l| l.strip_prefix(key)?.strip_prefix('=')) .and_then(|v| v.trim().parse::().ok()) }; ( samples, field("sample_rate").expect("sample rate"), field("channels").expect("channels") as usize, ) } fn correlation(a: &[f32], b: &[f32]) -> f64 { let n = a.len().min(b.len()); let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64); for i in 0..n { let (x, y) = (a[i] as f64, b[i] as f64); ab += x * y; aa += x * x; bb += y * y; } if aa == 0.0 || bb == 0.0 { return 0.0; } ab / (aa * bb).sqrt() } fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec { let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { bitrate_kbps: kbps, vbr_quality: None, }); encoder .push_pcm_f32(pcm, channels as u16, rate) .expect("encoder accepts the fixture"); encoder.finish(); let mut out = Vec::new(); while let Ok(frame) = encoder.next_packet() { out.extend_from_slice(&frame); } out } /// CBR-192 of the stereo 48 kHz tone fixture decodes at least as well as it /// did before the masking model was put in the quantiser's units (9ac19d6: /// corr 0.999999, RMS error 0.020% of the signal). A byte pin stood here /// while VBR landed; the psychoacoustic change legitimately moves the bytes, /// so the gate is the quality those bytes carried. #[test] fn cbr_quality_holds_its_floor() { let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav"); let (pcm, rate, channels) = read_wav(&path); let bytes = encode(&pcm, rate, channels, 192); let file = workdir("cbr").join("cbr192.mp3"); std::fs::write(&file, &bytes).unwrap(); let decoded = decode(&file); assert_eq!(decoded.len(), pcm.len()); let corr = correlation(&decoded, &pcm); let (err, sig) = decoded .iter() .zip(&pcm) .fold((0.0f64, 0.0f64), |(e, s), (d, p)| { (e + f64::from(d - p).powi(2), s + f64::from(*p).powi(2)) }); let rms = (err / sig).sqrt(); println!("cbr192 corr={corr:.6} rms={:.4}%", rms * 100.0); assert!(corr >= 0.999_99, "corr {corr:.6}"); assert!(rms <= 0.000_25, "rms {:.4}%", rms * 100.0); } fn decode(file: &Path) -> Vec { let out = ec_testkit::ffmpeg() .args(["-v", "warning", "-i"]) .arg(file) .args(["-f", "f32le", "-"]) .output() .expect("run ffmpeg"); assert!( out.stderr.is_empty(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr) ); out.stdout .as_chunks::<4>() .0 .iter() .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) .collect() }