forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

audio_vorbis.rs290 lines, 9.4 KiBHistoryRawDownload
1//! Vorbis decode, in Ogg and in Matroska, comes out the way ffmpeg's own decode
2//! of the same file does, at the same length to the sample. Edith decodes Vorbis
3//! with `ec-vorbis`, and the audio path cuts each stream to its own end: the page
4//! granules in Ogg, the last block's `DiscardPadding` in Matroska.
5//!
6//! The reference is generated here: ffmpeg encodes a stereo tone pair with
7//! libvorbis, the file is decoded through [`AudioSession`] (the call site a
8//! project's audio takes), and ffmpeg decodes it again to 32-bit float. The two
9//! are compared channel by channel. A Matroska copy of the same stream is held to
10//! the same reference, because the container is the only thing that differs.
11//!
12//! A seek into the file is held to the full run's own samples (see
13//! [`a_seek_into_ogg_vorbis_is_the_full_runs_samples`]).
14//!
15//! Skipped loudly, the way the rest of the suite skips its reference decodes,
16//! when ffmpeg is not on the box.
17
18use std::path::Path;
19use std::process::Command;
20
21use engine::audio::AudioSession;
22use engine::scratch::Scratch;
23
24fn have_ffmpeg() -> bool {
25 Command::new("ffmpeg")
26 .arg("-version")
27 .output()
28 .is_ok_and(|o| o.status.success())
29}
30
31fn run(args: &[&str]) {
32 let out = Command::new("ffmpeg")
33 .args(["-v", "error", "-y"])
34 .args(args)
35 .output()
36 .expect("ffmpeg runs");
37 assert!(
38 out.status.success(),
39 "ffmpeg: {}",
40 String::from_utf8_lossy(&out.stderr)
41 );
42}
43
44/// The interleaved samples of `path`'s first audio track, and its channel count.
45fn decode(path: &Path) -> (u16, Vec<f32>) {
46 let (meta, rx) = AudioSession::open(path)
47 .expect("opens")
48 .expect("has an audio track");
49 assert_eq!(meta.sample_rate, 44_100, "the rate the file states");
50 let mut samples = Vec::new();
51 for chunk in rx {
52 samples.extend_from_slice(&chunk.samples);
53 }
54 (meta.channels, samples)
55}
56
57/// `path` decoded from `start_secs` on, interleaved, and its channel count.
58fn decode_from(path: &Path, start_secs: f64) -> (u16, Vec<f32>) {
59 let (meta, rx) = AudioSession::open_at(path, start_secs)
60 .expect("opens")
61 .expect("has an audio track");
62 let mut samples = Vec::new();
63 for chunk in rx {
64 samples.extend_from_slice(&chunk.samples);
65 }
66 (meta.channels, samples)
67}
68
69/// ffmpeg's decode of the same file, as interleaved 32-bit float at `channels`.
70fn reference(path: &Path, channels: u16) -> Vec<f32> {
71 let out = Command::new("ffmpeg")
72 .args(["-v", "error", "-i"])
73 .arg(path)
74 .args(["-map", "0:a:0", "-f", "f32le", "-ac"])
75 .arg(channels.to_string())
76 .args(["-ar", "44100", "-"])
77 .output()
78 .expect("ffmpeg runs");
79 assert!(
80 out.status.success(),
81 "ffmpeg: {}",
82 String::from_utf8_lossy(&out.stderr)
83 );
84 out.stdout
85 .as_chunks::<4>()
86 .0
87 .iter()
88 .map(|b| f32::from_le_bytes(*b))
89 .collect()
90}
91
92fn channel(interleaved: &[f32], channels: usize, index: usize) -> Vec<f32> {
93 interleaved
94 .iter()
95 .skip(index)
96 .step_by(channels)
97 .copied()
98 .collect()
99}
100
101/// Normalised correlation over the common length: 1.0 for the same waveform at
102/// the same offset.
103fn correlation(a: &[f32], b: &[f32]) -> f64 {
104 let n = a.len().min(b.len());
105 let (mut dot, mut aa, mut bb) = (0f64, 0f64, 0f64);
106 for (&x, &y) in a[..n].iter().zip(&b[..n]) {
107 dot += f64::from(x) * f64::from(y);
108 aa += f64::from(x) * f64::from(x);
109 bb += f64::from(y) * f64::from(y);
110 }
111 dot / (aa.sqrt() * bb.sqrt()).max(f64::MIN_POSITIVE)
112}
113
114#[test]
115fn stereo_vorbis_in_ogg_matches_ffmpeg_per_channel() {
116 if !have_ffmpeg() {
117 eprintln!("skipped: no ffmpeg to encode and decode the reference with");
118 return;
119 }
120 let ogg = Scratch::file("ve_vorbis_stereo", "ogg");
121 encode_ogg(&ogg, 2);
122 check_against_ffmpeg(&ogg);
123}
124
125#[test]
126fn stereo_vorbis_in_matroska_matches_ffmpeg_per_channel() {
127 if !have_ffmpeg() {
128 eprintln!("skipped: no ffmpeg to encode and decode the reference with");
129 return;
130 }
131 let mkv = Scratch::file("ve_vorbis_stereo", "mkv");
132 encode_mkv(&mkv, 2);
133 check_against_ffmpeg(&mkv);
134}
135
136#[test]
137fn mono_vorbis_in_ogg_matches_ffmpeg() {
138 if !have_ffmpeg() {
139 eprintln!("skipped: no ffmpeg to encode and decode the reference with");
140 return;
141 }
142 let ogg = Scratch::file("ve_vorbis_mono", "ogg");
143 encode_ogg(&ogg, 1);
144 check_against_ffmpeg(&ogg);
145}
146
147/// A two-second tone, libvorbis at a middling quality: 440 Hz in the left channel
148/// and 880 Hz in the right when there are two.
149fn encode_ogg(path: &Scratch, channels: u16) {
150 encode(path, channels, "ogg", 2);
151}
152
153fn encode_mkv(path: &Scratch, channels: u16) {
154 encode(path, channels, "matroska", 2);
155}
156
157fn encode(path: &Scratch, channels: u16, format: &str, secs: u32) {
158 let mut args: Vec<String> = vec![
159 "-f".into(),
160 "lavfi".into(),
161 "-i".into(),
162 format!("sine=f=440:d={secs}"),
163 ];
164 if channels == 2 {
165 args.extend(["-f", "lavfi", "-i", &format!("sine=f=880:d={secs}")].map(String::from));
166 args.extend(["-filter_complex", "[0][1]amerge=inputs=2"].map(String::from));
167 }
168 args.extend(
169 [
170 "-ac",
171 &channels.to_string(),
172 "-ar",
173 "44100",
174 "-c:a",
175 "libvorbis",
176 "-q:a",
177 "5",
178 "-f",
179 format,
180 ]
181 .map(String::from),
182 );
183 args.push(path.to_string_lossy().into_owned());
184 let refs: Vec<&str> = args.iter().map(String::as_str).collect();
185 run(&refs);
186}
187
188fn check_against_ffmpeg(file: &Path) {
189 let (channels, ours) = decode(file);
190 let theirs = reference(file, channels);
191 let n = channels as usize;
192 assert!(!ours.is_empty(), "no sound out of {}", file.display());
193 // The length is the stream's, to the frame: both the Ogg granules and the
194 // Matroska padding state it exactly.
195 eprintln!(
196 "{}: {} frames per channel from edith, {} from ffmpeg",
197 file.display(),
198 ours.len() / n,
199 theirs.len() / n
200 );
201 assert_eq!(
202 ours.len(),
203 theirs.len(),
204 "frames per channel: edith {}, ffmpeg {}",
205 ours.len() / n,
206 theirs.len() / n
207 );
208 for index in 0..n {
209 let c = correlation(&channel(&ours, n, index), &channel(&theirs, n, index));
210 eprintln!("channel {index} correlates {c:.6} with ffmpeg");
211 assert!(c > 0.999, "channel {index} correlates {c:.6} with ffmpeg");
212 }
213}
214
215/// A seek into an Ogg Vorbis file lands on the full run's own samples: the
216/// tail from `start` is the same frames, bit for bit, at the same timeline
217/// position. Exact, not a tolerance: the reader lands on the packet at or before
218/// the target, and the decoder's warm-up is dropped (`ec-vorbis` answers nothing
219/// for a fresh decoder's first block, and that block's position is not taken).
220#[test]
221fn a_seek_into_ogg_vorbis_is_the_full_runs_samples() {
222 if !have_ffmpeg() {
223 eprintln!("skipped: no ffmpeg to encode the fixture with");
224 return;
225 }
226 let ogg = Scratch::file("ve_vorbis_seek", "ogg");
227 encode_ogg(&ogg, 2);
228 check_seek_is_full_run(&ogg);
229}
230
231/// The same seek on Matroska: its blocks are stamped in whole milliseconds, which
232/// is not where the samples are, so the reader has to place each packet by the
233/// samples before it rather than by its stamp.
234#[test]
235fn a_seek_into_matroska_vorbis_is_the_full_runs_samples() {
236 if !have_ffmpeg() {
237 eprintln!("skipped: no ffmpeg to encode the fixture with");
238 return;
239 }
240 let mkv = Scratch::file("ve_vorbis_seek", "mkv");
241 encode_mkv(&mkv, 2);
242 check_seek_is_full_run(&mkv);
243}
244
245/// A Matroska file long enough for several clusters: the targets fall in and
246/// across them, where the container's own seek used to land a cluster past the
247/// target.
248#[test]
249fn a_seek_across_matroska_clusters_is_the_full_runs_samples() {
250 if !have_ffmpeg() {
251 eprintln!("skipped: no ffmpeg to encode the fixture with");
252 return;
253 }
254 let mkv = Scratch::file("ve_vorbis_seek_long", "mkv");
255 encode(&mkv, 2, "matroska", 14);
256 check_seek_targets_is_full_run(&mkv, &[0.25, 3.5, 6.2, 9.9, 12.5, 13.7]);
257}
258
259/// Six seeks across `file`, each held to the full run's own tail from the same
260/// timeline position.
261fn check_seek_is_full_run(file: &Path) {
262 check_seek_targets_is_full_run(file, &[0.25, 0.5, 1.0, 1.25, 1.7, 1.99]);
263}
264
265fn check_seek_targets_is_full_run(file: &Path, targets: &[f64]) {
266 let (channels, full) = decode_from(file, 0.0);
267 let n = usize::from(channels);
268 let frames = full.len() / n;
269 // Targets across the file, the last near its end, each a whole frame.
270 for &secs in targets {
271 let at = (secs * 44_100.0_f64).round() as usize;
272 let (_, part) = decode_from(file, secs);
273 let want = &full[at * n..];
274 assert_eq!(
275 part.len() / n,
276 frames - at,
277 "a seek to {secs} s is a different length from the full run's tail"
278 );
279 if let Some(i) = part.iter().zip(want).position(|(a, b)| a != b) {
280 panic!(
281 "a seek to {secs} s differs from the full run at frame {} \
282 (sample {i} of the tail): {} vs {}",
283 i / n,
284 part[i],
285 want[i]
286 );
287 }
288 }
289}
290