forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

audio_mix_rates.rs322 lines, 11.9 KiBHistoryRawDownload
1//! Mixed audio lanes whose sources disagree on width and rate: a mono 22.05 kHz
2//! voice on one lane beside a stereo 48 kHz bed on another. The voice has to be
3//! heard for its whole length in the mix and in a WebM (Opus, which codes at
4//! 48 kHz) export, not cut off at half of it.
5
6use std::path::Path;
7use std::sync::mpsc::Receiver;
8use std::time::{Duration, Instant};
9
10use engine::audio::{AudioChunk, AudioSession};
11use engine::export::{ExportSettings, Format};
12use engine::project::{LaneKind, Source, Speed};
13use engine::scale::FitPolicy;
14use engine::scratch::Scratch;
15use engine::{Clip, ExportHandle, Project};
16
17/// A 16-bit PCM WAV written to `path`: a sine at `freq` Hz in every channel at
18/// `amp` of full scale.
19fn write_wav(path: impl AsRef<Path>, rate: u32, channels: u16, secs: f64, freq: f64, amp: f64) {
20 let frames = (secs * f64::from(rate)) as u32;
21 let data_len = frames * u32::from(channels) * 2;
22 let mut out = Vec::with_capacity(44 + data_len as usize);
23 out.extend_from_slice(b"RIFF");
24 out.extend_from_slice(&(36 + data_len).to_le_bytes());
25 out.extend_from_slice(b"WAVEfmt ");
26 out.extend_from_slice(&16u32.to_le_bytes());
27 out.extend_from_slice(&1u16.to_le_bytes());
28 out.extend_from_slice(&channels.to_le_bytes());
29 out.extend_from_slice(&rate.to_le_bytes());
30 out.extend_from_slice(&(rate * u32::from(channels) * 2).to_le_bytes());
31 out.extend_from_slice(&(channels * 2).to_le_bytes());
32 out.extend_from_slice(&16u16.to_le_bytes());
33 out.extend_from_slice(b"data");
34 out.extend_from_slice(&data_len.to_le_bytes());
35 for n in 0..frames {
36 let t = f64::from(n) / f64::from(rate);
37 let v = (amp * (2.0 * std::f64::consts::PI * freq * t).sin() * 32767.0) as i16;
38 for _ in 0..channels {
39 out.extend_from_slice(&v.to_le_bytes());
40 }
41 }
42 std::fs::write(path, out).expect("write wav");
43}
44
45/// Drains a stream, asserting its chunks are contiguous, and returns the
46/// interleaved samples.
47fn drain(rx: Receiver<AudioChunk>, channels: usize) -> Vec<f32> {
48 let mut samples = Vec::new();
49 let mut next = None;
50 for chunk in rx {
51 if let Some(next) = next {
52 assert_eq!(chunk.start_sample, next, "gap or overlap in the stream");
53 }
54 next = Some(chunk.start_sample + (chunk.samples.len() / channels) as u64);
55 samples.extend(chunk.samples);
56 }
57 samples
58}
59
60/// Root mean square of the first channel over each `window` seconds.
61fn rms_per_window(samples: &[f32], channels: usize, rate: u32, window: f64) -> Vec<f64> {
62 let per = (window * f64::from(rate)) as usize;
63 samples
64 .chunks(per * channels)
65 .map(|w| {
66 let sum: f64 = w
67 .iter()
68 .step_by(channels)
69 .map(|&s| f64::from(s).powi(2))
70 .sum();
71 (sum / (w.len() / channels) as f64).sqrt()
72 })
73 .collect()
74}
75
76/// Every half second of a 4 s voice must carry energy, the tail included.
77fn assert_voice_throughout(samples: &[f32], channels: usize, rate: u32, what: &str) {
78 let levels = rms_per_window(samples, channels, rate, 0.5);
79 assert!(
80 levels.len() >= 8,
81 "{what}: only {} half-second windows, the voice is 4 s",
82 levels.len()
83 );
84 for (i, level) in levels.iter().enumerate().take(8) {
85 assert!(
86 *level > 0.05,
87 "{what}: window {i} (at {:.1} s) is silent, rms {level:.5}; all {levels:?}",
88 i as f64 * 0.5
89 );
90 }
91}
92
93fn voice_and_bed() -> (Scratch, Scratch) {
94 let voice = Scratch::file("mix_voice_22k_mono", "wav");
95 let bed = Scratch::file("mix_bed_48k_stereo", "wav");
96 write_wav(&voice, 22_050, 1, 4.0, 220.0, 0.5);
97 write_wav(&bed, 48_000, 2, 1.0, 660.0, 0.2);
98 (voice, bed)
99}
100
101#[test]
102fn mono_22k_voice_mixed_with_a_stereo_48k_bed_is_heard_its_whole_length() {
103 let (voice, bed) = voice_and_bed();
104 let sources = vec![(voice.to_path_buf(), 0), (bed.to_path_buf(), 0)];
105 let lanes = vec![vec![(Some(0), 0.0, 4.0)], vec![(Some(1), 0.0, 1.0)]];
106 let (meta, rx) = AudioSession::open_mixed_streams(&sources, &lanes)
107 .expect("open")
108 .expect("audio");
109 let channels = usize::from(meta.channels);
110 let samples = drain(rx, channels);
111
112 let secs = samples.len() as f64 / channels as f64 / f64::from(meta.sample_rate);
113 assert!(secs > 3.9, "mix is {secs:.2} s, the voice is 4 s");
114 assert_voice_throughout(&samples, channels, meta.sample_rate, "mixed");
115}
116
117#[test]
118fn mono_22k_voice_alone_on_its_lane_is_heard_its_whole_length() {
119 // The control for the test above: the same voice with no bed beside it.
120 let (voice, _) = voice_and_bed();
121 let sources = vec![(voice.to_path_buf(), 0)];
122 let lanes = vec![vec![(Some(0), 0.0, 4.0)]];
123 let (meta, rx) = AudioSession::open_mixed_streams(&sources, &lanes)
124 .expect("open")
125 .expect("audio");
126 let channels = usize::from(meta.channels);
127 let samples = drain(rx, channels);
128 assert_voice_throughout(&samples, channels, meta.sample_rate, "solo");
129}
130
131#[test]
132fn a_mono_lane_beside_a_stereo_lane_is_the_mixs_width_not_its_own() {
133 // Mixed at 48 kHz, as WebM mixes: the voice is resampled up and must still
134 // be the mix's two channels wide, which is what the width rule guarantees.
135 let (voice, bed) = voice_and_bed();
136 let sources = vec![(voice.to_path_buf(), 0), (bed.to_path_buf(), 0)];
137 let lanes = vec![vec![(Some(0), 0.0, 4.0)], vec![(Some(1), 0.0, 1.0)]];
138 let (meta, rx) = AudioSession::open_mixed_streams_master_at(
139 &sources,
140 &lanes,
141 &[],
142 &[],
143 &[],
144 engine::limiter::Limiter::default(),
145 Some(48_000),
146 )
147 .expect("open")
148 .expect("audio");
149 assert_eq!(meta.channels, 2, "the mix takes the widest lane");
150 let channels = usize::from(meta.channels);
151 let samples = drain(rx, channels);
152 assert_voice_throughout(&samples, channels, meta.sample_rate, "mixed at 48k");
153}
154
155fn asset(name: &str) -> std::path::PathBuf {
156 Path::new(env!("CARGO_MANIFEST_DIR"))
157 .join("../../assets")
158 .join(name)
159}
160
161/// One clip of `source` at timeline frame `start`, `frames` long at the
162/// project's rate, playing its source from the start.
163fn clip(start: u32, frames: u32, source: usize) -> Clip {
164 Clip {
165 speed_keys: Vec::new(),
166 reversed: false,
167 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
168 angle: Default::default(),
169 fade_in: 0,
170 fade_out: 0,
171 transition_out: 0,
172 transition_kind: Default::default(),
173 visualizer: 0,
174 viz_paint: 0,
175 gain_db: 0.0,
176 gain_keys: Vec::new(),
177 pan: 0,
178 pitch: 0.0,
179 transform_keys: Vec::new(),
180 opacity_keys: Vec::new(),
181 color_keys: Vec::new(),
182 effects: Vec::new(),
183 start,
184 in_frame: 0,
185 out_frame: frames,
186 source,
187 link: None,
188 eq: None,
189 color: None,
190 fit: FitPolicy::default(),
191 speed: Speed::NORMAL,
192 transform: None,
193 }
194}
195
196#[test]
197fn a_webm_of_a_mono_voice_and_a_stereo_bed_keeps_the_voice_to_its_end() {
198 engine::envcfg::set("VE_SW", "1");
199 engine::envcfg::set("VE_SW_ENC", "1");
200 let (voice, bed) = voice_and_bed();
201 let project = Project::from_parts(
202 vec![
203 Source::new(asset("test_av.mp4"), 0),
204 Source::new(&voice, 0),
205 Source::new(&bed, 0),
206 ],
207 vec![
208 (LaneKind::Video, vec![clip(0, 120, 0)]),
209 (LaneKind::Audio, vec![clip(0, 120, 1)]),
210 (LaneKind::Audio, vec![clip(0, 30, 2)]),
211 ],
212 Vec::new(),
213 Vec::new(),
214 Vec::new(),
215 )
216 .expect("a picture with a voice and a bed under it");
217 let meta = engine::demux::Demuxer::open(&asset("test_av.mp4"))
218 .expect("open test_av")
219 .0;
220 let out = Scratch::file("mix_voice_bed", "webm");
221 let handle = engine::export::start(
222 project,
223 meta,
224 &out,
225 &ExportSettings {
226 format: Format::Webm,
227 ..Default::default()
228 },
229 None,
230 );
231 wait(&handle, Duration::from_secs(600)).expect("webm export");
232
233 let (audio, chunks) = AudioSession::open(&*out)
234 .expect("reopen the webm")
235 .expect("the webm has audio");
236 let channels = usize::from(audio.channels);
237 let mut samples = Vec::new();
238 for chunk in chunks {
239 samples.extend(chunk.samples);
240 }
241 let secs = samples.len() as f64 / channels as f64 / f64::from(audio.sample_rate);
242 assert!(
243 secs > 3.8,
244 "the webm sound is {secs:.2} s, the voice is 4 s"
245 );
246 assert_voice_throughout(&samples, channels, audio.sample_rate, "webm");
247}
248
249fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
250 let started = Instant::now();
251 while !handle.is_finished() {
252 assert!(
253 started.elapsed() < limit,
254 "export did not finish in {limit:?}"
255 );
256 std::thread::sleep(Duration::from_millis(10));
257 }
258 handle.result().expect("a finished export has an outcome")
259}
260
261/// Opens the mix of `sources` on `lanes` the way playback and export do, drains
262/// it, and returns the rate it runs at, its channel count, and its length in
263/// seconds as the stream delivers it.
264fn open_mix(sources: &[(std::path::PathBuf, usize)], lanes: &[Vec<(Option<usize>, f64, f64)>]) -> (u32, u16, f64) {
265 let (meta, rx) = AudioSession::open_mixed_streams(sources, lanes)
266 .expect("open")
267 .expect("audio");
268 let channels = usize::from(meta.channels);
269 let samples = drain(rx, channels);
270 let secs = samples.len() as f64 / channels as f64 / f64::from(meta.sample_rate);
271 (meta.sample_rate, meta.channels, secs)
272}
273
274#[test]
275fn a_22k_voiceover_beside_a_48k_bed_mixes_at_48k() {
276 // The bug: the first source's rate (the voiceover's) was the mix's, and a
277 // podcast exported at 22.05 kHz beside its 48 kHz music bed.
278 let (voice, bed) = voice_and_bed();
279 let sources = vec![(voice.to_path_buf(), 0), (bed.to_path_buf(), 0)];
280 let lanes = vec![vec![(Some(0), 0.0, 4.0)], vec![(Some(1), 0.0, 1.0)]];
281 let (rate, channels, secs) = open_mix(&sources, &lanes);
282 assert_eq!(rate, 48_000, "the highest source rate wins");
283 assert_eq!(channels, 2, "and the mix is as wide as its widest source");
284 assert!(secs > 3.9, "the 4 s voice is heard whole at 48k, got {secs:.2} s");
285}
286
287#[test]
288fn a_44k_source_beside_a_48k_source_mixes_at_48k() {
289 let low = Scratch::file("mix_rate_44k_src", "wav");
290 write_wav(&low, 44_100, 2, 4.0, 220.0, 0.3);
291 let high = Scratch::file("mix_rate_48k_src", "wav");
292 write_wav(&high, 48_000, 2, 4.0, 660.0, 0.3);
293 let sources = vec![(low.to_path_buf(), 0), (high.to_path_buf(), 0)];
294 let lanes = vec![vec![(Some(0), 0.0, 4.0)], vec![(Some(1), 0.0, 4.0)]];
295 let (rate, _, secs) = open_mix(&sources, &lanes);
296 assert_eq!(rate, 48_000);
297 assert!(secs > 3.9, "the 44.1 kHz source is heard whole, got {secs:.2} s");
298}
299
300#[test]
301fn only_a_22k_source_mixes_at_48k() {
302 // The documented choice: a mix whose sources are all below 44.1 kHz runs at
303 // 48 kHz, which AAC accepts and Opus needs. The length is unchanged.
304 let (voice, _) = voice_and_bed();
305 let sources = vec![(voice.to_path_buf(), 0)];
306 let lanes = vec![vec![(Some(0), 0.0, 4.0)]];
307 let (rate, channels, secs) = open_mix(&sources, &lanes);
308 assert_eq!(rate, 48_000);
309 assert_eq!(channels, 1);
310 assert!((secs - 4.0).abs() < 0.05, "a 4 s voice is 4 s at 48k, got {secs:.3} s");
311}
312
313#[test]
314fn a_44k_only_mix_stays_at_44k() {
315 let low = Scratch::file("mix_rate_44k_only", "wav");
316 write_wav(&low, 44_100, 2, 4.0, 220.0, 0.3);
317 let sources = vec![(low.to_path_buf(), 0)];
318 let lanes = vec![vec![(Some(0), 0.0, 4.0)]];
319 let (rate, _, secs) = open_mix(&sources, &lanes);
320 assert_eq!(rate, 44_100, "a 44.1 kHz timeline is not resampled");
321 assert!(secs > 3.9, "the 4 s source is heard whole, got {secs:.2} s");
322}