forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

real_library_flac.rs240 lines, 8.3 KiBHistoryRawDownload
1//! The FLAC writer on the owner's own media: 60 seconds from the middle of
2//! each named track, written through `engine::flac_write` and decoded back by
3//! ffmpeg. The round trip must be exact, and `STREAMINFO` must describe the
4//! same audio (rate, channels, bit depth, length and the MD5 of the PCM).
5//!
6//! * `wav_pcm16`: the file's own 16-bit PCM.
7//! * `av1_opus_51`, `ac3_51_film`: the sound track decoded by ffmpeg at its
8//! native rate and channel count, written at 16 bits (what the export asks
9//! for) and at 24 bits (what the writer takes but the export never asks for).
10//!
11//! The same checks as `flac_export.rs` on synthetic signals: ffmpeg's decode
12//! of the written stream is compared sample for sample with the input, and the
13//! 24-bit input is decoded by ffmpeg as its 32-bit left-justified form.
14//!
15//! Named by `real_library.toml` (gitignored). Skips where a key is absent or
16//! ffmpeg / ffprobe are not installed.
17
18use crate::reallib;
19
20use std::path::Path;
21use std::process::Command;
22use std::time::Instant;
23
24use engine::flac_write;
25use engine::scratch::Scratch;
26use reallib::{ffprobe_streams, have, md5_hex};
27
28/// Seconds of each track that are encoded, taken from its middle.
29const WINDOW_SECONDS: f64 = 60.0;
30
31fn run_ok(cmd: &mut Command, what: &str) -> Vec<u8> {
32 let out = cmd
33 .output()
34 .unwrap_or_else(|e| panic!("cannot run {what}: {e}"));
35 assert!(
36 out.status.success() && out.stderr.is_empty(),
37 "{what}: {}",
38 String::from_utf8_lossy(&out.stderr)
39 );
40 out.stdout
41}
42
43/// `(sample_rate, channels, duration_seconds)` of the first audio stream.
44fn source_shape(path: &Path) -> (u32, usize, f64) {
45 let audio = ffprobe_streams(path)
46 .into_iter()
47 .find(|s| s.kind == "audio")
48 .expect("the file has an audio stream");
49 let duration = run_ok(
50 Command::new("ffprobe")
51 .args([
52 "-v",
53 "error",
54 "-show_entries",
55 "format=duration",
56 "-of",
57 "default=nw=1:nk=1",
58 ])
59 .arg(path),
60 "ffprobe duration",
61 );
62 let duration: f64 = String::from_utf8_lossy(&duration)
63 .trim()
64 .parse()
65 .expect("a duration");
66 (
67 audio.sample_rate.expect("sample rate"),
68 usize::from(audio.channels.expect("channel count")),
69 duration,
70 )
71}
72
73/// The first audio track over the 60 seconds from the middle of the file, as
74/// raw little-endian PCM in `fmt` (`s16le` or `s24le`), at the track's own rate
75/// and channel count.
76fn pcm_window(path: &Path, duration: f64, fmt: &str) -> Vec<u8> {
77 let start = (duration / 2.0 - WINDOW_SECONDS / 2.0).max(0.0);
78 run_ok(
79 Command::new("ffmpeg")
80 .args(["-v", "error", "-nostdin", "-ss"])
81 .arg(format!("{start}"))
82 .arg("-i")
83 .arg(path)
84 .args(["-map", "0:a:0", "-vn", "-t"])
85 .arg(format!("{WINDOW_SECONDS}"))
86 .args(["-f", fmt, "-"]),
87 "ffmpeg pcm",
88 )
89}
90
91/// Little-endian PCM bytes to interleaved samples, `bits` wide, sign-extended.
92fn samples_of(bytes: &[u8], bits: u32) -> Vec<i32> {
93 match bits {
94 16 => bytes
95 .as_chunks::<2>()
96 .0
97 .iter()
98 .map(|b| i32::from(i16::from_le_bytes(*b)))
99 .collect(),
100 24 => bytes
101 .as_chunks::<3>()
102 .0
103 .iter()
104 .map(|b| (i32::from(b[0]) | i32::from(b[1]) << 8 | i32::from(b[2]) << 16) << 8 >> 8)
105 .collect(),
106 _ => unreachable!("only 16 and 24 bits are used here"),
107 }
108}
109
110/// Little-endian bytes of each sample in `bits / 8` bytes: the PCM the FLAC
111/// MD5 is defined over.
112fn pcm_bytes(samples: &[i32], bits: u32) -> Vec<u8> {
113 let width = (bits / 8) as usize;
114 samples
115 .iter()
116 .flat_map(|s| s.to_le_bytes().into_iter().take(width))
117 .collect()
118}
119
120/// The `STREAMINFO` block read by hand: `(rate, channels, bits, total, md5)`.
121fn streaminfo(bytes: &[u8]) -> (u32, usize, u32, u64, String) {
122 assert_eq!(&bytes[0..4], b"fLaC", "a FLAC stream, by its own magic");
123 assert_eq!(bytes[4] & 0x7F, 0, "the first metadata block is STREAMINFO");
124 let s = &bytes[8..42];
125 let rate = (u32::from(s[10]) << 12) | (u32::from(s[11]) << 4) | (u32::from(s[12]) >> 4);
126 let channels = usize::from((s[12] >> 1) & 0x07) + 1;
127 let bits = (u32::from(s[12] & 0x01) << 4 | u32::from(s[13] >> 4)) + 1;
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 (rate, channels, bits, total, md5)
132}
133
134/// ffmpeg's decode of `path`, as interleaved `i32`s, left-justified to 32 bits.
135fn ffmpeg_decode(path: &Path) -> Vec<i32> {
136 let bytes = run_ok(
137 Command::new("ffmpeg")
138 .args(["-v", "error", "-i"])
139 .arg(path)
140 .args(["-f", "s32le", "-"]),
141 "ffmpeg decode of the written flac",
142 );
143 bytes
144 .as_chunks::<4>()
145 .0
146 .iter()
147 .map(|b| i32::from_le_bytes(*b))
148 .collect()
149}
150
151/// Writes `input` through `flac_write`, then checks the header, the
152/// `STREAMINFO` and ffmpeg's decode against what went in.
153fn round_trip(name: &str, input: &[i32], bits: u32, channels: usize, rate: u32) {
154 let frames = input.len() / channels;
155 let out = Scratch::file(&format!("ve_flac_real_{name}"), "flac");
156 let started = Instant::now();
157 flac_write::write(&out, input, channels, bits, rate).expect("write the flac");
158 let wrote = started.elapsed();
159
160 let bytes = std::fs::read(&out).expect("read the flac back");
161 let (got_rate, got_channels, got_bits, total, md5) = streaminfo(&bytes);
162 assert_eq!(got_rate, rate, "{name}: STREAMINFO sample rate");
163 assert_eq!(got_channels, channels, "{name}: STREAMINFO channel count");
164 assert_eq!(got_bits, bits, "{name}: STREAMINFO bit depth");
165 assert_eq!(total, frames as u64, "{name}: STREAMINFO total samples");
166 assert_eq!(
167 md5,
168 md5_hex(&pcm_bytes(input, bits)),
169 "{name}: STREAMINFO MD5 is the MD5 of the input PCM"
170 );
171
172 let decoded = ffmpeg_decode(&out);
173 let shift = 32 - bits;
174 let expected: Vec<i32> = input.iter().map(|s| s << shift).collect();
175 assert_eq!(
176 decoded.len(),
177 expected.len(),
178 "{name}: decoded sample count"
179 );
180 let first_bad = decoded.iter().zip(&expected).position(|(a, b)| a != b);
181 assert_eq!(first_bad, None, "{name}: first mismatching sample index");
182
183 println!(
184 "{name}: {frames} frames x {channels} ch at {rate} Hz, {bits}-bit: \
185 {} bytes flac, encode {:.2} s, exact round trip",
186 bytes.len(),
187 wrote.as_secs_f64()
188 );
189}
190
191fn tools_present() -> bool {
192 if !have("ffmpeg") || !have("ffprobe") {
193 eprintln!("skipped: ffmpeg and ffprobe are needed");
194 return false;
195 }
196 true
197}
198
199#[test]
200fn wav_pcm16_round_trips_through_flac() {
201 let Some(path) = engine::real_library::film("wav_pcm16") else {
202 return;
203 };
204 if !tools_present() {
205 return;
206 }
207 let (rate, channels, duration) = source_shape(&path);
208 let samples = samples_of(&pcm_window(&path, duration, "s16le"), 16);
209 round_trip("wav_pcm16", &samples, 16, channels, rate);
210}
211
212#[test]
213fn av1_opus_51_round_trips_through_flac() {
214 let Some(path) = engine::real_library::film("av1_opus_51") else {
215 return;
216 };
217 if !tools_present() {
218 return;
219 }
220 let (rate, channels, duration) = source_shape(&path);
221 let pcm16 = samples_of(&pcm_window(&path, duration, "s16le"), 16);
222 round_trip("av1_opus_51_s16", &pcm16, 16, channels, rate);
223 let pcm24 = samples_of(&pcm_window(&path, duration, "s24le"), 24);
224 round_trip("av1_opus_51_s24", &pcm24, 24, channels, rate);
225}
226
227#[test]
228fn ac3_51_film_round_trips_through_flac() {
229 let Some(path) = engine::real_library::film("ac3_51_film") else {
230 return;
231 };
232 if !tools_present() {
233 return;
234 }
235 let (rate, channels, duration) = source_shape(&path);
236 let pcm16 = samples_of(&pcm_window(&path, duration, "s16le"), 16);
237 round_trip("ac3_51_film_s16", &pcm16, 16, channels, rate);
238 let pcm24 = samples_of(&pcm_window(&path, duration, "s24le"), 24);
239 round_trip("ac3_51_film_s24", &pcm24, 24, channels, rate);
240}