forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

ogg_opus_import.rs152 lines, 4.5 KiBHistoryRawDownload
1//! Opus in Ogg, read through edith's own audio call site ([`AudioSession`], the
2//! path a project's imported audio takes), held to ffmpeg's own decode of the
3//! same file: the same length to within one Opus packet, and the same waveform
4//! channel by channel.
5//!
6//! The reference is generated here: ffmpeg encodes a two-second stereo tone pair
7//! with libopus into an `.ogg`, and ffmpeg decodes that file to 32-bit float at
8//! 48 kHz. Opus output is always 48 kHz, so the rate is part of what is checked.
9//!
10//! Skipped loudly when ffmpeg is not on the box.
11//!
12//! ```text
13//! cargo test -p engine --release --test ogg_opus_import -- --nocapture
14//! ```
15
16use std::path::Path;
17use std::process::Command;
18
19use engine::audio::AudioSession;
20use engine::scratch::Scratch;
21
22const RATE: u32 = 48_000;
23/// One 20 ms Opus packet at 48 kHz: the most two decoders may disagree on the
24/// length of a file by, since each trims its own end.
25const ONE_PACKET: usize = 960;
26
27fn have_ffmpeg() -> bool {
28 Command::new("ffmpeg")
29 .arg("-version")
30 .output()
31 .is_ok_and(|o| o.status.success())
32}
33
34fn s(path: &Path) -> &str {
35 path.to_str().expect("a UTF-8 path")
36}
37
38fn ffmpeg(args: &[&str]) {
39 let out = Command::new("ffmpeg")
40 .args(["-v", "error", "-y"])
41 .args(args)
42 .output()
43 .expect("ffmpeg runs");
44 assert!(
45 out.status.success(),
46 "ffmpeg {args:?}: {}",
47 String::from_utf8_lossy(&out.stderr)
48 );
49}
50
51/// Edith's decode of the file's first audio track: the channel count, the rate
52/// it states, and the interleaved samples.
53fn decode(path: &Path) -> (u16, u32, Vec<f32>) {
54 let (meta, rx) = AudioSession::open(path)
55 .expect("opens")
56 .expect("has an audio track");
57 let mut samples = Vec::new();
58 for chunk in rx {
59 samples.extend_from_slice(&chunk.samples);
60 }
61 (meta.channels, meta.sample_rate, samples)
62}
63
64/// ffmpeg's decode of the same file, interleaved f32 at 48 kHz, stereo.
65fn reference(path: &Path) -> Vec<f32> {
66 let out = Command::new("ffmpeg")
67 .args(["-v", "error", "-i"])
68 .arg(path)
69 .args(["-map", "0:a:0", "-f", "f32le", "-ar", "48000", "-ac", "2", "-"])
70 .output()
71 .expect("ffmpeg runs");
72 assert!(
73 out.status.success(),
74 "ffmpeg: {}",
75 String::from_utf8_lossy(&out.stderr)
76 );
77 out.stdout
78 .as_chunks::<4>()
79 .0
80 .iter()
81 .map(|b| f32::from_le_bytes(*b))
82 .collect()
83}
84
85fn channel(interleaved: &[f32], channels: usize, index: usize) -> Vec<f32> {
86 interleaved
87 .iter()
88 .skip(index)
89 .step_by(channels)
90 .copied()
91 .collect()
92}
93
94/// Normalised correlation over the common length: 1.0 for the same waveform at
95/// the same offset.
96fn correlation(a: &[f32], b: &[f32]) -> f64 {
97 let n = a.len().min(b.len());
98 let (mut dot, mut aa, mut bb) = (0f64, 0f64, 0f64);
99 for (&x, &y) in a[..n].iter().zip(&b[..n]) {
100 dot += f64::from(x) * f64::from(y);
101 aa += f64::from(x) * f64::from(x);
102 bb += f64::from(y) * f64::from(y);
103 }
104 dot / (aa.sqrt() * bb.sqrt()).max(f64::MIN_POSITIVE)
105}
106
107#[test]
108fn stereo_opus_in_ogg_matches_ffmpegs_decode_in_length_and_waveform() {
109 if !have_ffmpeg() {
110 eprintln!("skipped: no ffmpeg to encode and decode the reference with");
111 return;
112 }
113 let ogg = Scratch::file("ve_opus_stereo", "ogg");
114 ffmpeg(&[
115 "-f",
116 "lavfi",
117 "-i",
118 "aevalsrc=sin(2*PI*440*t)|0.5*sin(2*PI*660*t):s=48000:d=2",
119 "-c:a",
120 "libopus",
121 "-b:a",
122 "96k",
123 s(&ogg),
124 ]);
125
126 let (channels, rate, edith) = decode(&ogg);
127 assert_eq!(rate, RATE, "Opus is decoded at the 48 kHz it is coded at");
128 assert_eq!(channels, 2, "the stereo the file states");
129
130 let want = reference(&ogg);
131 let frames = edith.len() / 2;
132 let want_frames = want.len() / 2;
133 assert!(
134 frames.abs_diff(want_frames) <= ONE_PACKET,
135 "edith decodes {frames} frames, ffmpeg {want_frames}"
136 );
137 // Two seconds, give or take the packet each decoder trims at its end.
138 assert!(
139 frames.abs_diff(2 * RATE as usize) <= ONE_PACKET,
140 "two seconds of audio, not {frames} frames"
141 );
142
143 for index in 0..2 {
144 let a = channel(&edith, 2, index);
145 let b = channel(&want, 2, index);
146 let r = correlation(&a, &b);
147 assert!(
148 r > 0.99,
149 "channel {index}: correlation {r} against ffmpeg's decode"
150 );
151 }
152}