forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

flac_export.rs213 lines, 7.3 KiBHistoryRawDownload
1//! The FLAC writer, checked against the tools that did not write it: a stream
2//! written through `engine::flac_write` must decode, under ffmpeg, to exactly
3//! the samples that went in, and its `STREAMINFO` must describe that same
4//! audio (rate, channels, bit depth, length and the MD5 of the PCM).
5//!
6//! Three shapes are covered: 16-bit stereo (what the export writes), 24-bit
7//! stereo and 24-bit 5.1 (what the writer takes but the export never asks for).
8//! The signal is synthetic and deterministic, with full-scale extremes in it,
9//! so a clipped or wrapped sample would show.
10//!
11//! Needs the `ffmpeg`, `ffprobe` and `md5sum` command-line tools. `flac -t` is
12//! not used: it is not installed on the machines this runs on, and ffmpeg's own
13//! decoder does not check the MD5, so the MD5 is compared here directly.
14
15use std::io::Write;
16use std::path::Path;
17use std::process::{Command, Stdio};
18
19use engine::flac_write;
20use engine::scratch::Scratch;
21
22/// Deterministic test signal: a per-channel tone plus LCG noise, clamped to the
23/// bit depth, with the two extremes planted at the start.
24fn signal(frames: usize, channels: usize, bits: u32) -> Vec<i32> {
25 let max = (1i64 << (bits - 1)) - 1;
26 let min = -(1i64 << (bits - 1));
27 let mut seed: u32 = 0x9E37_79B9;
28 let mut out = Vec::with_capacity(frames * channels);
29 for f in 0..frames {
30 for c in 0..channels {
31 seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
32 let noise = f64::from(seed >> 8) / f64::from(1u32 << 24) * 2.0 - 1.0;
33 let tone = (f as f64 * (110.0 + 37.0 * c as f64) * std::f64::consts::TAU / 48_000.0)
34 .sin();
35 let v = ((tone * 0.7 + noise * 0.05) * max as f64).round() as i64;
36 out.push(v.clamp(min, max) as i32);
37 }
38 }
39 if let Some(first) = out.first_mut() {
40 *first = max as i32;
41 }
42 if let Some(second) = out.get_mut(channels) {
43 *second = min as i32;
44 }
45 out
46}
47
48/// Little-endian bytes of each sample in `bits / 8` bytes, which is the PCM the
49/// FLAC MD5 is defined over.
50fn pcm_bytes(samples: &[i32], bits: u32) -> Vec<u8> {
51 let width = (bits / 8) as usize;
52 samples
53 .iter()
54 .flat_map(|s| s.to_le_bytes().into_iter().take(width))
55 .collect()
56}
57
58fn run(program: &str, args: &[&str]) -> std::process::Output {
59 Command::new(program)
60 .args(args)
61 .output()
62 .unwrap_or_else(|e| panic!("cannot run {program}: {e}"))
63}
64
65/// The MD5 of `data`, as `md5sum` prints it.
66fn md5_hex(data: &[u8]) -> String {
67 let mut child = Command::new("md5sum")
68 .stdin(Stdio::piped())
69 .stdout(Stdio::piped())
70 .spawn()
71 .expect("md5sum");
72 child
73 .stdin
74 .take()
75 .expect("md5sum stdin")
76 .write_all(data)
77 .expect("feed md5sum");
78 let out = child.wait_with_output().expect("md5sum output");
79 String::from_utf8_lossy(&out.stdout)
80 .split_whitespace()
81 .next()
82 .expect("md5sum digest")
83 .to_string()
84}
85
86/// `(sample_rate, channels, bits_per_raw_sample)` as ffprobe reports them.
87fn probe(path: &Path) -> (u32, usize, u32) {
88 let out = run(
89 "ffprobe",
90 &[
91 "-v",
92 "error",
93 "-select_streams",
94 "a:0",
95 "-show_entries",
96 "stream=codec_name,sample_rate,channels,bits_per_raw_sample",
97 "-of",
98 "default=nw=1",
99 path.to_str().expect("utf-8 path"),
100 ],
101 );
102 assert!(
103 out.status.success() && out.stderr.is_empty(),
104 "ffprobe on {}: {}",
105 path.display(),
106 String::from_utf8_lossy(&out.stderr)
107 );
108 let text = String::from_utf8_lossy(&out.stdout);
109 let field = |key: &str| -> String {
110 text.lines()
111 .find_map(|l| l.strip_prefix(&format!("{key}=")))
112 .unwrap_or_else(|| panic!("ffprobe reports no {key}: {text}"))
113 .to_string()
114 };
115 assert_eq!(field("codec_name"), "flac", "a FLAC stream");
116 (
117 field("sample_rate").parse().expect("rate"),
118 field("channels").parse().expect("channels"),
119 field("bits_per_raw_sample").parse().expect("bits"),
120 )
121}
122
123/// The `STREAMINFO` block, read by hand: the MD5 and the total sample count.
124fn streaminfo_md5_and_total(bytes: &[u8]) -> (String, u64) {
125 assert_eq!(&bytes[0..4], b"fLaC", "a FLAC stream, by its own magic");
126 assert_eq!(bytes[4] & 0x7F, 0, "the first metadata block is STREAMINFO");
127 let s = &bytes[8..42];
128 let total = (u64::from(s[13] & 0x0F) << 32)
129 | u64::from(u32::from_be_bytes([s[14], s[15], s[16], s[17]]));
130 let md5: String = s[18..34].iter().map(|b| format!("{b:02x}")).collect();
131 (md5, total)
132}
133
134/// ffmpeg's decode, as interleaved `i32`s (ffmpeg left-justifies every depth
135/// into 32 bits, so a 16-bit sample arrives as `sample << 16`).
136fn ffmpeg_decode(path: &Path) -> Vec<i32> {
137 let out = run(
138 "ffmpeg",
139 &[
140 "-v",
141 "error",
142 "-i",
143 path.to_str().expect("utf-8 path"),
144 "-f",
145 "s32le",
146 "-",
147 ],
148 );
149 assert!(
150 out.status.success() && out.stderr.is_empty(),
151 "ffmpeg decode of {}: {}",
152 path.display(),
153 String::from_utf8_lossy(&out.stderr)
154 );
155 out.stdout
156 .as_chunks::<4>()
157 .0
158 .iter()
159 .map(|b| i32::from_le_bytes(*b))
160 .collect()
161}
162
163fn check(name: &str, bits: u32, channels: usize, rate: u32, frames: usize) {
164 let input = signal(frames, channels, bits);
165 let out = Scratch::file(&format!("ve_flac_parity_{name}"), "flac");
166 flac_write::write(&out, &input, channels, bits, rate).expect("write the flac");
167
168 // ffprobe: the header says what was asked for.
169 let (got_rate, got_channels, got_bits) = probe(&out);
170 assert_eq!(got_rate, rate, "{name}: sample rate");
171 assert_eq!(got_channels, channels, "{name}: channel count");
172 assert_eq!(got_bits, bits, "{name}: bits_per_raw_sample");
173
174 // STREAMINFO: the MD5 is the one of the PCM that went in, and the length
175 // is the frame count.
176 let bytes = std::fs::read(&out).expect("read the flac back");
177 let (md5, total) = streaminfo_md5_and_total(&bytes);
178 assert_eq!(total, frames as u64, "{name}: total samples in STREAMINFO");
179 assert_eq!(
180 md5,
181 md5_hex(&pcm_bytes(&input, bits)),
182 "{name}: STREAMINFO MD5 is the MD5 of the input PCM"
183 );
184
185 // ffmpeg: every sample comes back, bit for bit, at the same position.
186 let decoded = ffmpeg_decode(&out);
187 let shift = 32 - bits;
188 let expected: Vec<i32> = input.iter().map(|s| s << shift).collect();
189 assert_eq!(decoded.len(), expected.len(), "{name}: decoded sample count");
190 let first_bad = decoded.iter().zip(&expected).position(|(a, b)| a != b);
191 assert_eq!(first_bad, None, "{name}: first mismatching sample index");
192
193 println!(
194 "{name}: {} bytes for {} bytes of PCM",
195 bytes.len(),
196 pcm_bytes(&input, bits).len()
197 );
198}
199
200#[test]
201fn flac_16_bit_stereo_decodes_to_the_same_samples() {
202 check("s16_stereo", 16, 2, 44_100, 22_050);
203}
204
205#[test]
206fn flac_24_bit_stereo_decodes_to_the_same_samples() {
207 check("s24_stereo", 24, 2, 48_000, 24_000);
208}
209
210#[test]
211fn flac_24_bit_51_decodes_to_the_same_samples() {
212 check("s24_51", 24, 6, 48_000, 24_000);
213}