forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

audio_multi.rs375 lines, 14.8 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 ec_core::Demuxer as _;
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.
108/// The stream of an mp4's first AAC track, as `ec-mp4` numbers it.
109fn aac_stream(reader: &ec_mp4::Mp4Demuxer<BufReader<File>>) -> u32 {
110 reader
111 .streams()
112 .iter()
113 .find(|s| s.params.codec == ec_core::CodecId::Aac)
114 .expect("an AAC track")
115 .index
116}
117
118fn raw(name: &str, ids: impl IntoIterator<Item = u32>) -> Vec<Vec<u8>> {
119 let file = File::open(asset(name)).unwrap();
120 let mut reader = ec_mp4::Mp4Demuxer::new(BufReader::new(file)).unwrap();
121 let stream = aac_stream(&reader);
122 ids.into_iter()
123 .map(|id| {
124 reader
125 .read_sample(stream, id as usize - 1)
126 .unwrap_or_else(|e| panic!("no sample {id} in {name}: {e:?}"))
127 .data
128 .to_vec()
129 })
130 .collect()
131}
132
133fn assert_same_bytes(got: &[AacPacket], want: &[Vec<u8>], what: &str) {
134 assert_eq!(got.len(), want.len(), "{what}: packet count");
135 for (i, (p, w)) in got.iter().zip(want).enumerate() {
136 assert_eq!(&p.bytes, w, "{what}: packet {i} ({} bytes)", p.bytes.len());
137 }
138}
139
140fn copy(segs: &[(usize, f64, f64)]) -> Vec<AacPacket> {
141 AudioSession::copy_multi_segments(&sources(), &named(segs))
142 .expect("copy")
143 .expect("the first source has an audio track")
144 .1
145}
146
147#[test]
148fn two_sources_join_without_a_gap() {
149 let (got, first, chunks) = multi(&[(0, 1.0, 2.0), (1, 0.0, 1.0)]);
150 // `drain` already proved every chunk butts against the previous one, so a
151 // full-length run is a joint with no gap and no overlap.
152 assert_eq!(first, RATE, "numbering starts at the first segment's start");
153 assert_eq!(
154 got.len() as u64 / CHANNELS as u64,
155 2 * RATE,
156 "{chunks} chunks"
157 );
158
159 let half = RATE as usize * CHANNELS;
160 assert_close(&got[..half], &window("test_av.mp4", 1.0, RATE), "source 0");
161 assert_close(&got[half..], &window("test_av2.mp4", 0.0, RATE), "source 1");
162
163 // And the two halves are audibly different files, not the same one twice:
164 // an octave-and-a-fifth apart, 440 -> 660 Hz.
165 let (c0, c1) = (cycles(&got[..half]), cycles(&got[half..]));
166 eprintln!("cycles: {c0} then {c1}");
167 assert!(
168 (c1 as f64 / c0 as f64 - 1.5).abs() < 0.1,
169 "{c0} then {c1} cycles: expected the 440 Hz source then the 660 Hz one"
170 );
171}
172
173#[test]
174fn each_source_ends_where_its_own_track_does() {
175 // test_av2 is 4 s: the ask runs a second past it and must simply stop there,
176 // then the next segment continues the numbering (`drain` checks that).
177 let (got, first, _) = multi(&[(1, 3.5, 5.0), (0, 0.0, 0.5)]);
178 assert_eq!(first, 3 * RATE + RATE / 2);
179 let frames = got.len() as u64 / CHANNELS as u64;
180 assert!(
181 (RATE..=RATE + PACKET).contains(&frames),
182 "{frames} frames for 0.5 s of a 4 s source plus 0.5 s of the next \
183 (+0..={PACKET} tail padding)"
184 );
185 let tail = got.len() - RATE as usize / 2 * CHANNELS;
186 assert_close(
187 &got[tail..],
188 &window("test_av.mp4", 0.0, RATE / 2),
189 "back to source 0",
190 );
191}
192
193#[test]
194fn probe_reads_the_import_policy_fields() {
195 let av = AudioSession::probe(asset("test_av.mp4"), 0)
196 .expect("probe")
197 .expect("test_av.mp4 has audio");
198 assert_eq!(av.channels, 2);
199 assert_eq!(av.sample_rate, RATE as u32);
200 assert_eq!(
201 AudioSession::probe(asset("test_av2.mp4"), 0)
202 .unwrap()
203 .unwrap(),
204 av,
205 "the fixtures are the matching pair import must accept"
206 );
207 for silent in ["test_baseline.mp4", "test_mismatch.mp4"] {
208 assert!(
209 AudioSession::probe(asset(silent), 0).unwrap().is_none(),
210 "{silent} has no audio track"
211 );
212 }
213}
214
215#[test]
216fn one_rounding_debt_is_carried_across_the_source_joins() {
217 // A second is 43.07 packets, so seven seconds copy 43 each and owe 68
218 // samples apiece; the eighth crosses half a packet and copies 44 (the unit
219 // test `packet_run_rounds_against_the_running_debt` pins that arithmetic).
220 // Per segment rounding would copy 43 eight times and start drifting out of
221 // sync — and every one of these joins is a *source* join.
222 let segs: Vec<_> = (0..8).map(|i| (i % 2, 0.0, 1.0)).collect();
223 let packets = copy(&segs);
224 assert_eq!(
225 packets.len(),
226 1 + 7 * 43 + 44,
227 "priming packet + seven seconds owing 68 each + the eighth repaying"
228 );
229 let audible = (packets.len() as u64 - 1) * PACKET;
230 assert!(
231 (audible as i64 - 8 * RATE as i64).unsigned_abs() < PACKET,
232 "{audible} samples for 8 s over seven source joins"
233 );
234}
235
236#[test]
237fn the_join_carries_no_second_priming_packet() {
238 let packets = copy(&[(0, 0.0, 1.0), (1, 0.0, 1.0)]);
239 // Source 1 is the last segment, so its run rounds up (`packet_run_last`):
240 // 43.13 packets owed become 44, one packet past the second asked for.
241 let split = 1 + 43;
242 assert_eq!(packets.len(), split + 44);
243 for p in &packets {
244 assert_eq!(p.samples as u64, PACKET, "AAC-LC packets are 1024 frames");
245 }
246 // Source 0 from id 1 — its own priming packet, the one the reader drops.
247 assert_same_bytes(&packets[..split], &raw("test_av.mp4", 1..=44), "source 0");
248 // Source 1 from id 2: 0.0 s is media 1024 (its priming), which packet 2
249 // holds. Starting at id 1 here would insert a packet the reader keeps.
250 assert_same_bytes(
251 &packets[split..],
252 &raw("test_av2.mp4", 2..46),
253 "source 1 at the join",
254 );
255}
256
257#[test]
258fn a_source_that_disagrees_on_layout_is_refused() {
259 // Import refuses these up front (one output device, one *layout*); the copy
260 // and the decode paths refuse them again rather than mislabel one esds for
261 // two different tracks. The decode path conforms a source the timeline can
262 // carry (c871d71 let a mono source up-mix, DEBT #46; ceddd4c before it
263 // conformed the rate; 768f7c0 downmixes a stereo source on a mono timeline).
264 // Stream 1 of the multi-audio fixture
265 // is the shape that stopped being a refusal: 22.05 kHz mono against a
266 // 44.1 kHz stereo timeline. The decode path widens and resamples it; the
267 // copy path still refuses it, because copied packets can be neither
268 // widened nor resampled and one esds cannot declare two tracks.
269 let mono = [(asset("test_av.mp4"), 0), (asset("test_multiaudio.mp4"), 1)];
270 let segs = [(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)];
271 let msg = AudioSession::copy_multi_streams(&mono, &segs)
272 .err()
273 .expect("copied packets cannot be widened or resampled")
274 .to_string();
275 assert!(msg.contains("source 1"), "{msg}");
276 // (`.expect` twice: neither Ok payload is `Debug`.)
277 let (_, rx) = AudioSession::open_multi_streams(&mono, &segs)
278 .expect("a mono source at another rate is conformed, not refused")
279 .expect("the first source has an audio track");
280 let (samples, _, _) = drain(rx);
281 let frames = samples.len() / CHANNELS;
282 assert!(
283 (frames as i64 - 2 * RATE as i64).unsigned_abs() < PACKET,
284 "{frames} frames for two seconds"
285 );
286 assert!(samples.iter().any(|s| *s != 0.0), "the widened stream plays");
287
288 // Stereo after a mono first source (`test_audio_only` is 44.1 kHz *mono* --
289 // no rate in the way, only the width). The copy path still refuses, in
290 // words that name the source: copied packets cannot be remixed. The decode
291 // path no longer folds the stereo source down to the first clip's mono: the
292 // timeline is as wide as its widest source (the mono one is widened into
293 // both channels), so the mix is stereo and the stereo source is kept.
294 let wide = [(asset("test_audio_only.mp4"), 0), (asset("test_av.mp4"), 0)];
295 let msg = AudioSession::copy_multi_streams(&wide, &segs)
296 .err()
297 .expect("copied packets cannot be remixed")
298 .to_string();
299 assert!(msg.contains("source 1"), "{msg}");
300 let (meta, rx) = AudioSession::open_multi_streams(&wide, &segs)
301 .expect("a stereo source after a mono one is conformed, not refused")
302 .expect("the first source has an audio track");
303 assert_eq!(meta.channels, 2, "the timeline is as wide as its widest source");
304 // Interleaved stereo: `start_sample` counts frames, so `drain` applies and
305 // checks the contiguity itself.
306 let (samples, _, _) = drain(rx);
307 let frames = samples.len() / CHANNELS;
308 assert!(
309 (frames as i64 - 2 * RATE as i64).unsigned_abs() < PACKET,
310 "{frames} stereo frames for two seconds"
311 );
312 assert!(samples.iter().any(|s| *s != 0.0), "the widened stream plays");
313 // An out-of-range index is an error, not a panic.
314 assert!(AudioSession::copy_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err());
315 assert!(AudioSession::open_multi_segments(&sources(), &[(Some(2), 0.0, 1.0)]).is_err());
316}
317
318/// A source with **no** track is not a refusal at all: its segments are the
319/// same silence a gap is, in both paths. That is what a silent clip on an audio
320/// lane is -- a picture over a hole -- and the timeline lets one in
321/// (`PlaybackSession::import`) precisely because these two agree here.
322#[test]
323fn a_silent_source_is_silence_and_not_a_refusal() {
324 let mixed = [asset("test_av.mp4"), asset("test_mismatch.mp4")];
325 let segs = [
326 (Some(0), 0.0, 1.0),
327 (Some(1), 0.0, 1.0),
328 (Some(0), 0.0, 1.0),
329 ];
330
331 // Decoded: three seconds, the middle one exact zero, and the chunks still
332 // arrive contiguous (`drain` asserts that), so the clock is fed through it.
333 let (_, rx) = AudioSession::open_multi_segments(&mixed, &segs)
334 .expect("a silent source opens")
335 .expect("the first source has an audio track");
336 let (samples, _, _) = drain(rx);
337 let frames = samples.len() / CHANNELS;
338 assert!(
339 (frames as i64 - 3 * RATE as i64).unsigned_abs() < PACKET,
340 "{frames} frames for three seconds"
341 );
342 let second = |n: usize| {
343 let at = |s: usize| (s * RATE as usize * CHANNELS).min(samples.len());
344 &samples[at(n)..at(n + 1)]
345 };
346 assert!(
347 second(0).iter().any(|s| *s != 0.0),
348 "the first second plays"
349 );
350 assert!(
351 second(1).iter().all(|s| *s == 0.0),
352 "the silent source is exact silence"
353 );
354 assert!(second(2).iter().any(|s| *s != 0.0), "and it comes back");
355
356 // Copied: the same shape in packets, so an mp4 export of that timeline is
357 // as long as the timeline and quiet where the silent clip is.
358 let (params, packets) = AudioSession::copy_multi_segments(&mixed, &segs)
359 .expect("a silent source copies")
360 .expect("the timeline has an audible source");
361 let copied = packets.len() as u64 * PACKET;
362 assert!(
363 (copied as i64 - 3 * RATE as i64).unsigned_abs() < 2 * PACKET,
364 "{copied} samples for three seconds, priming included"
365 );
366 assert_eq!(
367 params.sample_rate, RATE as u32,
368 "the audible source's track"
369 );
370 let silence: Vec<_> = packets[44..44 + 43].iter().map(|p| &p.bytes).collect();
371 assert!(
372 silence.iter().all(|b| b.len() <= 7),
373 "the hole is written as the hand-made silent packet, not as audio"
374 );
375}