forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

implicit_sbr.rs222 lines, 8.1 KiBHistoryRawDownload
1//! Implicit SBR signalling (ISO/IEC 14496-3 1.6.5.2): a stream whose config or
2//! ADTS header says plain AAC-LC, but whose frames carry an SBR extension
3//! payload, is decoded as HE-AAC at twice the core rate, as ffmpeg does.
4
5use crate::shared::fixtures;
6use crate::shared::have_ffmpeg;
7use std::path::{Path, PathBuf};
8use std::process::Command;
9
10use ec_aac::{AacDecoder, SbrSupport};
11
12/// Same contract as `oracle.rs`: an absent fixture skips loudly, and under
13/// `EC_REQUIRE_FIXTURES=1` it is a hard failure instead.
14fn require_fixture(path: &Path) -> bool {
15 let present = path.exists();
16 assert!(
17 present || std::env::var_os("EC_REQUIRE_FIXTURES").is_none(),
18 "EC_REQUIRE_FIXTURES=1 but fixture {} is absent",
19 path.display()
20 );
21 if !present {
22 eprintln!("SKIP: fixture {} absent", path.display());
23 }
24 present
25}
26
27/// The implicit-signalling HE-AAC fixture: 2 s of `heaac_44100_48k.m4a` remuxed to
28/// bare ADTS with `ffmpeg -c copy -f adts`. Its headers say AAC-LC at 22050 Hz.
29fn implicit_fixture() -> PathBuf {
30 Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/data/heaac_44100_48k_implicit_2s.aac")
31}
32
33/// ffmpeg's decode of a file, as planar-by-channel `f32`.
34fn ffmpeg_decode(path: &Path) -> Vec<Vec<f32>> {
35 let out = Command::new("ffmpeg")
36 .args(["-v", "error", "-i"])
37 .arg(path)
38 .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])
39 .output()
40 .expect("ffmpeg runs");
41 assert!(out.status.success(), "ffmpeg decode failed");
42 let samples: Vec<f32> = out
43 .stdout
44 .as_chunks::<4>()
45 .0
46 .iter()
47 .map(|c| f32::from_le_bytes([c[0], c[1], c[2], c[3]]))
48 .collect();
49 deinterleave(&samples, 2)
50}
51
52fn deinterleave(samples: &[f32], channels: usize) -> Vec<Vec<f32>> {
53 let mut out = vec![Vec::with_capacity(samples.len() / channels); channels];
54 for (i, &v) in samples.iter().enumerate() {
55 out[i % channels].push(v);
56 }
57 out
58}
59
60/// Pearson correlation over the overlap of two channels.
61fn correlation(a: &[f32], b: &[f32]) -> f64 {
62 let n = a.len().min(b.len());
63 assert!(n > 1024, "not enough overlap to compare: {n} samples");
64 let (a, b) = (&a[..n], &b[..n]);
65 let ma = a.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
66 let mb = b.iter().map(|v| f64::from(*v)).sum::<f64>() / n as f64;
67 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
68 for i in 0..n {
69 let (x, y) = (f64::from(a[i]) - ma, f64::from(b[i]) - mb);
70 num += x * y;
71 da += x * x;
72 db += y * y;
73 }
74 if da == 0.0 || db == 0.0 {
75 return if da == db { 1.0 } else { 0.0 };
76 }
77 num / (da * db).sqrt()
78}
79
80/// Decodes an ADTS file frame by frame, reading the output rate after each
81/// frame, as a caller would. Returns the planes, the rate before the first
82/// frame, and the rate after each frame.
83fn decode_adts(path: &Path) -> (Vec<Vec<f32>>, Option<u32>, Vec<u32>, AacDecoder) {
84 let data = std::fs::read(path).expect("fixture readable");
85 let mut decoder = AacDecoder::new();
86 let before = decoder.output_sample_rate();
87 let mut planes: Vec<Vec<f32>> = Vec::new();
88 let mut rates = Vec::new();
89 let mut at = 0usize;
90 while at + 7 <= data.len() {
91 let header = ec_aac::parse_adts(&data[at..]).expect("adts header");
92 let end = (at + header.frame_length).min(data.len());
93 let frame = decoder.decode(&data[at..end], None).expect("frame decodes");
94 assert_eq!(
95 Some(frame.sample_rate),
96 decoder.output_sample_rate(),
97 "a frame's rate must match the decoder's rate after that frame"
98 );
99 rates.push(frame.sample_rate);
100 let ch = usize::from(frame.channels);
101 if planes.is_empty() {
102 planes = vec![Vec::new(); ch];
103 }
104 for (i, v) in frame.samples.iter().enumerate() {
105 planes[i % ch].push(*v);
106 }
107 at = end;
108 }
109 (planes, before, rates, decoder)
110}
111
112#[test]
113fn implicit_he_aac_adts_switches_to_double_rate() {
114 let path = implicit_fixture();
115 if !require_fixture(&path) {
116 return;
117 }
118 let (ours, before, rates, decoder) = decode_adts(&path);
119
120 // Headers say 22050 Hz AAC-LC: nothing is known about the rate before frame 1.
121 assert_eq!(before, None, "no output rate before the first frame");
122 assert!(decoder.sbr_implicit(), "the SBR payload must switch implicit SBR on");
123 assert_eq!(decoder.sbr_support(), SbrSupport::V1);
124 assert_eq!(decoder.config().map(|c| c.sample_rate), None, "ADTS carries no config");
125 assert_eq!(decoder.output_sample_rate(), Some(44_100));
126
127 // The first frame carries the payload, so it is already at the doubled rate.
128 assert_eq!(rates[0], 44_100, "first frame is decoded with SBR");
129 assert!(rates.iter().all(|&r| r == 44_100));
130 assert_eq!(ours.len(), 2, "stereo");
131 let frames = ours[0].len();
132 assert!(frames > 80_000, "about 2 s at 44.1 kHz, got {frames}");
133 assert_eq!(ours[1].len(), frames);
134 for (ch, plane) in ours.iter().enumerate() {
135 let rms = (plane.iter().map(|v| f64::from(*v).powi(2)).sum::<f64>() / frames as f64).sqrt();
136 assert!(rms > 1e-4, "channel {ch} is silent after SBR (rms {rms})");
137 }
138}
139
140#[test]
141fn implicit_he_aac_adts_matches_ffmpeg_per_channel() {
142 if !have_ffmpeg() {
143 eprintln!("SKIP: ffmpeg not on PATH");
144 return;
145 }
146 let path = implicit_fixture();
147 if !require_fixture(&path) {
148 return;
149 }
150 let (ours, _, _, _) = decode_adts(&path);
151 let theirs = ffmpeg_decode(&path);
152 assert_eq!(theirs.len(), ours.len());
153 for (ch, (a, b)) in ours.iter().zip(&theirs).enumerate() {
154 let c = correlation(a, b);
155 assert!(c >= 0.999, "channel {ch}: correlation with ffmpeg {c:.6} < 0.999");
156 }
157}
158
159#[test]
160fn plain_aac_lc_adts_is_unchanged_by_implicit_detection() {
161 if !have_ffmpeg() {
162 eprintln!("SKIP: ffmpeg not on PATH");
163 return;
164 }
165 let path = fixtures().join("audio/aac-adts-stereo-44100.aac");
166 if !require_fixture(&path) {
167 return;
168 }
169 let (ours, _, rates, decoder) = decode_adts(&path);
170
171 // A plain LC stream has no SBR payload: no switch, and the rate stays at the core.
172 assert!(!decoder.sbr_implicit());
173 assert_eq!(decoder.sbr_support(), SbrSupport::NotSignalled);
174 assert!(rates.iter().all(|&r| r == 44_100));
175 assert_eq!(decoder.output_sample_rate(), Some(44_100));
176
177 let theirs = ffmpeg_decode(&path);
178 for (ch, (a, b)) in ours.iter().zip(&theirs).enumerate() {
179 let c = correlation(a, b);
180 assert!(c >= 0.999, "channel {ch}: correlation with ffmpeg {c:.6} < 0.999");
181 }
182}
183
184/// Core-only decoding of the implicit HE-AAC stream: every frame carries an SBR
185/// payload, and `core_only` must skip it, so the output stays at the 22050 Hz core
186/// rate with 1024 samples per channel per frame. Before the switch existed, a
187/// core-only measurement built with `with_config` re-armed implicit SBR and got the
188/// doubled-rate full chain back, labelled as core.
189#[test]
190fn core_only_decode_of_implicit_he_aac_stays_at_core_rate() {
191 let path = implicit_fixture();
192 if !require_fixture(&path) {
193 return;
194 }
195 let data = std::fs::read(&path).expect("fixture readable");
196 let mut decoder = AacDecoder::new().core_only();
197 let mut frames = 0usize;
198 let mut at = 0usize;
199 while at + 7 <= data.len() {
200 let header = ec_aac::parse_adts(&data[at..]).expect("adts header");
201 let end = (at + header.frame_length).min(data.len());
202 let frame = decoder.decode(&data[at..end], None).expect("frame decodes");
203 assert_eq!(
204 frame.sample_rate, 22_050,
205 "frame {frames} must stay at the core rate"
206 );
207 assert_eq!(
208 frame.samples.len(),
209 1024 * usize::from(frame.channels),
210 "frame {frames}: one core frame of 1024 samples per channel"
211 );
212 frames += 1;
213 at = end;
214 }
215 assert!(frames > 0, "fixture has frames");
216 assert!(
217 !decoder.sbr_implicit(),
218 "core-only must never arm implicit SBR"
219 );
220 assert_eq!(decoder.sbr_support(), SbrSupport::NotSignalled);
221 assert_eq!(decoder.output_sample_rate(), Some(22_050));
222}