forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBcc667e6Tahinli3 months ago285 commits

audio_decode.rs312 lines, 12.0 KiBHistoryRawDownload
1use std::path::PathBuf;
2use std::time::Instant;
3
4use engine::audio::AudioSession;
5use engine::scratch::Scratch;
6
7const RATE: u32 = 44100;
8const SECONDS: u32 = 5;
9/// One AAC-LC packet; the container's tail padding is not trimmed, so the
10/// decoded length may run up to a frame past the nominal duration.
11const FRAME: i64 = 1024;
12
13fn asset(name: &str) -> PathBuf {
14 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
15 .join("../../assets")
16 .join(name)
17}
18
19/// Sign changes ignoring exact zeros, so the 1 Hz volume pulse touching zero
20/// does not register as a crossing.
21fn zero_crossings(samples: &[f32]) -> usize {
22 let mut crossings = 0;
23 let mut last = 0f32;
24 for &s in samples {
25 if s == 0.0 {
26 continue;
27 }
28 if last != 0.0 && (s > 0.0) != (last > 0.0) {
29 crossings += 1;
30 }
31 last = s;
32 }
33 crossings
34}
35
36#[test]
37fn decodes_av_mp4_audio() {
38 let start = Instant::now();
39 let (meta, rx) = AudioSession::open(asset("test_av.mp4"))
40 .expect("open")
41 .expect("test_av.mp4 has an audio track");
42 assert_eq!((meta.sample_rate, meta.channels), (RATE, 2));
43
44 let mut left = Vec::new();
45 let mut right = Vec::new();
46 let mut next_sample = 0u64;
47 let mut chunks = 0usize;
48 for chunk in rx {
49 // d. no gaps, no overlaps.
50 assert_eq!(chunk.start_sample, next_sample, "chunk {chunks} start");
51 assert!(!chunk.samples.is_empty(), "empty chunk {chunks}");
52 assert_eq!(
53 chunk.samples.len() % 2,
54 0,
55 "partial frame in chunk {chunks}"
56 );
57 next_sample += (chunk.samples.len() / 2) as u64;
58 left.extend(chunk.samples.iter().step_by(2));
59 right.extend(chunk.samples[1..].iter().step_by(2));
60 chunks += 1;
61 }
62 let elapsed = start.elapsed();
63 let frames = left.len();
64 assert!(frames > 0, "no audio decoded");
65
66 // b. ~5 s of audio, priming trimmed, at most a frame of tail padding over.
67 let want = (RATE * SECONDS) as i64;
68 let slack = frames as i64 - want;
69 assert!(
70 (0..=FRAME).contains(&slack),
71 "{frames} frames per channel, want {want} (+0..={FRAME})"
72 );
73 assert_eq!(right.len(), frames, "channel lengths differ");
74
75 // c. channel identity: L is 440 Hz, R is 880 Hz. A swap or a bad interleave
76 // shows up as the wrong crossing count.
77 let secs = frames as f64 / RATE as f64;
78 for (name, samples, hz) in [("left", &left, 440.0), ("right", &right, 880.0)] {
79 let want = 2.0 * hz * secs;
80 let got = zero_crossings(samples) as f64;
81 assert!(
82 (got - want).abs() <= 0.05 * want,
83 "{name}: {got} zero crossings, want {want} +/-5%"
84 );
85 }
86
87 // Priming trimmed: the sine starts at a rising zero crossing, and audio is
88 // present immediately rather than after a silent or garbage run-in.
89 assert!(
90 left[0].abs() < 0.05,
91 "first sample {} not near zero",
92 left[0]
93 );
94 assert!(left[1] > 0.0, "first sine quarter is not rising");
95 let head_peak = left[..FRAME as usize]
96 .iter()
97 .fold(0f32, |m, s| m.max(s.abs()));
98 assert!(head_peak > 0.01, "first frame is silent: peak {head_peak}");
99
100 eprintln!(
101 "{frames} frames/ch in {chunks} chunks, {elapsed:?} ({:?}/packet)",
102 elapsed / chunks as u32
103 );
104}
105
106#[test]
107fn video_only_file_has_no_audio() {
108 assert!(
109 AudioSession::open(asset("test_baseline.mp4"))
110 .expect("open")
111 .is_none()
112 );
113 assert!(
114 AudioSession::unsupported(asset("test_baseline.mp4"))
115 .expect("probe")
116 .is_none(),
117 "a file with no audio track is not a complaint"
118 );
119}
120
121/// Both ends of the AC-3 path decode: the 44.1 kHz **mono** fixture stays the
122/// mono source it is, and the 48 kHz **5.1** one — the shape a BluRay remux has
123/// — arrives as stereo, downmixed by the decoder itself (A/52 §7.8). Both play
124/// their two seconds, at a level that is neither silence nor clipping, and
125/// neither owes the session an excuse.
126#[test]
127fn an_ac3_track_decodes_and_51_comes_down_to_stereo() {
128 for (name, rate, channels) in [("test_ac3.mp4", 44100, 1), ("test_ac3_51.mp4", 48000, 2)] {
129 let path = asset(name);
130 let (meta, rx) = AudioSession::open(&path)
131 .expect("open")
132 .expect("AC-3 decodes now");
133 assert_eq!((meta.sample_rate, meta.channels), (rate, channels), "{name}");
134 let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
135 let secs = (samples.len() / channels as usize) as f64 / f64::from(rate);
136 assert!(
137 (1.9..2.1).contains(&secs),
138 "{name} is two seconds, decoded {secs:.3}s"
139 );
140 // The 440 Hz sine survives at a sane level. The vetting caveat was an
141 // LFE passthrough running hot, which the built-in downmix is what
142 // avoids; this is that level check, and it is also what catches a
143 // downmix that comes out silent.
144 let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>()
145 / samples.len() as f64)
146 .sqrt();
147 assert!(
148 (0.005..0.75).contains(&rms),
149 "{name}: RMS {rms:.6} is not a sine at a sane level"
150 );
151 assert!(
152 samples.iter().all(|s| s.abs() <= 1.0),
153 "{name}: the decode must not leave the device's range"
154 );
155 let session = engine::PlaybackSession::open(&path).expect("open for playback");
156 assert_eq!(
157 session.audio_disabled_reason(),
158 None,
159 "{name}: a track that decodes owes no excuse"
160 );
161 }
162}
163
164/// The same two ends of the AC-3 path, in **Matroska**: a stereo AC-3 track and
165/// a 5.1 E-AC-3 one -- the codec a remux carries and the one the "(AAC only)"
166/// refusal used to fire on -- both come out of the blocks, both arrive as the
167/// stereo the §7.8 downmix hands the timeline, and neither owes the session an
168/// excuse any more.
169#[test]
170fn matroska_ac3_and_eac3_decode_out_of_the_blocks() {
171 for (name, codec) in [("test_ac3.mkv", "ac-3"), ("test_eac3.mkv", "e-ac-3")] {
172 let path = asset(name);
173 let (meta, rx) = AudioSession::open(&path)
174 .expect("open")
175 .expect("Matroska AC-3 decodes now");
176 assert_eq!((meta.sample_rate, meta.channels), (48000, 2), "{name}");
177 let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
178 let secs = (samples.len() / 2) as f64 / 48000.0;
179 assert!(
180 (1.9..2.1).contains(&secs),
181 "{name} is two seconds, decoded {secs:.3}s"
182 );
183 let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>()
184 / samples.len() as f64)
185 .sqrt();
186 assert!(
187 (0.005..0.75).contains(&rms),
188 "{name}: RMS {rms:.6} is not a sine at a sane level"
189 );
190 assert!(
191 samples.iter().all(|s| s.abs() <= 1.0),
192 "{name}: the decode must not leave the device's range"
193 );
194 // The user-facing half: the session comes up with sound and no notice,
195 // and the file's one audio stream is offered by the name it is in.
196 let session = engine::PlaybackSession::open(&path).expect("open for playback");
197 assert_eq!(
198 session.audio_disabled_reason(),
199 None,
200 "{name}: a track that decodes owes no excuse"
201 );
202 let streams = AudioSession::probe_streams(&path).expect("streams");
203 assert_eq!(streams.len(), 1, "{name}: one audio track, one row");
204 assert_eq!(streams[0].codec, codec, "{name}");
205 assert!(streams[0].decodable, "{name}");
206 assert_eq!(
207 AudioSession::unsupported(&path).expect("unsupported"),
208 None,
209 "{name}: nothing to excuse when it plays"
210 );
211 }
212 // The invariant, stated as an assert: the AAC track of a Matroska file is
213 // still symphonia's, listed and decoded exactly as it was.
214 let streams = AudioSession::probe_streams(asset("test_av1.mkv")).expect("streams");
215 assert_eq!(streams.len(), 1);
216 assert_eq!(streams[0].codec, "aac", "AAC in an mkv is untouched by this");
217 assert!(
218 AudioSession::open(asset("test_av1.mkv"))
219 .expect("open")
220 .is_some(),
221 "AAC in an mkv still decodes"
222 );
223}
224
225/// A seek into a Matroska AC-3 track: Matroska indexes no samples, so the block
226/// a decode starts on is found by the blocks' own timestamps -- and getting that
227/// wrong is a tail that is the wrong length or lands in the wrong place. It is
228/// the same check `audio_seek` makes of the mp4 path, on the container that has
229/// no sample table.
230#[test]
231fn a_seek_into_a_matroska_ac3_track_is_the_tail_of_a_full_run() {
232 let path = asset("test_eac3.mkv");
233 let full: Vec<f32> = AudioSession::open(&path)
234 .expect("open")
235 .expect("audio")
236 .1
237 .into_iter()
238 .flat_map(|c| c.samples)
239 .collect();
240 let start = 48_000u64; // one second in, in frames per channel
241 let mut next = start;
242 let mut tail = Vec::new();
243 for chunk in AudioSession::open_at(&path, 1.0).expect("open").expect("audio").1 {
244 assert_eq!(chunk.start_sample, next, "a seeked run numbers from the seek");
245 next += (chunk.samples.len() / 2) as u64;
246 tail.extend(chunk.samples);
247 }
248 let want = &full[start as usize * 2..];
249 assert_eq!(tail.len(), want.len(), "the seeked run is a different length");
250 let diff = tail
251 .iter()
252 .zip(want)
253 .map(|(a, b)| (a - b).abs())
254 .fold(0.0f32, f32::max);
255 // One syncframe of pre-roll is what the 256-sample overlap-add needs, so
256 // this is exact in practice; the tolerance is for a decoder that carries
257 // more state than the frame before, not for a wrong block.
258 assert!(diff < 1e-3, "max abs diff {diff} after the seek");
259}
260
261/// An AC-3 syncframe is not something an `mp4a` sample table holds, so the
262/// *copy* path names it and hands the export on to the re-encode (which decodes
263/// this very source: the downmix above is what it encodes). Named either way --
264/// never a silent export.
265#[test]
266fn an_ac3_source_refuses_an_mp4_audio_copy() {
267 let Err(err) = AudioSession::copy_segments(asset("test_ac3.mp4"), &[(0.0, 1.0)]) else {
268 panic!("AC-3 cannot become an mp4a track");
269 };
270 let err = err.to_string();
271 assert!(
272 err.contains("needs AAC in an mp4") && err.contains("AC-3"),
273 "unhelpful refusal: {err}"
274 );
275}
276
277/// The two things a Matroska file with no *readable* sound can be, told apart:
278/// a file with no audio track is the silent source it says it is, and a file
279/// whose audio will not open at all is an error. They used to be the same
280/// answer -- silence -- so a broken track played and exported as a hole with
281/// nothing but an `eprintln` to say why.
282#[test]
283fn a_matroska_with_no_track_is_silent_and_a_broken_one_is_an_error() {
284 // No audio track at all: a picture and two subtitle tracks. Silent, and the
285 // stream picker offers nothing rather than refusing the file.
286 let subs = asset("test_subs.mkv");
287 assert!(
288 AudioSession::probe(&subs, 0)
289 .expect("no audio is not an error")
290 .is_none(),
291 "an mkv with no audio track is a silent source"
292 );
293 assert!(AudioSession::probe_streams(&subs).expect("list").is_empty());
294 assert!(
295 AudioSession::open(&subs).expect("open").is_none(),
296 "no sound"
297 );
298
299 // ...and a file that will not parse at all, under the same extension: an
300 // `Err` a front-end can show, not a silent import.
301 let broken = Scratch::file("ve_broken", "mkv");
302 std::fs::write(&broken, b"\x1a\x45\xdf\xa3not a matroska file at all").expect("write");
303 let err = AudioSession::probe(&broken, 0)
304 .expect_err("a broken file must not pass for a silent one")
305 .to_string();
306 assert!(!err.is_empty(), "the refusal says something");
307 assert!(
308 AudioSession::probe_streams(&broken).is_err(),
309 "and so does the listing"
310 );
311 std::fs::remove_file(&broken).unwrap();
312}