forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

audio_aac.rs249 lines, 9.2 KiBHistoryRawDownload
1//! Every AAC stream edith decodes goes through `ec-aac`, HE-AAC included.
2//!
3//! symphonia refused SBR outright ("aac: aac too complex"), so a stereo HE-AAC
4//! file never opened here. The first test is that file; the second is an AAC-LC
5//! file through the same path, held to ffmpeg's decode of it; the third is the
6//! guard that keeps symphonia's AAC decoder out of the engine's dependencies.
7
8use std::path::{Path, PathBuf};
9use std::process::Command;
10
11use engine::audio::AudioSession;
12use engine::scratch::Scratch;
13
14/// A stereo HE-AAC v1 clip, 2.04 s, 44.1 kHz output from a 22.05 kHz AAC-LC core
15/// with SBR, a 2 s stream copy of edith_codecs' synthetic sweep fixture (scripts/aac-tables/make-heaac-fixtures.sh, heaac_44100_48k). The
16/// container says 44.1 kHz; the core it codes is half that.
17const HE_FIXTURE: &str = "aac_he_v1_stereo.m4a";
18
19fn fixture(name: &str) -> PathBuf {
20 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
21 .join("tests/data")
22 .join(name)
23}
24
25/// The interleaved samples of `path`'s first audio track, with its metadata.
26fn decode(path: &Path) -> (engine::audio::AudioMeta, Vec<f32>) {
27 let (meta, rx) = AudioSession::open(path)
28 .expect("opens")
29 .expect("has an audio track");
30 let mut samples = Vec::new();
31 for chunk in rx {
32 samples.extend_from_slice(&chunk.samples);
33 }
34 (meta, samples)
35}
36
37/// One channel out of an interleaved buffer.
38fn channel(interleaved: &[f32], channels: usize, index: usize) -> Vec<f32> {
39 interleaved.iter().skip(index).step_by(channels).copied().collect()
40}
41
42/// Root-mean-square level of a run of samples.
43fn rms(samples: &[f32]) -> f64 {
44 let sum: f64 = samples.iter().map(|&s| f64::from(s) * f64::from(s)).sum();
45 (sum / samples.len().max(1) as f64).sqrt()
46}
47
48/// Normalised correlation of two runs over their common length: 1.0 when they
49/// are the same waveform at the same offset.
50fn correlation(a: &[f32], b: &[f32]) -> f64 {
51 let n = a.len().min(b.len());
52 let (mut dot, mut aa, mut bb) = (0f64, 0f64, 0f64);
53 for (&x, &y) in a[..n].iter().zip(&b[..n]) {
54 dot += f64::from(x) * f64::from(y);
55 aa += f64::from(x) * f64::from(x);
56 bb += f64::from(y) * f64::from(y);
57 }
58 dot / (aa.sqrt() * bb.sqrt()).max(f64::MIN_POSITIVE)
59}
60
61/// Whether `ffmpeg` runs here. Without it the tests that need it are skipped,
62/// loudly, the way the rest of the suite skips its reference decodes.
63fn have_ffmpeg() -> bool {
64 Command::new("ffmpeg").arg("-version").output().is_ok_and(|o| o.status.success())
65}
66
67#[test]
68fn stereo_he_aac_opens_at_its_sbr_rate_and_decodes() {
69 let (meta, samples) = decode(&fixture(HE_FIXTURE));
70 // The output rate is the extension rate, not the core's: 44.1 kHz from a
71 // 22.05 kHz core. A timeline counted in the core rate would run at half speed.
72 assert_eq!((meta.sample_rate, meta.channels), (44_100, 2));
73
74 let frames = samples.len() / 2;
75 let secs = frames as f64 / 44_100.0;
76 assert!(
77 (1.9..=2.1).contains(&secs),
78 "{frames} frames per channel is {secs:.3} s, want about 2.04 s"
79 );
80 for index in 0..2 {
81 let level = rms(&channel(&samples, 2, index));
82 assert!(level > 1e-3, "channel {index} is silent (rms {level})");
83 }
84}
85
86#[test]
87fn stereo_he_aac_in_matroska_decodes_at_the_same_rate() {
88 if !have_ffmpeg() {
89 eprintln!("skipped: no ffmpeg to remux the fixture into Matroska");
90 return;
91 }
92 let mkv = Scratch::file("ve_aac_he", "mkv");
93 let out = Command::new("ffmpeg")
94 .args(["-v", "error", "-y", "-i"])
95 .arg(fixture(HE_FIXTURE))
96 .args(["-c", "copy"])
97 .arg(&*mkv)
98 .output()
99 .expect("ffmpeg runs");
100 assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));
101
102 let (meta, samples) = decode(&mkv);
103 assert_eq!((meta.sample_rate, meta.channels), (44_100, 2));
104 assert!(rms(&samples) > 1e-3, "no sound out of the Matroska copy");
105}
106
107#[test]
108fn stereo_aac_lc_matches_ffmpeg_per_channel() {
109 if !have_ffmpeg() {
110 eprintln!("skipped: no ffmpeg to encode and decode the reference with");
111 return;
112 }
113 // 440 Hz left, 880 Hz right, AAC-LC from ffmpeg's own encoder.
114 let m4a = Scratch::file("ve_aac_lc", "m4a");
115 let out = Command::new("ffmpeg")
116 .args(["-v", "error", "-y"])
117 .args(["-f", "lavfi", "-i", "sine=f=440:d=2"])
118 .args(["-f", "lavfi", "-i", "sine=f=880:d=2"])
119 .args(["-filter_complex", "[0][1]amerge=inputs=2", "-ac", "2", "-ar", "44100"])
120 .args(["-c:a", "aac", "-b:a", "128k"])
121 .arg(&*m4a)
122 .output()
123 .expect("ffmpeg runs");
124 assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));
125
126 let (meta, ours) = decode(&m4a);
127 assert_eq!((meta.sample_rate, meta.channels), (44_100, 2));
128
129 let reference = Command::new("ffmpeg")
130 .args(["-v", "error", "-i"])
131 .arg(&*m4a)
132 .args(["-map", "0:a:0", "-f", "f32le", "-ac", "2", "-ar", "44100", "-"])
133 .output()
134 .expect("ffmpeg runs");
135 assert!(reference.status.success());
136 let theirs: Vec<f32> = reference
137 .stdout
138 .as_chunks::<4>().0.iter()
139 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
140 .collect();
141
142 for index in 0..2 {
143 let a = channel(&ours, 2, index);
144 let b = channel(&theirs, 2, index);
145 let r = correlation(&a, &b);
146 assert!(r >= 0.999, "channel {index} correlates {r:.6} with ffmpeg, want >= 0.999");
147 }
148}
149
150#[test]
151fn symphonia_codec_aac_is_not_an_engine_dependency() {
152 // symphonia's AAC decoder refuses HE-AAC, and every AAC stream now goes
153 // through `ec-aac`. Neither the crate nor symphonia's `aac` feature may
154 // come back: that feature is the only thing that pulls the crate in.
155 let manifest = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml"))
156 .expect("read engine's Cargo.toml");
157 let live = |line: &&str| !line.trim_start().starts_with('#');
158 assert!(
159 !manifest.lines().filter(live).any(|l| l.contains("symphonia-codec-aac")),
160 "symphonia-codec-aac is back in engine's dependencies"
161 );
162 let features = manifest
163 .split("symphonia = {")
164 .nth(1)
165 .and_then(|rest| rest.split(']').next())
166 .expect("engine depends on symphonia");
167 assert!(
168 !features.contains("\"aac\""),
169 "symphonia's aac feature is back in engine's Cargo.toml"
170 );
171}
172
173/// A bare ADTS HE-AAC stream, 2 s, stereo, 44.1 kHz: its headers say AAC-LC at
174/// 22.05 kHz, and every frame carries an SBR payload (implicit signalling). The
175/// rate has to come from decoding the frames, not from the headers.
176const ADTS_IMPLICIT_FIXTURE: &str = "heaac_44100_48k_implicit_2s.aac";
177
178#[test]
179fn bare_adts_he_aac_opens_at_its_implicit_sbr_rate() {
180 let (meta, samples) = decode(&fixture(ADTS_IMPLICIT_FIXTURE));
181 // The headers say 22.05 kHz; the decoded SBR output is 44.1 kHz.
182 assert_eq!((meta.sample_rate, meta.channels), (44_100, 2));
183
184 // Whole ADTS frames, not trimmed to 2 s: 47 frames of 2048 samples, 2.14 s,
185 // which is the length ffmpeg decodes too.
186 let frames = samples.len() / 2;
187 let secs = frames as f64 / 44_100.0;
188 assert!(
189 (1.9..=2.2).contains(&secs),
190 "{frames} frames per channel is {secs:.3} s, want about 2 s"
191 );
192 for index in 0..2 {
193 let level = rms(&channel(&samples, 2, index));
194 assert!(level > 1e-3, "channel {index} is silent (rms {level})");
195 }
196}
197
198#[test]
199fn bare_adts_he_aac_matches_ffmpeg_per_channel() {
200 if !have_ffmpeg() {
201 eprintln!("skipped: no ffmpeg to decode the reference with");
202 return;
203 }
204 let (_, ours) = decode(&fixture(ADTS_IMPLICIT_FIXTURE));
205
206 let reference = Command::new("ffmpeg")
207 .args(["-v", "error", "-i"])
208 .arg(fixture(ADTS_IMPLICIT_FIXTURE))
209 .args(["-map", "0:a:0", "-f", "f32le", "-ac", "2", "-ar", "44100", "-"])
210 .output()
211 .expect("ffmpeg runs");
212 assert!(reference.status.success());
213 let theirs: Vec<f32> = reference
214 .stdout
215 .as_chunks::<4>()
216 .0
217 .iter()
218 .map(|b| f32::from_le_bytes(*b))
219 .collect();
220
221 for index in 0..2 {
222 let r = correlation(&channel(&ours, 2, index), &channel(&theirs, 2, index));
223 assert!(r >= 0.999, "channel {index} correlates {r:.6} with ffmpeg, want >= 0.999");
224 }
225}
226
227#[test]
228fn mp4_he_aac_with_an_implicit_config_opens_at_its_sbr_rate() {
229 // ffmpeg's mp4 muxer writes the ADTS headers as an AudioSpecificConfig: plain
230 // AAC-LC at 22.05 kHz, with SBR payloads in the frames. The mp4 track must
231 // report the decoded 44.1 kHz rate, as the bare stream does.
232 if !have_ffmpeg() {
233 eprintln!("skipped: no ffmpeg to remux the fixture into mp4");
234 return;
235 }
236 let m4a = Scratch::file("ve_aac_implicit", "m4a");
237 let out = Command::new("ffmpeg")
238 .args(["-v", "error", "-y", "-i"])
239 .arg(fixture(ADTS_IMPLICIT_FIXTURE))
240 .args(["-c", "copy"])
241 .arg(&*m4a)
242 .output()
243 .expect("ffmpeg runs");
244 assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));
245
246 let (meta, samples) = decode(&m4a);
247 assert_eq!((meta.sample_rate, meta.channels), (44_100, 2));
248 assert!(rms(&samples) > 1e-3, "no sound out of the mp4 copy");
249}