forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

audio_streams.rs181 lines, 6.5 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};
8
9/// Three audio streams: 0 is AAC 44.1k stereo (440/880 Hz, und), 1 is AAC
10/// 22.05k mono (220 Hz, fra), 2 is AC-3, which we cannot decode.
11/// See `scripts/gen_fixtures.sh`.
12const MULTI: &str = "test_multiaudio.mp4";
13
14fn asset(name: &str) -> PathBuf {
15 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
16 .join("../../assets")
17 .join(name)
18}
19
20/// Everything the worker produced for one stream, flat.
21fn decode(name: &str, stream: usize) -> (engine::AudioMeta, Vec<f32>) {
22 let sources = [(asset(name), stream)];
23 let (meta, rx) = AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)])
24 .expect("opens")
25 .expect("has audio");
26 let mut samples = Vec::new();
27 for chunk in rx {
28 samples.extend_from_slice(&chunk.samples);
29 }
30 (meta, samples)
31}
32
33/// Sign changes, exact zeros ignored: at one tone per channel this is 2f per
34/// second per channel.
35fn zero_crossings(samples: &[f32]) -> usize {
36 let (mut crossings, mut last) = (0, 0f32);
37 for &s in samples {
38 if s == 0.0 {
39 continue;
40 }
41 if last != 0.0 && (s > 0.0) != (last > 0.0) {
42 crossings += 1;
43 }
44 last = s;
45 }
46 crossings
47}
48
49#[test]
50fn probe_streams_lists_every_audio_track_in_file_order() {
51 let streams = AudioSession::probe_streams(asset(MULTI)).expect("probes");
52 assert_eq!(
53 streams,
54 vec![
55 StreamInfo {
56 index: 0,
57 codec: "aac".into(),
58 channels: 2,
59 sample_rate: 44100,
60 lang: None, // the `und` every muxer writes by default
61 decodable: true,
62 },
63 StreamInfo {
64 index: 1,
65 codec: "aac".into(),
66 channels: 1,
67 sample_rate: 22050,
68 lang: Some("fra".into()),
69 decodable: true,
70 },
71 // The one we cannot play is listed all the same, so a picker can
72 // grey it rather than pretend the file has two streams. mp4 0.14
73 // keeps no fourcc for a sample entry it does not parse, hence the
74 // blanks — the row exists, which is the point.
75 StreamInfo {
76 index: 2,
77 codec: "unknown".into(),
78 channels: 0,
79 sample_rate: 0,
80 lang: None,
81 decodable: false,
82 },
83 ]
84 );
85 // File order, run to run: `Mp4Reader::tracks` is a HashMap, so a careless
86 // enumeration would shuffle these two.
87 for _ in 0..8 {
88 let again = AudioSession::probe_streams(asset(MULTI)).expect("probes");
89 assert_eq!(again, streams);
90 }
91}
92
93#[test]
94fn probe_streams_on_one_track_and_on_none() {
95 let one = AudioSession::probe_streams(asset("test_av.mp4")).expect("probes");
96 assert_eq!(one.len(), 1, "test_av.mp4 has a single audio track");
97 assert_eq!(
98 (one[0].index, one[0].sample_rate, one[0].channels),
99 (0, 44100, 2)
100 );
101 assert!(one[0].decodable);
102 // No audio at all is an empty list, not an error: a silent source is valid.
103 assert!(
104 AudioSession::probe_streams(asset("test_baseline.mp4"))
105 .expect("probes")
106 .is_empty()
107 );
108}
109
110#[test]
111fn a_named_stream_decodes_that_stream_and_not_the_first() {
112 let (meta, samples) = decode(MULTI, 1);
113 assert_eq!((meta.sample_rate, meta.channels), (22050, 1));
114 // 220 Hz mono is 2 crossings a period. Measured over the middle half only:
115 // the encoder's ramp-in and the container's tail padding are low-level
116 // noise that crosses zero far more often than the tone does.
117 let middle = &samples[samples.len() / 4..samples.len() * 3 / 4];
118 let expected = 2.0 * 220.0 * middle.len() as f64 / 22050.0;
119 let crossings = zero_crossings(middle) as f64;
120 assert!(
121 (crossings - expected).abs() < 0.05 * expected,
122 "stream 1 is {crossings} crossings, 220 Hz mono would be {expected}"
123 );
124 assert!(samples.len() > 22050, "less than a second of stream 1");
125
126 // Stream 0 of the same file is the other one entirely.
127 let (meta, _) = decode(MULTI, 0);
128 assert_eq!((meta.sample_rate, meta.channels), (44100, 2));
129}
130
131#[test]
132fn stream_0_stays_exactly_what_the_wrapper_gave() {
133 // The default wrapper and stream 0 are the same track, sample for sample.
134 let (wrapped, rx) = AudioSession::open(asset(MULTI))
135 .expect("opens")
136 .expect("audio");
137 let mut plain = Vec::new();
138 for chunk in rx {
139 plain.extend_from_slice(&chunk.samples);
140 }
141 let (meta, named) = decode(MULTI, 0);
142 assert_eq!(wrapped, meta);
143 assert_eq!(plain, named);
144}
145
146#[test]
147fn an_impossible_stream_is_refused_not_guessed() {
148 let out_of_range = [(asset(MULTI), 3)];
149 let err = AudioSession::open_multi_streams(&out_of_range, &[(Some(0), 0.0, 1.0)])
150 .expect_err("stream 3 of 3 does not exist");
151 assert!(
152 err.to_string().contains("audio stream 3 of 3"),
153 "unhelpful refusal: {err}"
154 );
155 // Stream 2 exists but is AC-3: refused with its own message, not decoded
156 // into noise and not silently swapped for a stream that does decode.
157 let ac3 = [(asset(MULTI), 2)];
158 let err = AudioSession::open_multi_streams(&ac3, &[(Some(0), 0.0, 1.0)])
159 .expect_err("AC-3 does not decode here");
160 assert!(
161 err.to_string().contains("audio stream 2 is not AAC"),
162 "unhelpful refusal: {err}"
163 );
164 // A source a *segment* names, opened lazily, refuses just the same.
165 let sources = [(asset(MULTI), 0), (asset(MULTI), 9)];
166 assert!(
167 AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, 1.0), (Some(1), 0.0, 1.0)])
168 .is_err(),
169 "a second source's bad stream index has to refuse too"
170 );
171
172 // Stream 0 of a file with no audio is still the silent source it always
173 // was; a *named* stream of one is a promise the file cannot keep.
174 let silent = asset("test_baseline.mp4");
175 assert!(
176 AudioSession::open_multi_streams(&[(silent.clone(), 0)], &[(Some(0), 0.0, 1.0)])
177 .expect("no audio is not an error")
178 .is_none()
179 );
180 assert!(AudioSession::open_multi_streams(&[(silent, 1)], &[(Some(0), 0.0, 1.0)]).is_err());
181}