forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

audio_streams.rs442 lines, 17.8 KiBHistoryRawDownload
1//! Files carry more than one audio track — a remux has one per language — so
2//! the engine has to *list* them all and open the one it is asked for, instead
3//! of taking whichever AAC track it stumbles on first.
4
5use std::path::PathBuf;
6
7use engine::audio::{AudioSession, StreamInfo};
8use engine::scratch::Scratch;
9
10/// Three audio streams: 0 is AAC 44.1k stereo (440/880 Hz, und), 1 is AAC
11/// 22.05k mono (220 Hz, fra), 2 is AC-3, which we cannot decode.
12/// See `scripts/gen_fixtures.sh`.
13const MULTI: &str = "test_multiaudio.mp4";
14
15/// Two audio streams in **Matroska**, the shape a dual-audio remux has: 0 is
16/// AAC 44.1k stereo 440/880 Hz English, 1 is the same shape at 220/330 Hz
17/// French. See `scripts/gen_fixtures.sh`.
18const MULTI_MKV: &str = "test_multiaudio.mkv";
19
20fn asset(name: &str) -> PathBuf {
21 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
22 .join("../../assets")
23 .join(name)
24}
25
26/// Everything the worker produced for one stream, flat.
27fn decode(name: &str, stream: usize) -> (engine::AudioMeta, Vec<f32>) {
28 let sources = [(asset(name), stream)];
29 let (meta, rx) = AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])
30 .expect("opens")
31 .expect("has audio");
32 let mut samples = Vec::new();
33 for chunk in rx {
34 samples.extend_from_slice(&chunk.samples);
35 }
36 (meta, samples)
37}
38
39/// Sign changes, exact zeros ignored: at one tone per channel this is 2f per
40/// second per channel.
41fn zero_crossings(samples: &[f32]) -> usize {
42 let (mut crossings, mut last) = (0, 0f32);
43 for &s in samples {
44 if s == 0.0 {
45 continue;
46 }
47 if last != 0.0 && (s > 0.0) != (last > 0.0) {
48 crossings += 1;
49 }
50 last = s;
51 }
52 crossings
53}
54
55#[test]
56fn probe_streams_lists_every_audio_track_in_file_order() {
57 let streams = AudioSession::probe_streams(asset(MULTI)).expect("probes");
58 // The bitrates are the encoder's output, and the fixtures are regenerated
59 // with whatever ffmpeg is installed, so each is held to within 5 % of the
60 // value it was last measured at rather than to the exact figure. The rest
61 // of every row is compared exactly below.
62 let mut shape = streams.clone();
63 for (s, want) in shape.iter_mut().zip([128_372u64, 62_612, 193_928]) {
64 let got = s.bitrate.expect("a bitrate");
65 assert!(
66 got.abs_diff(want) * 20 <= want,
67 "stream {}: bitrate {got} is more than 5% from {want}",
68 s.index
69 );
70 s.bitrate = Some(want);
71 }
72 assert_eq!(
73 shape,
74 vec![
75 StreamInfo {
76 index: 0,
77 codec: "aac".into(),
78 channels: 2,
79 sample_rate: 44100,
80 lang: None, // the `und` every muxer writes by default
81 decodable: true,
82 bit_depth: None,
83 bitrate: Some(128_372),
84 },
85 StreamInfo {
86 index: 1,
87 codec: "aac".into(),
88 channels: 1,
89 sample_rate: 22050,
90 lang: Some("fra".into()),
91 decodable: true,
92 bit_depth: None,
93 bitrate: Some(62_612),
94 },
95 // mp4 0.14 parses no sample entry for AC-3 and keeps no fourcc, so
96 // this row is described by the AC-3 reader itself: the codec by the
97 // stsd fourcc read by hand, the rate and the layout by the first
98 // syncframe. Stereo, because that is what the downmix hands out.
99 StreamInfo {
100 index: 2,
101 codec: "ac-3".into(),
102 channels: 2,
103 sample_rate: 44100,
104 lang: None,
105 decodable: true,
106 bit_depth: None,
107 bitrate: Some(193_928),
108 },
109 ]
110 );
111 // File order, run to run: `Mp4Reader::tracks` is a HashMap, so a careless
112 // enumeration would shuffle these two.
113 for _ in 0..8 {
114 let again = AudioSession::probe_streams(asset(MULTI)).expect("probes");
115 assert_eq!(again, streams);
116 }
117}
118
119/// The same listing for the container a film actually arrives in. A Matroska
120/// file used to be worth exactly one row here -- whichever track the readers
121/// stumbled on first -- so the second language of a dual-audio remux was
122/// invisible, and the language it is in was never shown at all.
123#[test]
124fn probe_streams_lists_every_matroska_audio_track_with_its_language() {
125 let streams = AudioSession::probe_streams(asset(MULTI_MKV)).expect("probes");
126 assert_eq!(
127 streams,
128 vec![
129 StreamInfo {
130 index: 0,
131 codec: "aac".into(),
132 channels: 2,
133 sample_rate: 44100,
134 lang: Some("eng".into()),
135 decodable: true,
136 bit_depth: None,
137 bitrate: None,
138 },
139 StreamInfo {
140 index: 1,
141 codec: "aac".into(),
142 channels: 2,
143 sample_rate: 44100,
144 lang: Some("fra".into()),
145 decodable: true,
146 bit_depth: None,
147 bitrate: None,
148 },
149 ]
150 );
151}
152
153/// The stream index is a position in the file's `Tracks` element and the reader
154/// is pointed at that entry's *track number*; a mapping that drifts plays the
155/// other language and saves it into the project, so it is measured by the tones
156/// each track carries.
157#[test]
158fn a_named_matroska_stream_decodes_that_stream_and_not_the_first() {
159 // The left channel of each stream: 440 Hz on stream 0, 220 Hz on stream 1.
160 for (stream, hz) in [(0usize, 440.0f64), (1, 220.0)] {
161 let (meta, samples) = decode(MULTI_MKV, stream);
162 assert_eq!((meta.sample_rate, meta.channels), (44100, 2));
163 let left: Vec<f32> = samples.chunks(2).map(|c| c[0]).collect();
164 let middle = &left[left.len() / 4..left.len() * 3 / 4];
165 let expected = 2.0 * hz * middle.len() as f64 / 44100.0;
166 let crossings = zero_crossings(middle) as f64;
167 assert!(
168 (crossings - expected).abs() < 0.05 * expected,
169 "stream {stream} is {crossings} crossings, {hz} Hz would be {expected}"
170 );
171 let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>()
172 / samples.len() as f64)
173 .sqrt();
174 assert!(rms > 0.01, "stream {stream} decoded silent: RMS {rms:.6}");
175 }
176
177 // Stream 0 is what the file has always played: the wrapper that names no
178 // stream and stream 0 are the same track, sample for sample.
179 let (wrapped, rx) = AudioSession::open(asset(MULTI_MKV))
180 .expect("opens")
181 .expect("audio");
182 let plain: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
183 let (meta, named) = decode(MULTI_MKV, 0);
184 assert_eq!(wrapped, meta);
185 assert_eq!(plain, named);
186
187 // ...and a stream the file does not have is refused, not quietly served the
188 // first track.
189 let err = AudioSession::open_multi_streams(&[(asset(MULTI_MKV), 2)], &[(Some(0), 0.0, 1.0)])
190 .expect_err("stream 2 of 2 does not exist");
191 assert!(
192 err.to_string().contains("audio stream 2 of 2 streams"),
193 "unhelpful refusal: {err}"
194 );
195}
196
197/// Stream 0 is the track the file already played, not the first one in the
198/// file: a remux flags the language it wants heard with `FlagDefault` on
199/// whichever track it likes, every reader here picked with that flag, and an
200/// `.edith` project saved before this listing existed must keep playing what it
201/// was saved with. Numbering by file position outright would switch its audio
202/// silently.
203///
204/// The flag is byte-patched in rather than muxed: ffmpeg writes `FlagDefault`
205/// only to say *0*, so the fixture's second track carries `88 81 00` and the
206/// one byte is flipped here -- same length, same offsets, a file mkvmerge could
207/// have written.
208#[test]
209fn flag_default_on_a_later_track_is_still_stream_0() {
210 let mut bytes = std::fs::read(asset(MULTI_MKV)).expect("read the fixture");
211 // `TrackLanguage` "fra" is the second audio `TrackEntry`; its `FlagDefault`
212 // sits right behind it.
213 let language = b"\x22\xb5\x9c\x83fra";
214 let at = bytes
215 .windows(language.len())
216 .position(|w| w == language)
217 .expect("the fixture's French track")
218 + language.len();
219 assert_eq!(
220 &bytes[at..at + 3],
221 b"\x88\x81\x00",
222 "the fixture stopped carrying an explicit FlagDefault=0"
223 );
224 bytes[at + 2] = 1;
225 let patched = Scratch::file("ve_flagdefault", "mkv");
226 std::fs::write(&patched, &bytes).expect("write the patched file");
227
228 // The flagged track leads: it is what `AudioSession::open` played before
229 // any of this, so it is stream 0 -- and the other one is still listed,
230 // behind it.
231 let streams = AudioSession::probe_streams(&patched).expect("probes");
232 assert_eq!(
233 streams.iter().map(|s| s.lang.clone()).collect::<Vec<_>>(),
234 vec![Some("fra".into()), Some("eng".into())],
235 "the default track has to lead: {streams:?}"
236 );
237 assert_eq!((streams[0].index, streams[1].index), (0, 1));
238
239 // ...and it decodes to what it always decoded to: 220 Hz, the French
240 // track's tone, sample for sample what the wrapper hands out.
241 let (wrapped, rx) = AudioSession::open(&patched).expect("opens").expect("audio");
242 let played: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
243 let sources = [(patched.to_path_buf(), 0)];
244 let (meta, stream_0) = {
245 let (meta, rx) = AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])
246 .expect("opens")
247 .expect("audio");
248 (meta, rx.into_iter().flat_map(|c| c.samples).collect::<Vec<f32>>())
249 };
250 assert_eq!(wrapped, meta);
251 assert_eq!(played, stream_0, "stream 0 is not what the file plays");
252 let left: Vec<f32> = stream_0.chunks(2).map(|c| c[0]).collect();
253 let middle = &left[left.len() / 4..left.len() * 3 / 4];
254 let expected = 2.0 * 220.0 * middle.len() as f64 / 44100.0;
255 let crossings = zero_crossings(middle) as f64;
256 assert!(
257 (crossings - expected).abs() < 0.05 * expected,
258 "stream 0 is {crossings} crossings, the French track's 220 Hz would be {expected}"
259 );
260 std::fs::remove_file(&patched).unwrap();
261}
262
263/// The file the ask came from: a dual-audio Blu-ray rip, two AAC tracks, and
264/// the second one has to play. Existence-gated -- it is not in the repo.
265#[test]
266fn a_real_dual_audio_remux_lists_both_tracks_and_plays_the_second() {
267 let Some(path) = engine::real_library::film("h264_dual_audio") else {
268 return;
269 };
270 let streams = AudioSession::probe_streams(&path).expect("probes");
271 assert_eq!(streams.len(), 2, "two audio tracks: {streams:?}");
272 for (index, info) in streams.iter().enumerate() {
273 assert_eq!(info.index, index);
274 assert_eq!(info.codec, "aac", "{info:?}");
275 assert!(info.decodable, "{info:?}");
276 }
277 // A second of each track, ten seconds in (past the silence a title card
278 // opens on): both have to carry sound and they have to be *different*
279 // sound. The failure this guards against is a stream index that resolves to
280 // nothing, or to the first track again.
281 let mut takes = Vec::new();
282 for stream in [0, 1] {
283 let (meta, rx) =
284 AudioSession::open_multi_streams(&[(path.clone(), stream)], &[(Some(0), 10.0, 11.0)])
285 .expect("the stream opens")
286 .expect("the stream is there");
287 let samples: Vec<f32> = rx.into_iter().flat_map(|c| c.samples).collect();
288 assert!(
289 samples.len() > meta.sample_rate as usize / 2,
290 "half a second of stream {stream} at least, got {}",
291 samples.len()
292 );
293 let rms = (samples.iter().map(|s| f64::from(*s) * f64::from(*s)).sum::<f64>()
294 / samples.len() as f64)
295 .sqrt();
296 assert!(rms > 1e-4, "stream {stream} came out silent: RMS {rms:.8}");
297 takes.push(samples);
298 }
299 assert_ne!(
300 takes[0], takes[1],
301 "the two languages decoded to the same samples: the stream index picked one track twice"
302 );
303}
304
305#[test]
306fn probe_streams_on_one_track_and_on_none() {
307 let one = AudioSession::probe_streams(asset("test_av.mp4")).expect("probes");
308 assert_eq!(one.len(), 1, "test_av.mp4 has a single audio track");
309 assert_eq!(
310 (one[0].index, one[0].sample_rate, one[0].channels),
311 (0, 44100, 2)
312 );
313 assert!(one[0].decodable);
314 // No audio at all is an empty list, not an error: a silent source is valid.
315 assert!(
316 AudioSession::probe_streams(asset("test_baseline.mp4"))
317 .expect("probes")
318 .is_empty()
319 );
320}
321
322#[test]
323fn a_named_stream_decodes_that_stream_and_not_the_first() {
324 let (meta, samples) = decode(MULTI, 1);
325 // A mix of sources all below 44.1 kHz runs at 48 kHz (see `mix_rate`), so the
326 // 22.05 kHz stream is resampled up; its pitch is checked below all the same.
327 assert_eq!((meta.sample_rate, meta.channels), (48000, 1));
328 // 220 Hz mono is 2 crossings a period. Measured over the middle half only:
329 // the encoder's ramp-in and the container's tail padding are low-level
330 // noise that crosses zero far more often than the tone does.
331 let middle = &samples[samples.len() / 4..samples.len() * 3 / 4];
332 let expected = 2.0 * 220.0 * middle.len() as f64 / f64::from(meta.sample_rate);
333 let crossings = zero_crossings(middle) as f64;
334 assert!(
335 (crossings - expected).abs() < 0.05 * expected,
336 "stream 1 is {crossings} crossings, 220 Hz mono would be {expected}"
337 );
338 assert!(samples.len() > 22050, "less than a second of stream 1");
339
340 // Stream 0 of the same file is the other one entirely.
341 let (meta, _) = decode(MULTI, 0);
342 assert_eq!((meta.sample_rate, meta.channels), (44100, 2));
343}
344
345#[test]
346fn stream_0_stays_exactly_what_the_wrapper_gave() {
347 // The default wrapper and stream 0 are the same track, sample for sample.
348 let (wrapped, rx) = AudioSession::open(asset(MULTI))
349 .expect("opens")
350 .expect("audio");
351 let mut plain = Vec::new();
352 for chunk in rx {
353 plain.extend_from_slice(&chunk.samples);
354 }
355 let (meta, named) = decode(MULTI, 0);
356 assert_eq!(wrapped, meta);
357 assert_eq!(plain, named);
358}
359
360#[test]
361fn an_impossible_stream_is_refused_not_guessed() {
362 let out_of_range = [(asset(MULTI), 3)];
363 let err = AudioSession::open_multi_streams(&out_of_range, &[(Some(0), 0.0, 1.0)])
364 .expect_err("stream 3 of 3 does not exist");
365 assert!(
366 err.to_string().contains("audio stream 3 of 3"),
367 "unhelpful refusal: {err}"
368 );
369 // Stream 2 is AC-3, and a *named* stream is opened by its own reader: it
370 // decodes to the same 44.1 kHz stereo the AAC stream 0 does, which is what
371 // lets it share this timeline at all.
372 let ac3 = [(asset(MULTI), 2)];
373 let (meta, _rx) = AudioSession::open_multi_streams(&ac3, &[(Some(0), 0.0, 1.0)])
374 .expect("AC-3 decodes now")
375 .expect("the stream is there");
376 assert_eq!((meta.sample_rate, meta.channels), (44100, 2));
377 // A source a *segment* names, opened lazily, refuses just the same.
378 let sources = [(asset(MULTI), 0), (asset(MULTI), 9)];
379 assert!(
380 AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)])
381 .is_err(),
382 "a second source's bad stream index has to refuse too"
383 );
384
385 // Stream 0 of a file with no audio is still the silent source it always
386 // was; a *named* stream of one is a promise the file cannot keep.
387 let silent = asset("test_baseline.mp4");
388 assert!(
389 AudioSession::open_multi_streams(&[(silent.clone(), 0)], &[(Some(0), 0.0, 1.0)])
390 .expect("no audio is not an error")
391 .is_none()
392 );
393 assert!(AudioSession::open_multi_streams(&[(silent, 1)], &[(Some(0), 0.0, 1.0)]).is_err());
394}
395
396/// Where the stream picker meets a file that has no picture to pick against: a
397/// standalone audio file is one stream, so it lists as one and answers to 0
398/// alone. A picker that offered a second row here would be offering a track
399/// that does not exist.
400#[test]
401fn a_standalone_audio_file_is_exactly_one_stream() {
402 for (name, codec) in [("test_tone.mp3", "mp3"), ("test_tone.flac", "flac")] {
403 let streams = AudioSession::probe_streams(asset(name)).expect("probes");
404 assert_eq!(
405 streams,
406 vec![StreamInfo {
407 index: 0,
408 codec: codec.into(),
409 channels: 2,
410 sample_rate: 44100,
411 // No mdhd to carry an ISO-639 tag, and one track needs no
412 // telling apart.
413 lang: None,
414 decodable: true,
415 bit_depth: None,
416 bitrate: None,
417 }],
418 "{name}"
419 );
420 // Stream 0 opens; anything above it is refused rather than quietly
421 // served the only track there is.
422 assert!(
423 AudioSession::open_multi_streams(&[(asset(name), 0)], &[(Some(0), 0.0, 1.0)])
424 .expect("stream 0 opens")
425 .is_some(),
426 "{name}"
427 );
428 let err = AudioSession::open_multi_streams(&[(asset(name), 1)], &[(Some(0), 0.0, 1.0)])
429 .expect_err("there is no stream 1");
430 assert!(
431 err.to_string().contains("audio stream 1 of 1 stream"),
432 "unhelpful refusal for {name}: {err}"
433 );
434 }
435 // The ALAC .m4a is the awkward one: it parses as an mp4 whose only audio
436 // track is not AAC, so the mp4 walk would call it "unknown" and undecodable
437 // where symphonia decodes it perfectly well.
438 let alac = AudioSession::probe_streams(asset("test_tone.m4a")).expect("probes");
439 assert_eq!(alac.len(), 1);
440 assert!(alac[0].decodable, "ALAC decodes: {alac:?}");
441 assert_eq!((alac[0].sample_rate, alac[0].channels), (44100, 2));
442}