forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

audio_segments.rs259 lines, 9.7 KiBHistoryRawDownload
1//! `AudioSession::open_segments` must pour source windows back to back: each
2//! segment equal to the matching window of a plain `open_at`, `start_sample`
3//! continuous across the join, and the trims exact down to a sub-packet clip.
4
5use std::path::PathBuf;
6use std::sync::mpsc::Receiver;
7
8use engine::audio::{AudioChunk, AudioSession};
9
10const RATE: u64 = 44100;
11const CHANNELS: usize = 2;
12/// One AAC-LC packet, in frames per channel.
13const PACKET: u64 = 1024;
14
15fn asset() -> PathBuf {
16 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4")
17}
18
19/// Drains a session flat, asserting chunks are contiguous, and reports the
20/// first chunk's `start_sample` plus how many chunks arrived.
21fn drain(rx: Receiver<AudioChunk>) -> (Vec<f32>, u64, usize) {
22 let (mut samples, mut first, mut chunks) = (Vec::new(), None, 0usize);
23 for AudioChunk {
24 start_sample,
25 samples: s,
26 } in rx
27 {
28 assert!(!s.is_empty(), "empty chunk {chunks}");
29 let want = first.unwrap_or(start_sample) + (samples.len() / CHANNELS) as u64;
30 assert_eq!(start_sample, want, "gap or overlap before chunk {chunks}");
31 first.get_or_insert(start_sample);
32 samples.extend(s);
33 chunks += 1;
34 }
35 (samples, first.unwrap_or(0), chunks)
36}
37
38fn segments(segs: &[(f64, f64)]) -> (Vec<f32>, u64, usize) {
39 let (_, rx) = AudioSession::open_segments(asset(), segs)
40 .expect("open")
41 .expect("test_av.mp4 has an audio track");
42 drain(rx)
43}
44
45/// The first `frames` per channel of a plain `open_at(start)`.
46fn window(start: f64, frames: u64) -> Vec<f32> {
47 let (_, rx) = AudioSession::open_at(asset(), start).unwrap().unwrap();
48 let (mut samples, _, _) = drain(rx);
49 assert!(samples.len() >= frames as usize * CHANNELS, "short window");
50 samples.truncate(frames as usize * CHANNELS);
51 samples
52}
53
54/// Largest per-sample difference, and where it is.
55fn max_diff(a: &[f32], b: &[f32]) -> (f32, usize) {
56 assert_eq!(a.len(), b.len(), "length mismatch");
57 a.iter()
58 .zip(b)
59 .enumerate()
60 .map(|(i, (x, y))| ((x - y).abs(), i))
61 .fold((0.0, 0), |m, d| if d.0 > m.0 { d } else { m })
62}
63
64/// Perceptual noise substitution reseeds per decoder, so a segment can never be
65/// promised bit-exact against another run (engine/src/audio.rs docs, ledger).
66fn assert_close(got: &[f32], want: &[f32], what: &str) {
67 let (diff, at) = max_diff(got, want);
68 eprintln!(
69 "{what}: max abs diff {diff:e} at sample {at} of {}",
70 got.len()
71 );
72 assert!(diff < 1e-3, "{what}: max abs diff {diff} at sample {at}");
73}
74
75#[test]
76fn two_segments_concat() {
77 let (got, first, chunks) = segments(&[(1.0, 2.0), (3.0, 4.0)]);
78 // `drain` already proved every chunk butts against the previous one, so a
79 // full-length run is a joint with no gap and no overlap.
80 assert_eq!(first, RATE, "numbering starts at the first segment's start");
81 assert_eq!(
82 got.len() as u64 / CHANNELS as u64,
83 2 * RATE,
84 "{chunks} chunks"
85 );
86
87 let want: Vec<f32> = [window(1.0, RATE), window(3.0, RATE)].concat();
88 assert_close(&got, &want, "two segments");
89}
90
91#[test]
92fn tiny_segment_is_one_frame_long() {
93 // A single 30 fps video frame's worth of audio: 1470 samples per channel,
94 // decoded from two packets and trimmed at both.
95 let (got, first, chunks) = segments(&[(1.0, 1.0 + 1.0 / 30.0)]);
96 assert_eq!(first, RATE);
97 assert_eq!(got.len() as u64 / CHANNELS as u64, 1470, "{chunks} chunks");
98 assert_close(&got, &window(1.0, 1470), "one video frame");
99}
100
101#[test]
102fn sub_packet_segment_trims_one_buffer_at_both_ends() {
103 // 441 samples starting 44100 in: with priming that is media 45124..45565,
104 // both inside packet 45 ([45056, 46080)), so the head trim and the tail trim
105 // hit the same decoded buffer.
106 let (got, first, chunks) = segments(&[(1.0, 1.01)]);
107 assert_eq!(first, RATE);
108 assert_eq!(got.len() as u64 / CHANNELS as u64, 441);
109 assert_eq!(chunks, 1, "both trims must land in one decoded buffer");
110 assert_close(&got, &window(1.0, 441), "sub-packet segment");
111}
112
113#[test]
114fn segment_past_the_end_is_capped() {
115 // test_av.mp4 is 5 s: the ask runs 55 s past the track and must simply stop.
116 let (got, first, _) = segments(&[(4.0, 60.0)]);
117 assert_eq!(first, 4 * RATE);
118 let frames = got.len() as u64 / CHANNELS as u64;
119 assert!(
120 (RATE..=RATE + PACKET).contains(&frames),
121 "{frames} frames for the last second (+0..={PACKET} tail padding)"
122 );
123}
124
125#[test]
126fn no_segments_ends_clean() {
127 let (meta, rx) = AudioSession::open_segments(asset(), &[])
128 .expect("open")
129 .expect("test_av.mp4 has an audio track");
130 assert_eq!(meta.sample_rate as u64, RATE);
131 assert_eq!(
132 rx.into_iter().count(),
133 0,
134 "an empty edit list decodes nothing"
135 );
136}
137
138/// A segment naming no source is a gap, and a gap is *synthesised silence* in
139/// the same stream -- real chunks, contiguous with the audible ones (`drain`
140/// asserts that), so the master clock keeps counting through the hole instead
141/// of stalling on it.
142#[test]
143fn a_gap_segment_is_silence_of_its_own_length() {
144 let sources = [asset()];
145 let segs = [
146 (Some(0), 0.0, 0.5),
147 (None, 0.0, 1.0), // one second of hole
148 (Some(0), 2.0, 2.5),
149 ];
150 let (_, rx) = AudioSession::open_multi_segments(&sources, &segs)
151 .expect("open")
152 .expect("test_av.mp4 has an audio track");
153 let (samples, first, _) = drain(rx);
154 assert_eq!(first, 0, "the run still starts at audible zero");
155
156 let frames = samples.len() as u64 / CHANNELS as u64;
157 let want = 2 * RATE / 2 + RATE;
158 assert!(
159 frames.abs_diff(want) <= PACKET,
160 "{frames} frames for {want} asked for: a gap must cost exactly its length"
161 );
162 // The hole itself is digital silence, and what surrounds it is not.
163 let hole = (RATE / 2) as usize * CHANNELS..(RATE / 2 + RATE) as usize * CHANNELS;
164 assert!(
165 samples[hole.clone()].iter().all(|s| *s == 0.0),
166 "the gap must be silent"
167 );
168 assert!(
169 samples[..hole.start].iter().any(|s| s.abs() > 1e-3)
170 && samples[hole.end..].iter().any(|s| s.abs() > 1e-3),
171 "the clips around it must not be"
172 );
173
174 // Nothing but gap is a valid run of silence; the meta still comes from the
175 // source, because that is what the device was opened with.
176 let (meta, rx) = AudioSession::open_multi_segments(&sources, &[(None, 0.0, 0.25)])
177 .expect("open")
178 .expect("meta comes from source 0 even with nothing to decode");
179 assert_eq!(meta.sample_rate as u64, RATE);
180 let (samples, _, _) = drain(rx);
181 assert!(samples.iter().all(|s| *s == 0.0));
182 assert!(
183 (samples.len() as u64 / CHANNELS as u64).abs_diff(RATE / 4) <= PACKET,
184 "quarter second of silence"
185 );
186}
187
188/// The copy side of a gap: a copy never encodes, so the hole is copied
189/// as hand-written silent packets -- real access units, one 1024-frame stts
190/// entry each, the rounding debt carried through them like any other segment.
191/// Every packet after the gap therefore still lands at its timeline position.
192#[test]
193fn a_copied_gap_is_packets_of_hand_written_silence() {
194 let sources = [asset()];
195 let plain = [(Some(0), 0.0, 1.0), (Some(0), 2.0, 3.0)];
196 let gapped = [(Some(0), 0.0, 1.0), (None, 0.0, 1.0), (Some(0), 2.0, 3.0)];
197
198 let (_, without) = AudioSession::copy_multi_segments(&sources, &plain)
199 .unwrap()
200 .unwrap();
201 let (_, with) = AudioSession::copy_multi_segments(&sources, &gapped)
202 .unwrap()
203 .unwrap();
204 let total = |p: &[engine::AacPacket]| p.iter().map(|p| u64::from(p.samples)).sum::<u64>();
205 assert!(
206 with.iter().all(|p| u64::from(p.samples) == PACKET),
207 "gap or not, every AAC-LC packet is 1024 frames"
208 );
209 let gap = total(&with) - total(&without);
210 assert!(
211 gap.abs_diff(RATE) <= PACKET / 2,
212 "the hole is {gap} frames of silence for a second of timeline"
213 );
214 // The audible packets are the same bytes in the same order: the silence was
215 // inserted between them, not spliced through them.
216 let audible: Vec<&Vec<u8>> = with
217 .iter()
218 .map(|p| &p.bytes)
219 .filter(|b| b.len() > 7)
220 .collect();
221 let want: Vec<&Vec<u8>> = without.iter().map(|p| &p.bytes).collect();
222 assert_eq!(audible, want, "not one byte of audio moved");
223 // Stereo silence is the 7-byte block, and it sits where the hole is.
224 let silent = |p: &engine::AacPacket| p.bytes == [0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0E];
225 let run: Vec<usize> = with
226 .iter()
227 .enumerate()
228 .filter(|(_, p)| silent(p))
229 .map(|(i, _)| i)
230 .collect();
231 assert_eq!(
232 run.len() as u64,
233 gap / PACKET,
234 "the gap is that many silent packets"
235 );
236 assert!(
237 run.windows(2).all(|w| w[1] == w[0] + 1) && run[0] > 0,
238 "and they are one interior run, at {run:?}"
239 );
240
241 // A gap at the *head* is packets of its own -- its own length plus the one
242 // more a reader drops as priming. Without that one the drop would come out
243 // of the hole and everything after it would play a packet early.
244 let (_, leading) =
245 AudioSession::copy_multi_segments(&sources, &[(None, 0.0, 0.5), (Some(0), 0.0, 1.0)])
246 .unwrap()
247 .unwrap();
248 let head = leading.iter().take_while(|p| silent(p)).count() as u64;
249 assert!(
250 (head * PACKET).abs_diff(RATE / 2 + PACKET) <= PACKET / 2,
251 "{head} silent packets for half a second of leading hole plus priming"
252 );
253 // ...and only a *leading* hole gets it: the interior one above did not.
254 assert_eq!(
255 run.len() as u64 * PACKET,
256 gap,
257 "an interior gap is its own length exactly"
258 );
259}