forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

audio_aac_v2.rs207 lines, 6.3 KiBHistoryRawDownload
1//! HE-AAC v2 (AAC with Parametric Stereo) is decoded through `ec-aac`, not refused.
2//!
3//! The stream is encoded here by ffmpeg's `libfdk_aac` from a stereo source, so
4//! the core is mono and the second channel comes from PS. Three wrappings are
5//! covered: an mp4 with the explicit v2 config ffmpeg writes on encode, a bare
6//! ADTS stream (implicit signalling), and an mp4 remuxed from that ADTS. Each is
7//! held to ffmpeg's own decode, per channel. A machine whose ffmpeg has no
8//! `libfdk_aac` that can encode v2 skips the test loudly, as the other reference
9//! tests do. Some builds of `libfdk_aac` have SBR and PS compiled out, so the
10//! encoder is probed with a real v2 encode, not just looked up by name.
11
12use std::path::Path;
13use std::process::Command;
14
15use engine::audio::AudioSession;
16use engine::scratch::Scratch;
17
18/// The ffmpeg arguments that encode the test source as HE-AAC v2 into `out`.
19fn he_v2_args(out: &str, seconds: &str) -> Vec<String> {
20 [
21 "-f",
22 "lavfi",
23 "-i",
24 &format!("sine=f=440:d={seconds}"),
25 "-f",
26 "lavfi",
27 "-i",
28 &format!("sine=f=880:d={seconds}"),
29 "-filter_complex",
30 "[0][1]amerge=inputs=2",
31 "-ac",
32 "2",
33 "-ar",
34 "44100",
35 "-c:a",
36 "libfdk_aac",
37 "-profile:a",
38 "aac_he_v2",
39 "-b:a",
40 "24k",
41 out,
42 ]
43 .map(String::from)
44 .to_vec()
45}
46
47/// Whether this machine's ffmpeg can encode HE-AAC v2: a short real encode, so a
48/// `libfdk_aac` without PS support counts as absent.
49fn can_encode_he_v2() -> bool {
50 let probe = Scratch::file("ve_aac_v2_probe", "m4a");
51 Command::new("ffmpeg")
52 .args(["-v", "error", "-y"])
53 .args(he_v2_args(probe.to_str().expect("utf-8 path"), "0.2"))
54 .output()
55 .is_ok_and(|o| o.status.success())
56}
57
58/// Runs `ffmpeg` with `args`, panicking with its stderr on failure.
59fn ffmpeg(args: &[String]) {
60 let out = Command::new("ffmpeg")
61 .args(["-v", "error", "-y"])
62 .args(args)
63 .output()
64 .expect("ffmpeg runs");
65 assert!(
66 out.status.success(),
67 "ffmpeg {args:?}: {}",
68 String::from_utf8_lossy(&out.stderr)
69 );
70}
71
72/// The interleaved samples of `path`'s first audio track, with its metadata.
73fn decode(path: &Path) -> (engine::audio::AudioMeta, Vec<f32>) {
74 let (meta, rx) = AudioSession::open(path)
75 .expect("opens")
76 .expect("has an audio track");
77 let mut samples = Vec::new();
78 for chunk in rx {
79 samples.extend_from_slice(&chunk.samples);
80 }
81 (meta, samples)
82}
83
84/// One channel out of an interleaved buffer.
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 of two runs over their common length.
95fn correlation(a: &[f32], b: &[f32]) -> f64 {
96 let n = a.len().min(b.len());
97 let (mut dot, mut aa, mut bb) = (0f64, 0f64, 0f64);
98 for (&x, &y) in a[..n].iter().zip(&b[..n]) {
99 dot += f64::from(x) * f64::from(y);
100 aa += f64::from(x) * f64::from(x);
101 bb += f64::from(y) * f64::from(y);
102 }
103 dot / (aa.sqrt() * bb.sqrt()).max(f64::MIN_POSITIVE)
104}
105
106/// ffmpeg's own decode of `path`'s first audio track, stereo at 44.1 kHz.
107fn reference(path: &Path) -> Vec<f32> {
108 let out = Command::new("ffmpeg")
109 .args(["-v", "error", "-i"])
110 .arg(path)
111 .args([
112 "-map", "0:a:0", "-f", "f32le", "-ac", "2", "-ar", "44100", "-",
113 ])
114 .output()
115 .expect("ffmpeg runs");
116 assert!(
117 out.status.success(),
118 "ffmpeg decode: {}",
119 String::from_utf8_lossy(&out.stderr)
120 );
121 out.stdout
122 .as_chunks::<4>()
123 .0
124 .iter()
125 .map(|b| f32::from_le_bytes(*b))
126 .collect()
127}
128
129/// Encodes a 2 s stereo source (440 Hz left, 880 Hz right) as HE-AAC v2 at
130/// 24 kbps into `out`, in the container `out` names.
131fn encode_he_v2(out: &Path) {
132 ffmpeg(&he_v2_args(out.to_str().expect("utf-8 path"), "2"));
133}
134
135/// Checks `ours` against ffmpeg's decode of `path`, channel by channel.
136fn assert_matches_ffmpeg(path: &Path, ours: &[f32]) {
137 let theirs = reference(path);
138 for index in 0..2 {
139 let r = correlation(&channel(ours, 2, index), &channel(&theirs, 2, index));
140 assert!(
141 r >= 0.999,
142 "channel {index} correlates {r:.6} with ffmpeg, want >= 0.999"
143 );
144 }
145}
146
147fn assert_stereo_at_44_1(path: &Path) -> Vec<f32> {
148 let (meta, samples) = decode(path);
149 // The output is stereo at the SBR extension rate, whatever the core's width.
150 assert_eq!(
151 (meta.sample_rate, meta.channels),
152 (44_100, 2),
153 "{}",
154 path.display()
155 );
156 let frames = samples.len() / 2;
157 assert!(
158 frames > 40_000,
159 "{frames} frames per channel from {}",
160 path.display()
161 );
162 samples
163}
164
165#[test]
166fn he_aac_v2_in_mp4_decodes_to_stereo_and_matches_ffmpeg() {
167 if !can_encode_he_v2() {
168 eprintln!("skipped: no ffmpeg here encodes HE-AAC v2 (libfdk_aac with PS needed)");
169 return;
170 }
171 let m4a = Scratch::file("ve_aac_v2_mp4", "m4a");
172 encode_he_v2(&m4a);
173 let samples = assert_stereo_at_44_1(&m4a);
174 assert_matches_ffmpeg(&m4a, &samples);
175}
176
177#[test]
178fn he_aac_v2_in_adts_decodes_to_stereo_and_matches_ffmpeg() {
179 if !can_encode_he_v2() {
180 eprintln!("skipped: no ffmpeg here encodes HE-AAC v2 (libfdk_aac with PS needed)");
181 return;
182 }
183 let aac = Scratch::file("ve_aac_v2_adts", "aac");
184 encode_he_v2(&aac);
185 let samples = assert_stereo_at_44_1(&aac);
186 assert_matches_ffmpeg(&aac, &samples);
187}
188
189#[test]
190fn he_aac_v2_adts_remuxed_to_mp4_decodes_to_stereo_and_matches_ffmpeg() {
191 if !can_encode_he_v2() {
192 eprintln!("skipped: no ffmpeg here encodes HE-AAC v2 (libfdk_aac with PS needed)");
193 return;
194 }
195 let aac = Scratch::file("ve_aac_v2_src", "aac");
196 encode_he_v2(&aac);
197 let m4a = Scratch::file("ve_aac_v2_remux", "m4a");
198 ffmpeg(&[
199 "-i".into(),
200 aac.to_str().expect("utf-8 path").into(),
201 "-c".into(),
202 "copy".into(),
203 m4a.to_str().expect("utf-8 path").into(),
204 ]);
205 let samples = assert_stereo_at_44_1(&m4a);
206 assert_matches_ffmpeg(&m4a, &samples);
207}