forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB8c7bf80Tahinli3 months ago114 commits

audio_multi.rs272 lines, 10.0 KiBHistoryRawDownload
1//! Multi-source audio: two files poured into one stream. A source join has to
2//! behave exactly like a cut inside one file — no gap in `start_sample`, no
3//! second priming packet, one shared rounding debt — while each source still
4//! contributes its own content, its own packet table and its own length.
5
6use std::fs::File;
7use std::io::BufReader;
8use std::path::PathBuf;
9use std::sync::mpsc::Receiver;
10
11use engine::audio::{AacPacket, AudioChunk, AudioSession};
12use mp4::{MediaType, Mp4Reader};
13
14const RATE: u64 = 44100;
15const CHANNELS: usize = 2;
16/// Frames per channel in one AAC-LC packet.
17const PACKET: u64 = 1024;
18
19fn asset(name: &str) -> PathBuf {
20 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
21 .join("../../assets")
22 .join(name)
23}
24
25/// The import-policy pair: same 1280x720@30 / AAC-LC 44.1k stereo, plainly
26/// different content (440/880 Hz vs 660/1320 Hz, 5 s vs 4 s).
27fn sources() -> Vec<PathBuf> {
28 vec![asset("test_av.mp4"), asset("test_av2.mp4")]
29}
30
31/// Drains a session flat, asserting chunks are contiguous, and reports the
32/// first chunk's `start_sample` plus how many chunks arrived.
33/// Every segment names a source: these tests are about joins between files,
34/// not about gaps (which name none).
35fn named(segs: &[(usize, f64, f64)]) -> Vec<(Option<usize>, f64, f64)> {
36 segs.iter().map(|&(s, a, b)| (Some(s), a, b)).collect()
37}
38
39fn drain(rx: Receiver<AudioChunk>) -> (Vec<f32>, u64, usize) {
40 let (mut samples, mut first, mut chunks) = (Vec::new(), None, 0usize);
41 for AudioChunk {
42 start_sample,
43 samples: s,
44 } in rx
45 {
46 assert!(!s.is_empty(), "empty chunk {chunks}");
47 let want = first.unwrap_or(start_sample) + (samples.len() / CHANNELS) as u64;
48 assert_eq!(start_sample, want, "gap or overlap before chunk {chunks}");
49 first.get_or_insert(start_sample);
50 samples.extend(s);
51 chunks += 1;
52 }
53 (samples, first.unwrap_or(0), chunks)
54}
55
56fn multi(segs: &[(usize, f64, f64)]) -> (Vec<f32>, u64, usize) {
57 let segs = named(segs);
58 let (_, rx) = AudioSession::open_multi_segments(&sources(), &segs)
59 .expect("open")
60 .expect("the first source has an audio track");
61 drain(rx)
62}
63
64/// The first `frames` per channel of a plain single-file `open_at(start)`.
65fn window(name: &str, start: f64, frames: u64) -> Vec<f32> {
66 let (_, rx) = AudioSession::open_at(asset(name), start).unwrap().unwrap();
67 let (mut samples, _, _) = drain(rx);
68 assert!(samples.len() >= frames as usize * CHANNELS, "short window");
69 samples.truncate(frames as usize * CHANNELS);
70 samples
71}
72
73/// Perceptual noise substitution reseeds per decoder, so a segment can never be
74/// promised bit-exact against another run (engine/src/audio.rs docs, ledger).
75fn assert_close(got: &[f32], want: &[f32], what: &str) {
76 assert_eq!(got.len(), want.len(), "{what}: length");
77 let (diff, at) = got
78 .iter()
79 .zip(want)
80 .enumerate()
81 .map(|(i, (x, y))| ((x - y).abs(), i))
82 .fold((0.0f32, 0), |m, d| if d.0 > m.0 { d } else { m });
83 eprintln!(
84 "{what}: max abs diff {diff:e} at sample {at} of {}",
85 got.len()
86 );
87 assert!(diff < 1e-3, "{what}: max abs diff {diff} at sample {at}");
88}
89
90/// Cycles of the left channel: rising edges through a deadband, so the coding
91/// noise around the fixture's 1 Hz volume dip is not counted as a cycle. One
92/// second of the 440 Hz source reads ~440, of the 660 Hz one ~660.
93fn cycles(samples: &[f32]) -> usize {
94 let (mut n, mut high) = (0usize, false);
95 for &s in samples.iter().step_by(CHANNELS) {
96 if !high && s > 0.05 {
97 high = true;
98 n += 1;
99 } else if high && s < -0.05 {
100 high = false;
101 }
102 }
103 n
104}
105
106/// The AAC sample bytes for 1-based `ids` of `name`, read straight from the
107/// demuxer — the reference a copy must match byte for byte.
108fn raw(name: &str, ids: impl IntoIterator<Item = u32>) -> Vec<Vec<u8>> {
109 let file = File::open(asset(name)).unwrap();
110 let size = file.metadata().unwrap().len();
111 let mut reader = Mp4Reader::read_header(BufReader::new(file), size).unwrap();
112 let track = reader
113 .tracks()
114 .values()
115 .find(|t| matches!(t.media_type(), Ok(MediaType::AAC)))
116 .unwrap()
117 .track_id();
118 ids.into_iter()
119 .map(|id| {
120 reader
121 .read_sample(track, id)
122 .unwrap()
123 .unwrap_or_else(|| panic!("no sample {id} in {name}"))
124 .bytes
125 .to_vec()
126 })
127 .collect()
128}
129
130fn assert_same_bytes(got: &[AacPacket], want: &[Vec<u8>], what: &str) {
131 assert_eq!(got.len(), want.len(), "{what}: packet count");
132 for (i, (p, w)) in got.iter().zip(want).enumerate() {
133 assert_eq!(&p.bytes, w, "{what}: packet {i} ({} bytes)", p.bytes.len());
134 }
135}
136
137fn copy(segs: &[(usize, f64, f64)]) -> Vec<AacPacket> {
138 AudioSession::copy_multi_segments(&sources(), &named(segs))
139 .expect("copy")
140 .expect("the first source has an audio track")
141 .1
142}
143
144#[test]
145fn two_sources_join_without_a_gap() {
146 let (got, first, chunks) = multi(&[(0, 1.0, 2.0), (1, 0.0, 1.0)]);
147 // `drain` already proved every chunk butts against the previous one, so a
148 // full-length run is a joint with no gap and no overlap.
149 assert_eq!(first, RATE, "numbering starts at the first segment's start");
150 assert_eq!(
151 got.len() as u64 / CHANNELS as u64,
152 2 * RATE,
153 "{chunks} chunks"
154 );
155
156 let half = RATE as usize * CHANNELS;
157 assert_close(&got[..half], &window("test_av.mp4", 1.0, RATE), "source 0");
158 assert_close(&got[half..], &window("test_av2.mp4", 0.0, RATE), "source 1");
159
160 // And the two halves are audibly different files, not the same one twice:
161 // an octave-and-a-fifth apart, 440 -> 660 Hz.
162 let (c0, c1) = (cycles(&got[..half]), cycles(&got[half..]));
163 eprintln!("cycles: {c0} then {c1}");
164 assert!(
165 (c1 as f64 / c0 as f64 - 1.5).abs() < 0.1,
166 "{c0} then {c1} cycles: expected the 440 Hz source then the 660 Hz one"
167 );
168}
169
170#[test]
171fn each_source_ends_where_its_own_track_does() {
172 // test_av2 is 4 s: the ask runs a second past it and must simply stop there,
173 // then the next segment continues the numbering (`drain` checks that).
174 let (got, first, _) = multi(&[(1, 3.5, 5.0), (0, 0.0, 0.5)]);
175 assert_eq!(first, 3 * RATE + RATE / 2);
176 let frames = got.len() as u64 / CHANNELS as u64;
177 assert!(
178 (RATE..=RATE + PACKET).contains(&frames),
179 "{frames} frames for 0.5 s of a 4 s source plus 0.5 s of the next \
180 (+0..={PACKET} tail padding)"
181 );
182 let tail = got.len() - RATE as usize / 2 * CHANNELS;
183 assert_close(
184 &got[tail..],
185 &window("test_av.mp4", 0.0, RATE / 2),
186 "back to source 0",
187 );
188}
189
190#[test]
191fn probe_reads_the_import_policy_fields() {
192 let av = AudioSession::probe(asset("test_av.mp4"), 0)
193 .expect("probe")
194 .expect("test_av.mp4 has audio");
195 assert_eq!(av.channels, 2);
196 assert_eq!(av.sample_rate, RATE as u32);
197 assert_eq!(
198 AudioSession::probe(asset("test_av2.mp4"), 0)
199 .unwrap()
200 .unwrap(),
201 av,
202 "the fixtures are the matching pair import must accept"
203 );
204 for silent in ["test_baseline.mp4", "test_mismatch.mp4"] {
205 assert!(
206 AudioSession::probe(asset(silent), 0).unwrap().is_none(),
207 "{silent} has no audio track"
208 );
209 }
210}
211
212#[test]
213fn one_rounding_debt_is_carried_across_the_source_joins() {
214 // A second is 43.07 packets, so seven seconds copy 43 each and owe 68
215 // samples apiece; the eighth crosses half a packet and copies 44 (the unit
216 // test `packet_run_rounds_against_the_running_debt` pins that arithmetic).
217 // Per segment rounding would copy 43 eight times and start drifting out of
218 // sync — and every one of these joins is a *source* join.
219 let segs: Vec<_> = (0..8).map(|i| (i % 2, 0.0, 1.0)).collect();
220 let packets = copy(&segs);
221 assert_eq!(
222 packets.len(),
223 1 + 7 * 43 + 44,
224 "priming packet + seven seconds owing 68 each + the eighth repaying"
225 );
226 let audible = (packets.len() as u64 - 1) * PACKET;
227 assert!(
228 (audible as i64 - 8 * RATE as i64).unsigned_abs() < PACKET,
229 "{audible} samples for 8 s over seven source joins"
230 );
231}
232
233#[test]
234fn the_join_carries_no_second_priming_packet() {
235 let packets = copy(&[(0, 0.0, 1.0), (1, 0.0, 1.0)]);
236 let split = 1 + 43;
237 assert_eq!(packets.len(), split + 43);
238 for p in &packets {
239 assert_eq!(p.samples as u64, PACKET, "AAC-LC packets are 1024 frames");
240 }
241 // Source 0 from id 1 — its own priming packet, the one the reader drops.
242 assert_same_bytes(&packets[..split], &raw("test_av.mp4", 1..=44), "source 0");
243 // Source 1 from id 2: 0.0 s is media 1024 (its priming), which packet 2
244 // holds. Starting at id 1 here would insert a packet the reader keeps.
245 assert_same_bytes(
246 &packets[split..],
247 &raw("test_av2.mp4", 2..45),
248 "source 1 at the join",
249 );
250}
251
252#[test]
253fn a_source_without_the_timeline_audio_is_refused() {
254 // Import refuses these up front (same rate, same layout, or both silent);
255 // the copy and the decode paths refuse them again rather than mislabel one
256 // esds for two different tracks.
257 let mixed = [asset("test_av.mp4"), asset("test_mismatch.mp4")];
258 let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)];
259 // (`.err()`, not `unwrap_err`: neither Ok payload is `Debug`.)
260 for e in [
261 AudioSession::copy_multi_segments(&mixed, &segs).err(),
262 AudioSession::open_multi_segments(&mixed, &segs).err(),
263 ]
264 .map(|e| e.expect("a source with no audio track must be refused"))
265 {
266 let msg = e.to_string();
267 assert!(msg.contains("source 1"), "{msg}");
268 }
269 // An out-of-range index is an error, not a panic.
270 assert!(AudioSession::copy_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err());
271 assert!(AudioSession::open_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err());
272}