forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBa3e9dc2Tahinli3 months ago134 commits

audio_decode.rs175 lines, 6.1 KiBHistoryRawDownload
1use std::path::PathBuf;
2use std::time::Instant;
3
4use engine::audio::AudioSession;
5
6const RATE: u32 = 44100;
7const SECONDS: u32 = 5;
8/// One AAC-LC packet; the container's tail padding is not trimmed, so the
9/// decoded length may run up to a frame past the nominal duration.
10const FRAME: i64 = 1024;
11
12fn asset(name: &str) -> PathBuf {
13 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
14 .join("../../assets")
15 .join(name)
16}
17
18/// Sign changes ignoring exact zeros, so the 1 Hz volume pulse touching zero
19/// does not register as a crossing.
20fn zero_crossings(samples: &[f32]) -> usize {
21 let mut crossings = 0;
22 let mut last = 0f32;
23 for &s in samples {
24 if s == 0.0 {
25 continue;
26 }
27 if last != 0.0 && (s > 0.0) != (last > 0.0) {
28 crossings += 1;
29 }
30 last = s;
31 }
32 crossings
33}
34
35#[test]
36fn decodes_av_mp4_audio() {
37 let start = Instant::now();
38 let (meta, rx) = AudioSession::open(asset("test_av.mp4"))
39 .expect("open")
40 .expect("test_av.mp4 has an audio track");
41 assert_eq!((meta.sample_rate, meta.channels), (RATE, 2));
42
43 let mut left = Vec::new();
44 let mut right = Vec::new();
45 let mut next_sample = 0u64;
46 let mut chunks = 0usize;
47 for chunk in rx {
48 // d. no gaps, no overlaps.
49 assert_eq!(chunk.start_sample, next_sample, "chunk {chunks} start");
50 assert!(!chunk.samples.is_empty(), "empty chunk {chunks}");
51 assert_eq!(
52 chunk.samples.len() % 2,
53 0,
54 "partial frame in chunk {chunks}"
55 );
56 next_sample += (chunk.samples.len() / 2) as u64;
57 left.extend(chunk.samples.iter().step_by(2));
58 right.extend(chunk.samples[1..].iter().step_by(2));
59 chunks += 1;
60 }
61 let elapsed = start.elapsed();
62 let frames = left.len();
63 assert!(frames > 0, "no audio decoded");
64
65 // b. ~5 s of audio, priming trimmed, at most a frame of tail padding over.
66 let want = (RATE * SECONDS) as i64;
67 let slack = frames as i64 - want;
68 assert!(
69 (0..=FRAME).contains(&slack),
70 "{frames} frames per channel, want {want} (+0..={FRAME})"
71 );
72 assert_eq!(right.len(), frames, "channel lengths differ");
73
74 // c. channel identity: L is 440 Hz, R is 880 Hz. A swap or a bad interleave
75 // shows up as the wrong crossing count.
76 let secs = frames as f64 / RATE as f64;
77 for (name, samples, hz) in [("left", &left, 440.0), ("right", &right, 880.0)] {
78 let want = 2.0 * hz * secs;
79 let got = zero_crossings(samples) as f64;
80 assert!(
81 (got - want).abs() <= 0.05 * want,
82 "{name}: {got} zero crossings, want {want} +/-5%"
83 );
84 }
85
86 // Priming trimmed: the sine starts at a rising zero crossing, and audio is
87 // present immediately rather than after a silent or garbage run-in.
88 assert!(
89 left[0].abs() < 0.05,
90 "first sample {} not near zero",
91 left[0]
92 );
93 assert!(left[1] > 0.0, "first sine quarter is not rising");
94 let head_peak = left[..FRAME as usize]
95 .iter()
96 .fold(0f32, |m, s| m.max(s.abs()));
97 assert!(head_peak > 0.01, "first frame is silent: peak {head_peak}");
98
99 eprintln!(
100 "{frames} frames/ch in {chunks} chunks, {elapsed:?} ({:?}/packet)",
101 elapsed / chunks as u32
102 );
103}
104
105#[test]
106fn video_only_file_has_no_audio() {
107 assert!(
108 AudioSession::open(asset("test_baseline.mp4"))
109 .expect("open")
110 .is_none()
111 );
112 assert!(
113 AudioSession::unsupported(asset("test_baseline.mp4"))
114 .expect("probe")
115 .is_none(),
116 "a file with no audio track is not a complaint"
117 );
118}
119
120/// Both ends of the AC-3 path decode: the 44.1 kHz **mono** fixture stays the
121/// mono source it is, and the 48 kHz **5.1** one — the shape a BluRay remux has
122/// — arrives as stereo, downmixed by the decoder itself (A/52 §7.8). Both play
123/// their two seconds, at a level that is neither silence nor clipping, and
124/// neither owes the session an excuse.
125#[test]
126fn an_ac3_track_decodes_and_51_comes_down_to_stereo() {
127 for (name, rate, channels) in [("test_ac3.mp4", 44100, 1), ("test_ac3_51.mp4", 48000, 2)] {
128 let path = asset(name);
129 let (meta, rx) = AudioSession::open(&path)
130 .expect("open")
131 .expect("AC-3 decodes now");
132 assert_eq!((meta.sample_rate, meta.channels), (rate, channels), "{name}");
133 let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
134 let secs = (samples.len() / channels as usize) as f64 / f64::from(rate);
135 assert!(
136 (1.9..2.1).contains(&secs),
137 "{name} is two seconds, decoded {secs:.3}s"
138 );
139 // The 440 Hz sine survives at a sane level. The vetting caveat was an
140 // LFE passthrough running hot, which the built-in downmix is what
141 // avoids; this is that level check, and it is also what catches a
142 // downmix that comes out silent.
143 let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>()
144 / samples.len() as f64)
145 .sqrt();
146 assert!(
147 (0.005..0.75).contains(&rms),
148 "{name}: RMS {rms:.6} is not a sine at a sane level"
149 );
150 assert!(
151 samples.iter().all(|s| s.abs() <= 1.0),
152 "{name}: the decode must not leave the device's range"
153 );
154 let session = engine::PlaybackSession::open(&path).expect("open for playback");
155 assert_eq!(
156 session.audio_disabled_reason(),
157 None,
158 "{name}: a track that decodes owes no excuse"
159 );
160 }
161}
162
163/// An AC-3 source cannot be packet-copied into an mp4 -- there is no AAC
164/// encoder here -- and that refusal is named, never a silent silent export.
165#[test]
166fn an_ac3_source_refuses_an_mp4_audio_copy() {
167 let Err(err) = AudioSession::copy_segments(asset("test_ac3.mp4"), &[(0.0, 1.0)]) else {
168 panic!("AC-3 cannot become an mp4a track");
169 };
170 let err = err.to_string();
171 assert!(
172 err.contains("needs AAC audio") && err.contains("AC-3"),
173 "unhelpful refusal: {err}"
174 );
175}