forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

duck_audio.rs372 lines, 13.3 KiBHistoryRawDownload
1//! Auto-ducking where it has to be true: in the samples the mix sums, which
2//! playback feeds the device and an export writes. Both reach that sum through
3//! `AudioSession::open_mixed_streams_master_at_fade` with the project's own
4//! `audio_gains` and `audio_ducks`, so this drives that opener with the same
5//! lists the export hands it (`export.rs`), and reads the summed stream.
6//!
7//! The fixtures are generated here, so the levels are known exactly:
8//! * `A1` is a dialogue stand-in: a 0.5 amplitude tone for one second, from
9//! 1 s to 2 s, and silence everywhere else.
10//! * `A2` is a music-bed stand-in: a 0.2 amplitude tone for the whole four
11//! seconds.
12//!
13//! `A2` is ducked under `A1` by 12 dB. The mix with the duck minus the mix
14//! without it is then exactly `A2 * (gain - 1)` while the duck is in effect,
15//! because `A1` is the same in both and only `A2` moves. So the test can read
16//! `A2`'s own contribution off the sum, in the burst and out of it.
17
18use std::path::{Path, PathBuf};
19
20use engine::duck::Duck;
21use engine::project::{Clip, Lane, LaneKind, Source, Speed};
22use engine::scale::FitPolicy;
23use engine::scratch::Scratch;
24use engine::{AudioSession, Project};
25
26const RATE: u32 = 44_100;
27const FPS: f64 = 30.0;
28const SECONDS: f64 = 4.0;
29const DIALOGUE_AMP: f32 = 0.5;
30const BED_AMP: f32 = 0.2;
31const DEPTH_DB: f32 = -12.0;
32
33fn clip(source: usize, frames: u32) -> Clip {
34 Clip {
35 speed_keys: Vec::new(),
36 reversed: false,
37 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
38 angle: Default::default(),
39 fade_in: 0,
40 fade_out: 0,
41 transition_out: 0,
42 transition_kind: Default::default(),
43 visualizer: 0,
44 viz_paint: 0,
45 gain_db: 0.0,
46 gain_keys: Vec::new(),
47 pan: 0,
48 pitch: 0.0,
49 transform_keys: Vec::new(),
50 opacity_keys: Vec::new(),
51 color_keys: Vec::new(),
52 effects: Vec::new(),
53 start: 0,
54 in_frame: 0,
55 out_frame: frames,
56 source,
57 link: None,
58 eq: None,
59 color: None,
60 fit: FitPolicy::default(),
61 speed: Speed::NORMAL,
62 transform: None,
63 }
64}
65
66/// A 16-bit stereo PCM WAV of `SECONDS`, the sample at each frame from `at`.
67fn write_wav(path: &Path, at: impl Fn(f64) -> f32) {
68 let frames = (SECONDS * f64::from(RATE)) as usize;
69 let mut data = Vec::with_capacity(frames * 4);
70 for i in 0..frames {
71 let s = at(i as f64 / f64::from(RATE));
72 let q = (s * 32767.0).round() as i16;
73 data.extend_from_slice(&q.to_le_bytes());
74 data.extend_from_slice(&q.to_le_bytes());
75 }
76 let mut out = Vec::new();
77 out.extend_from_slice(b"RIFF");
78 out.extend_from_slice(&(36 + data.len() as u32).to_le_bytes());
79 out.extend_from_slice(b"WAVEfmt ");
80 out.extend_from_slice(&16u32.to_le_bytes());
81 out.extend_from_slice(&1u16.to_le_bytes()); // PCM
82 out.extend_from_slice(&2u16.to_le_bytes()); // stereo
83 out.extend_from_slice(&RATE.to_le_bytes());
84 out.extend_from_slice(&(RATE * 4).to_le_bytes());
85 out.extend_from_slice(&4u16.to_le_bytes());
86 out.extend_from_slice(&16u16.to_le_bytes());
87 out.extend_from_slice(b"data");
88 out.extend_from_slice(&(data.len() as u32).to_le_bytes());
89 out.extend_from_slice(&data);
90 std::fs::write(path, out).expect("write the generated wav");
91}
92
93fn tone(hz: f64, amp: f32, t: f64) -> f32 {
94 amp * (std::f64::consts::TAU * hz * t).sin() as f32
95}
96
97/// The summed stream, interleaved stereo, from the mix the export opens.
98fn mixed(project: &Project, ducks: &[Vec<Duck>]) -> Vec<f32> {
99 let sources = project.audio_sources();
100 let segs = project.audio_segments_from(0, FPS);
101 let (meta, chunks) = AudioSession::open_mixed_streams_master_at_fade(
102 &sources,
103 &segs,
104 &[],
105 &[],
106 &[],
107 FPS,
108 &project.audio_gains(),
109 ducks,
110 &project.audio_voices(),
111 project.limiter(),
112 None,
113 )
114 .expect("open the mix")
115 .expect("the project has audio");
116 assert_eq!((meta.sample_rate, meta.channels), (RATE, 2));
117 chunks.into_iter().flat_map(|c| c.samples).collect()
118}
119
120/// The `A2` contribution the duck removed, per sample, over `[from, to)`.
121fn removed(without: &[f32], with: &[f32], from: f64, to: f64) -> f64 {
122 let at = |secs: f64| (secs * f64::from(RATE)) as usize * 2;
123 let (a, b) = (at(from), at(to));
124 let diff: Vec<f32> = without[a..b]
125 .iter()
126 .zip(&with[a..b])
127 .map(|(x, y)| x - y)
128 .collect();
129 (diff.iter().map(|&d| f64::from(d) * f64::from(d)).sum::<f64>() / diff.len() as f64).sqrt()
130}
131
132#[test]
133fn a_bed_ducked_under_dialogue_is_quieter_only_while_the_dialogue_plays() {
134 let dir = Scratch::dir("ve_duck_audio");
135 let dialogue: PathBuf = dir.join("dialogue.wav");
136 let bed: PathBuf = dir.join("bed.wav");
137 write_wav(&dialogue, |t| {
138 if (1.0..2.0).contains(&t) {
139 tone(220.0, DIALOGUE_AMP, t)
140 } else {
141 0.0
142 }
143 });
144 write_wav(&bed, |t| tone(440.0, BED_AMP, t));
145
146 let frames = (SECONDS * FPS) as u32;
147 let mut project = Project::from_parts(
148 vec![Source::new(dialogue.clone(), 0), Source::new(bed.clone(), 0)],
149 vec![
150 (LaneKind::Audio, vec![clip(0, frames)]),
151 (LaneKind::Audio, vec![clip(1, frames)]),
152 ],
153 Vec::new(),
154 Vec::new(),
155 Vec::new(),
156 )
157 .expect("two audio lanes over two generated files");
158 // The duck is set the way an editor sets it: on A2, keyed off A1.
159 let a2 = Lane::new(LaneKind::Audio, 1);
160 let duck = Duck {
161 under: 0,
162 depth_db: DEPTH_DB,
163 threshold_db: -40.0,
164 attack_ms: 80.0,
165 release_ms: 400.0,
166 };
167 assert!(project.set_lane_duck(a2, Some(duck)), "A2 ducks under A1");
168 let ducks = project.audio_ducks();
169 assert_eq!(ducks, vec![vec![], vec![duck]], "in the mix, A2 keys off mixed lane 0");
170
171 let without = mixed(&project, &[]);
172 let with = mixed(&project, &ducks);
173 assert_eq!(without.len(), with.len(), "the same timeline either way");
174
175 // Before the dialogue the key is silent, so nothing moves at all.
176 assert!(
177 removed(&without, &with, 0.0, 0.9) < 1e-7,
178 "a silent key leaves the bed exactly as it was"
179 );
180 // In the burst, A2 is at the depth, so what it loses is (1 - depth) of
181 // its own level: a bed at 0.2 amplitude is 0.2/sqrt(2) rms.
182 let bed_rms = f64::from(BED_AMP) / std::f64::consts::SQRT_2;
183 let depth_lin = 10f64.powf(f64::from(DEPTH_DB) / 20.0);
184 let expected = (1.0 - depth_lin) * bed_rms;
185 let in_burst = removed(&without, &with, 1.3, 1.8);
186 assert!(
187 (in_burst - expected).abs() < expected * 0.03,
188 "the bed is ducked to its depth under the dialogue: removed {in_burst:.5}, want {expected:.5}"
189 );
190 // Long after the dialogue the duck has released, and the bed is back.
191 assert!(
192 removed(&without, &with, 2.6, 3.8) < 1e-5,
193 "the bed is back to its level once the dialogue has gone"
194 );
195}
196
197/// A bed ducked under two keys at once: each key's burst pulls the bed down
198/// to its depth, and the bed is back in between, so both ducks are heard and
199/// neither is lost to the other being set later.
200#[test]
201fn a_bed_ducked_under_two_keys_drops_under_each_of_them() {
202 let dir = Scratch::dir("ve_duck_two_keys");
203 let first: PathBuf = dir.join("first.wav");
204 let second: PathBuf = dir.join("second.wav");
205 let bed: PathBuf = dir.join("bed.wav");
206 write_wav(&first, |t| {
207 if (1.0..2.0).contains(&t) {
208 tone(220.0, DIALOGUE_AMP, t)
209 } else {
210 0.0
211 }
212 });
213 write_wav(&second, |t| {
214 if (3.0..3.5).contains(&t) {
215 tone(330.0, DIALOGUE_AMP, t)
216 } else {
217 0.0
218 }
219 });
220 write_wav(&bed, |t| tone(440.0, BED_AMP, t));
221
222 let frames = (SECONDS * FPS) as u32;
223 let mut project = Project::from_parts(
224 vec![
225 Source::new(first.clone(), 0),
226 Source::new(second.clone(), 0),
227 Source::new(bed.clone(), 0),
228 ],
229 vec![
230 (LaneKind::Audio, vec![clip(0, frames)]),
231 (LaneKind::Audio, vec![clip(1, frames)]),
232 (LaneKind::Audio, vec![clip(2, frames)]),
233 ],
234 Vec::new(),
235 Vec::new(),
236 Vec::new(),
237 )
238 .expect("three audio lanes over three generated files");
239 let a3 = Lane::new(LaneKind::Audio, 2);
240 let under_first = Duck {
241 under: 0,
242 depth_db: DEPTH_DB,
243 threshold_db: -40.0,
244 attack_ms: 80.0,
245 release_ms: 400.0,
246 };
247 let under_second = Duck {
248 under: 1,
249 ..under_first
250 };
251 assert!(project.set_lane_duck(a3, Some(under_first)), "A3 ducks under A1");
252 assert!(project.set_lane_duck(a3, Some(under_second)), "and under A2 too");
253 let ducks = project.audio_ducks();
254 assert_eq!(ducks[2], vec![under_first, under_second], "both kept, in order");
255
256 let without = mixed(&project, &[]);
257 let with = mixed(&project, &ducks);
258
259 // Each burst is alone in its window, so the bed loses (1 - depth) of its
260 // level under that key and under no other.
261 let bed_rms = f64::from(BED_AMP) / std::f64::consts::SQRT_2;
262 let depth_lin = 10f64.powf(f64::from(DEPTH_DB) / 20.0);
263 let expected = (1.0 - depth_lin) * bed_rms;
264 for (from, to, key) in [(1.3, 1.8, "A1"), (3.1, 3.4, "A2")] {
265 let got = removed(&without, &with, from, to);
266 assert!(
267 (got - expected).abs() < expected * 0.03,
268 "under {key} the bed drops to its depth: removed {got:.5}, want {expected:.5}"
269 );
270 }
271 // Between the bursts both keys are silent or released, and the bed is back.
272 assert!(
273 removed(&without, &with, 2.6, 2.9) < 1e-5,
274 "the bed is back between the two keys"
275 );
276}
277
278/// Clearing one of two keys leaves the other in force: the bed ducks under the
279/// key that stays and not under the one that went.
280#[test]
281fn clearing_one_key_leaves_the_other_duck_in_the_mix() {
282 let dir = Scratch::dir("ve_duck_clear_key");
283 let first: PathBuf = dir.join("first.wav");
284 let second: PathBuf = dir.join("second.wav");
285 let bed: PathBuf = dir.join("bed.wav");
286 write_wav(&first, |t| {
287 if (1.0..2.0).contains(&t) {
288 tone(220.0, DIALOGUE_AMP, t)
289 } else {
290 0.0
291 }
292 });
293 write_wav(&second, |t| {
294 if (3.0..3.5).contains(&t) {
295 tone(330.0, DIALOGUE_AMP, t)
296 } else {
297 0.0
298 }
299 });
300 write_wav(&bed, |t| tone(440.0, BED_AMP, t));
301 let frames = (SECONDS * FPS) as u32;
302 let mut project = Project::from_parts(
303 vec![
304 Source::new(first.clone(), 0),
305 Source::new(second.clone(), 0),
306 Source::new(bed.clone(), 0),
307 ],
308 vec![
309 (LaneKind::Audio, vec![clip(0, frames)]),
310 (LaneKind::Audio, vec![clip(1, frames)]),
311 (LaneKind::Audio, vec![clip(2, frames)]),
312 ],
313 Vec::new(),
314 Vec::new(),
315 Vec::new(),
316 )
317 .expect("three audio lanes");
318 let a3 = Lane::new(LaneKind::Audio, 2);
319 let under_first = Duck::new(0, DEPTH_DB);
320 assert!(project.set_lane_duck(a3, Some(under_first)));
321 assert!(project.set_lane_duck(a3, Some(Duck::new(1, DEPTH_DB))));
322 assert!(project.clear_lane_duck(a3, 1), "the A2 key goes");
323 let ducks = project.audio_ducks();
324 assert_eq!(ducks[2], vec![under_first], "only the A1 key is left");
325
326 let without = mixed(&project, &[]);
327 let with = mixed(&project, &ducks);
328 assert!(
329 removed(&without, &with, 3.1, 3.4) < 1e-5,
330 "with A2 gone, its burst no longer ducks the bed"
331 );
332 let bed_rms = f64::from(BED_AMP) / std::f64::consts::SQRT_2;
333 let depth_lin = 10f64.powf(f64::from(DEPTH_DB) / 20.0);
334 let expected = (1.0 - depth_lin) * bed_rms;
335 let got = removed(&without, &with, 1.3, 1.8);
336 assert!(
337 (got - expected).abs() < expected * 0.03,
338 "the A1 key still ducks the bed: removed {got:.5}, want {expected:.5}"
339 );
340}
341
342/// Two ducks on one lane are saved and reopened as two: the file names each
343/// key on its own `duck` line, and the reopened lane has both back in order.
344#[test]
345fn two_ducks_on_one_lane_survive_a_save_and_reopen() {
346 let mut s = engine::PlaybackSession::open(asset("test_av.mp4")).expect("open");
347 s.set_gain(0.0);
348 let a2 = s.add_lane(LaneKind::Audio);
349 let a3 = s.add_lane(LaneKind::Audio);
350 let end = s.timeline_duration();
351 assert!(s.place_at(a2, end, clip(0, 150)), "a key on A2");
352 assert!(s.place_at(a3, end, clip(0, 150)), "a bed on A3");
353 assert!(s.set_lane_duck(a3, Some(Duck::new(0, DEPTH_DB))), "A3 under A1");
354 assert!(s.set_lane_duck(a3, Some(Duck::new(1, DEPTH_DB))), "and under A2");
355 assert_eq!(s.lane_duck_list(a3).len(), 2);
356
357 let dir = Scratch::dir("ve_duck_two_keys_save");
358 let path = dir.join("two.edith");
359 s.save_project(&path).expect("save");
360 let back = engine::PlaybackSession::open_project(&path).expect("reopen");
361 let list = back.lane_duck_list(a3);
362 assert_eq!(list.len(), 2, "both ducks came back");
363 assert_eq!(list[0].under, 0);
364 assert_eq!(list[1].under, 1);
365 assert!(back.load_warnings().is_empty(), "{:?}", back.load_warnings());
366}
367
368fn asset(name: &str) -> PathBuf {
369 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
370 .join("../../assets")
371 .join(name)
372}