forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.4 MiBcdccbc2Tahinli8 hours ago4263 commits

encode_matrix.rs138 lines, 4.1 KiBHistoryRawDownload
1//! Our encoder measured the only way a lossy one can be: encode, decode the
2//! result with ffmpeg, correlate against the samples that went in.
3
4use std::path::{Path, PathBuf};
5
6use ec_mp3::{Mp3Encoder, Mp3EncoderConfig};
7
8
9fn workdir(test: &str) -> PathBuf {
10 let dir = std::env::temp_dir().join(format!("ec-mp3-{}-{test}", std::process::id()));
11 std::fs::create_dir_all(&dir).expect("create work dir");
12 dir
13}
14
15/// Reads a WAV fixture as interleaved f32 plus its rate and channel count.
16fn read_wav(path: &Path) -> (Vec<f32>, u32, usize) {
17 let out = ec_testkit::ffmpeg()
18 .args(["-v", "error", "-i"])
19 .arg(path)
20 .args(["-f", "f32le", "-"])
21 .output()
22 .expect("run ffmpeg");
23 assert!(
24 out.status.success(),
25 "ffmpeg could not read {}",
26 path.display()
27 );
28 let samples = out
29 .stdout
30 .as_chunks::<4>()
31 .0
32 .iter()
33 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
34 .collect();
35 let probe = ec_testkit::ffprobe()
36 .args([
37 "-v",
38 "error",
39 "-select_streams",
40 "a:0",
41 "-show_entries",
42 "stream=channels,sample_rate",
43 "-of",
44 "default=noprint_wrappers=1",
45 ])
46 .arg(path)
47 .output()
48 .expect("run ffprobe");
49 let text = String::from_utf8_lossy(&probe.stdout);
50 let field = |key: &str| {
51 text.lines()
52 .find_map(|l| l.strip_prefix(key)?.strip_prefix('='))
53 .and_then(|v| v.trim().parse::<u32>().ok())
54 };
55 (
56 samples,
57 field("sample_rate").expect("sample rate"),
58 field("channels").expect("channels") as usize,
59 )
60}
61
62fn correlation(a: &[f32], b: &[f32]) -> f64 {
63 let n = a.len().min(b.len());
64 let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64);
65 for i in 0..n {
66 let (x, y) = (a[i] as f64, b[i] as f64);
67 ab += x * y;
68 aa += x * x;
69 bb += y * y;
70 }
71 if aa == 0.0 || bb == 0.0 {
72 return 0.0;
73 }
74 ab / (aa * bb).sqrt()
75}
76
77fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> {
78 let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
79 bitrate_kbps: kbps,
80 vbr_quality: None,
81 });
82 encoder
83 .push_pcm_f32(pcm, channels as u16, rate)
84 .expect("encoder accepts the fixture");
85 encoder.finish();
86 let mut out = Vec::new();
87 while let Ok(frame) = encoder.next_packet() {
88 out.extend_from_slice(&frame);
89 }
90 out
91}
92
93/// CBR-192 of the stereo 48 kHz tone fixture decodes at least as well as it
94/// did before the masking model was put in the quantiser's units (9ac19d6:
95/// corr 0.999999, RMS error 0.020% of the signal). A byte pin stood here
96/// while VBR landed; the psychoacoustic change legitimately moves the bytes,
97/// so the gate is the quality those bytes carried.
98#[test]
99fn cbr_quality_holds_its_floor() {
100 let path = ec_testkit::fixture("audio/wav16-stereo-48000.wav");
101 let (pcm, rate, channels) = read_wav(&path);
102 let bytes = encode(&pcm, rate, channels, 192);
103 let file = workdir("cbr").join("cbr192.mp3");
104 std::fs::write(&file, &bytes).unwrap();
105 let decoded = decode(&file);
106 assert_eq!(decoded.len(), pcm.len());
107 let corr = correlation(&decoded, &pcm);
108 let (err, sig) = decoded
109 .iter()
110 .zip(&pcm)
111 .fold((0.0f64, 0.0f64), |(e, s), (d, p)| {
112 (e + f64::from(d - p).powi(2), s + f64::from(*p).powi(2))
113 });
114 let rms = (err / sig).sqrt();
115 println!("cbr192 corr={corr:.6} rms={:.4}%", rms * 100.0);
116 assert!(corr >= 0.999_99, "corr {corr:.6}");
117 assert!(rms <= 0.000_25, "rms {:.4}%", rms * 100.0);
118}
119
120fn decode(file: &Path) -> Vec<f32> {
121 let out = ec_testkit::ffmpeg()
122 .args(["-v", "warning", "-i"])
123 .arg(file)
124 .args(["-f", "f32le", "-"])
125 .output()
126 .expect("run ffmpeg");
127 assert!(
128 out.stderr.is_empty(),
129 "ffmpeg: {}",
130 String::from_utf8_lossy(&out.stderr)
131 );
132 out.stdout
133 .as_chunks::<4>()
134 .0
135 .iter()
136 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
137 .collect()
138}