forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

voice_audio.rs354 lines, 15.0 KiBHistoryRawDownload
1//! Voice cleanup where it has to be true: in the samples the mix sums, which playback feeds
2//! the device and an export writes. Both reach them through
3//! `AudioSession::open_mixed_streams_master_at_fade` with the project's own `audio_voices`,
4//! so this drives that opener with the lists the export hands it.
5//!
6//! The fixture is generated: one lane of 4 s, white noise at -30 dBFS throughout and a
7//! -12 dBFS 1 kHz tone over it from 2 s to 4 s. The first two seconds are the noise alone.
8
9use std::path::Path;
10
11use engine::project::{Clip, Lane, LaneKind, Source, Speed};
12use engine::scale::FitPolicy;
13use engine::scratch::Scratch;
14use engine::voice::{self, Strength, VoiceFx};
15use engine::{AudioSession, Project};
16
17const RATE: u32 = 44_100;
18const FPS: f64 = 30.0;
19const SECONDS: f64 = 4.0;
20
21fn clip(source: usize, frames: u32) -> Clip {
22 Clip {
23 speed_keys: Vec::new(),
24 fade_in: 0,
25 fade_out: 0,
26 transition_out: 0,
27 visualizer: 0,
28 viz_paint: 0,
29 gain_db: 0.0,
30 gain_keys: Vec::new(),
31 pan: 0,
32 pitch: 0.0,
33 transform_keys: Vec::new(),
34 start: 0,
35 in_frame: 0,
36 out_frame: frames,
37 source,
38 link: None,
39 eq: None,
40 color: None,
41 fit: FitPolicy::default(),
42 speed: Speed::NORMAL,
43 transform: None,
44 opacity_keys: Vec::new(),
45 color_keys: Vec::new(),
46 effects: Vec::new(),
47 transition_kind: Default::default(),
48 reversed: false,
49 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
50 angle: Default::default(),
51 }
52}
53
54/// Deterministic noise in about -0.5..0.5 per sample index, scaled to the given rms.
55fn noise(i: usize, rms: f32) -> f32 {
56 let mut sum = 0.0f32;
57 for k in 0..4u64 {
58 let mut x = (i as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15).wrapping_add(k.wrapping_mul(0xD1B5_4A32_D192_ED03));
59 x ^= x >> 29;
60 x = x.wrapping_mul(0xBF58_476D_1CE4_E5B9);
61 x ^= x >> 32;
62 sum += (x >> 40) as f32 / (1u64 << 24) as f32 - 0.5;
63 }
64 sum * rms / (4.0f32 / 12.0).sqrt()
65}
66
67fn write_wav(path: &Path, at: impl Fn(usize) -> 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 q = (at(i) * 32767.0).round() as i16;
72 data.extend_from_slice(&q.to_le_bytes());
73 data.extend_from_slice(&q.to_le_bytes());
74 }
75 let mut out = Vec::new();
76 out.extend_from_slice(b"RIFF");
77 out.extend_from_slice(&(36 + data.len() as u32).to_le_bytes());
78 out.extend_from_slice(b"WAVEfmt ");
79 out.extend_from_slice(&16u32.to_le_bytes());
80 out.extend_from_slice(&1u16.to_le_bytes());
81 out.extend_from_slice(&2u16.to_le_bytes());
82 out.extend_from_slice(&RATE.to_le_bytes());
83 out.extend_from_slice(&(RATE * 4).to_le_bytes());
84 out.extend_from_slice(&4u16.to_le_bytes());
85 out.extend_from_slice(&16u16.to_le_bytes());
86 out.extend_from_slice(b"data");
87 out.extend_from_slice(&(data.len() as u32).to_le_bytes());
88 out.extend_from_slice(&data);
89 std::fs::write(path, out).expect("write the generated wav");
90}
91
92fn project(wav: &Path) -> Project {
93 let frames = (SECONDS * FPS) as u32;
94 Project::from_parts(
95 vec![Source::new(wav, 0)],
96 vec![(LaneKind::Audio, vec![clip(0, frames)])],
97 Vec::new(),
98 Vec::new(),
99 Vec::new(),
100 )
101 .expect("one audio lane over a generated file")
102}
103
104fn mixed(project: &Project) -> Vec<f32> {
105 let (meta, chunks) = AudioSession::open_mixed_streams_master_at_fade(
106 &project.audio_sources(),
107 &project.audio_segments_from(0, FPS),
108 &project.audio_eqs_from(0, FPS),
109 &project.audio_speeds_from(0, FPS),
110 &project.audio_fades_from(0, FPS),
111 FPS,
112 &project.audio_gains(),
113 &project.audio_ducks(),
114 &project.audio_voices(),
115 project.limiter(),
116 None,
117 )
118 .expect("open the mix")
119 .expect("the project has audio");
120 assert_eq!((meta.sample_rate, meta.channels), (RATE, 2));
121 chunks.into_iter().flat_map(|c| c.samples).collect()
122}
123
124/// Left channel only, `[from, to)` seconds.
125fn left(x: &[f32], from: f64, to: f64) -> Vec<f32> {
126 let at = |s: f64| (s * f64::from(RATE)) as usize;
127 x[at(from) * 2..at(to) * 2].as_chunks::<2>().0.iter().map(|f| f[0]).collect()
128}
129
130fn rms_db(x: &[f32]) -> f32 {
131 20.0 * (x.iter().map(|s| s * s).sum::<f32>() / x.len() as f32).sqrt().max(1e-12).log10()
132}
133
134/// Level of the 1 kHz component in the left channel over `[from, to)` seconds, dBFS peak.
135fn tone_db(x: &[f32], from: f64, to: f64) -> f32 {
136 let at = |s: f64| (s * f64::from(RATE)) as usize;
137 let (mut s, mut c) = (0.0f64, 0.0f64);
138 let (a, b) = (at(from), at(to));
139 for i in a..b {
140 let ph = std::f64::consts::TAU * 1000.0 * i as f64 / f64::from(RATE);
141 s += f64::from(x[i * 2]) * ph.sin();
142 c += f64::from(x[i * 2]) * ph.cos();
143 }
144 (20.0 * (2.0 * (s * s + c * c).sqrt() / (b - a) as f64).log10()) as f32
145}
146
147#[test]
148fn cleaning_a_lane_takes_the_noise_out_of_the_mix_and_keeps_the_tone_and_the_length() {
149 let dir = Scratch::dir("ve_voice_audio");
150 let wav = dir.join("voice.wav");
151 write_wav(&wav, |i| {
152 let t = i as f64 / f64::from(RATE);
153 let tone = if t >= 2.0 { 0.25 * (std::f64::consts::TAU * 1000.0 * t).sin() as f32 } else { 0.0 };
154 noise(i, 0.0316) + tone
155 });
156 let mut project = project(&wav);
157 let a1 = Lane::A1;
158 let plain = mixed(&project);
159 assert!(project.audio_voices().iter().all(|v| !v.is_active()), "nothing on by default");
160
161 // The noise is learned from the quietest stretch, found by itself: it is in the first two
162 // seconds, where only the noise plays.
163 let learned = voice::learn_noise(&project, a1, FPS, None, None).expect("a stretch to learn from");
164 assert!(learned.from.0 >= 0.0 && learned.from.1 <= 2.05, "found at {:?}", learned.from);
165 assert!((learned.noise_db + 30.0).abs() < 1.5, "learned {:.1} dB", learned.noise_db);
166 // ...or from a range given by hand, which has to agree about the level.
167 let by_hand = voice::learn_noise(&project, a1, FPS, None, Some((0.2, 1.7))).expect("the given range");
168 assert!((by_hand.noise_db - learned.noise_db).abs() < 1.0);
169 assert!(voice::learn_noise(&project, a1, FPS, None, Some((0.2, 0.21))).is_err(), "too short to learn");
170
171 // Noise reduction alone, switched on without a profile, is refused.
172 let mut fx = VoiceFx::clean_voice(Strength::Medium, learned.profile.clone(), Some(learned.noise_db));
173 fx.gate.on = false;
174 fx.comp.on = false;
175 fx.deess.on = false;
176 fx.nr.strength = 0.8;
177 let mut bare = fx.clone();
178 bare.nr.profile.clear();
179 assert!(!project.set_lane_voice(a1, bare), "nr on with no profile");
180 assert!(project.set_lane_voice(a1, fx.clone()));
181 assert!(!project.set_lane_voice(a1, fx.clone()), "unchanged is no change");
182
183 let cleaned = mixed(&project);
184 assert_eq!(cleaned.len(), plain.len(), "the stage keeps the lane its length");
185 let drop = rms_db(&left(&plain, 0.5, 1.8)) - rms_db(&left(&cleaned, 0.5, 1.8));
186 assert!(drop >= 15.0, "the noise-only stretch fell {drop:.1} dB");
187 let kept = tone_db(&cleaned, 2.5, 3.8) - tone_db(&plain, 2.5, 3.8);
188 assert!(kept.abs() < 1.0, "the tone moved by {kept:.2} dB");
189
190 // One undo step takes it all back, and the mix is the bit-exact plain one again.
191 assert!(project.undo());
192 assert!(!project.lane_voice(a1).is_active());
193 assert_eq!(mixed(&project), plain, "no processors on: the same samples as before");
194}
195
196#[test]
197fn a_one_click_preset_is_one_undo_step() {
198 let dir = Scratch::dir("ve_voice_preset");
199 let wav = dir.join("voice.wav");
200 write_wav(&wav, |i| noise(i, 0.0316));
201 let mut project = project(&wav);
202 let a1 = Lane::A1;
203 let learned = voice::learn_noise(&project, a1, FPS, None, None).unwrap();
204 let fx = VoiceFx::clean_voice(Strength::Medium, learned.profile, Some(learned.noise_db));
205 assert!(project.set_lane_voice(a1, fx.clone()));
206 assert_eq!(project.lane_voice(a1), fx);
207 assert_eq!(project.lane_voices(), vec![fx.clone()], "saved by its own lane");
208 assert!(project.undo(), "the whole preset is one step");
209 assert_eq!(project.lane_voice(a1), VoiceFx::default());
210 assert!(project.redo());
211 assert_eq!(project.lane_voice(a1), fx);
212 // A video lane takes no voice.
213 assert!(!project.set_lane_voice(Lane::V1, fx));
214}
215
216/// A lane an hour long (900 four-second clips of one file) is searched for noise by reading a
217/// bounded amount of it, so the time does not grow with the lane.
218#[test]
219fn the_noise_search_of_an_hour_long_lane_is_bounded() {
220 let dir = Scratch::dir("ve_voice_hour");
221 let wav = dir.join("voice.wav");
222 write_wav(&wav, |i| noise(i, 0.0316));
223 let clips = 900u32;
224 let each = (SECONDS * FPS) as u32;
225 let lane: Vec<Clip> = (0..clips)
226 .map(|k| {
227 let mut c = clip(0, each);
228 c.start = k * each;
229 c
230 })
231 .collect();
232 let project = Project::from_parts(
233 vec![Source::new(&wav, 0)],
234 vec![(LaneKind::Audio, lane)],
235 Vec::new(),
236 Vec::new(),
237 Vec::new(),
238 )
239 .expect("an hour of clips");
240 let started = std::time::Instant::now();
241 let learned = voice::learn_noise(&project, Lane::A1, FPS, None, None).expect("noise in an hour of noise");
242 let took = started.elapsed();
243 assert!((learned.noise_db + 30.0).abs() < 1.5, "learned {:.1} dB", learned.noise_db);
244 assert!(learned.from.1 <= 3600.0 + 0.1);
245 // Reading the whole hour decodes 3600 s of audio; the bounded search reads 60 s of it.
246 assert!(took < std::time::Duration::from_secs(20), "an hour took {took:?}");
247}
248
249/// The full chain, noise reduction and de-esser included, keeps the lane where it was: a noise
250/// burst comes out at the same sample, within one.
251#[test]
252fn the_full_chain_adds_no_delay() {
253 let dir = Scratch::dir("ve_voice_align");
254 let wav = dir.join("voice.wav");
255 let burst = |i: usize| {
256 let t = i as f64 / f64::from(RATE);
257 if (2.0..2.3).contains(&t) { noise(i + 7_000_000, 0.2) } else { 0.0 }
258 };
259 write_wav(&wav, |i| noise(i, 0.0063) + burst(i));
260 let mut project = project(&wav);
261 let plain = mixed(&project);
262 let learned = voice::learn_noise(&project, Lane::A1, FPS, None, Some((0.2, 1.7))).unwrap();
263 let fx = VoiceFx::clean_voice(Strength::Medium, learned.profile, Some(learned.noise_db));
264 assert!(fx.gate.on && fx.nr.on && fx.comp.on && fx.deess.on, "the whole chain");
265 assert!(project.set_lane_voice(Lane::A1, fx));
266 let cleaned = mixed(&project);
267 assert_eq!(cleaned.len(), plain.len());
268 let a = left(&plain, 2.05, 2.25);
269 let from = (2.05 * f64::from(RATE)) as usize;
270 let b: Vec<f32> = cleaned.as_chunks::<2>().0.iter().map(|f| f[0]).collect();
271 let (mut best, mut at) = (f64::MIN, 0i64);
272 for lag in -200i64..=200 {
273 let dot: f64 = a
274 .iter()
275 .enumerate()
276 .map(|(i, &x)| f64::from(x) * f64::from(b[(from + i).wrapping_add_signed(lag as isize)]))
277 .sum();
278 if dot > best {
279 (best, at) = (dot, lag);
280 }
281 }
282 assert!(at.abs() <= 1, "the processed lane is {at} samples off");
283}
284
285/// A ranged export starts with the chain warm: its first second is the same span of the full export.
286#[test]
287fn a_ranged_export_matches_the_same_span_of_the_full_one() {
288 use engine::export::{ExportSettings, Format};
289 let dir = Scratch::dir("ve_voice_range");
290 let wav = dir.join("voice.wav");
291 write_wav(&wav, |i| {
292 let t = i as f64 / f64::from(RATE);
293 let tone = if t >= 1.0 { 0.25 * (std::f64::consts::TAU * 1000.0 * t).sin() as f32 } else { 0.0 };
294 noise(i, 0.0316) + tone
295 });
296 let mut project = project(&wav);
297 let learned = voice::learn_noise(&project, Lane::A1, FPS, None, Some((0.1, 0.9))).unwrap();
298 let fx = VoiceFx::clean_voice(Strength::Strong, learned.profile, Some(learned.noise_db));
299 assert!(project.set_lane_voice(Lane::A1, fx));
300 let meta = engine::demux::Demuxer::open(&std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4"))
301 .expect("open test_av")
302 .0;
303 let export = |fps: f64, range: Option<(u32, u32)>, name: &str| -> Vec<f32> {
304 let out = dir.join(name);
305 let mut meta = meta;
306 meta.frame_rate = fps;
307 let handle = engine::export::start(
308 project.clone(),
309 meta,
310 &out,
311 &ExportSettings { format: Format::Wav, range, ..Default::default() },
312 None,
313 );
314 let started = std::time::Instant::now();
315 while !handle.is_finished() {
316 assert!(started.elapsed().as_secs() < 60, "export hung");
317 std::thread::sleep(std::time::Duration::from_millis(10));
318 }
319 handle.result().expect("an outcome").expect("a wav");
320 let (_, chunks) = AudioSession::open(&out).unwrap().unwrap();
321 chunks.into_iter().flat_map(|c| c.samples).collect()
322 };
323 // 30 fps, and the two rates whose frames are no whole number of samples: the range
324 // starts where rounding the pre-roll's own length would land one sample off.
325 for (name, fps, pre) in [("30", 30.0, 15u32), ("29.97", 30000.0 / 1001.0, 15), ("23.976", 24000.0 / 1001.0, 12)] {
326 let at = |f: u32| (f64::from(f) / fps * f64::from(RATE)).round() as usize;
327 let lone = |pre: u32| (f64::from(pre) / fps * f64::from(RATE)).round() as usize;
328 let from = if fps == 30.0 {
329 60
330 } else {
331 (pre..120).find(|&f| at(f) - at(f - pre) != lone(pre)).expect("a start where the roundings part")
332 };
333 let to = from + (fps * 1.5) as u32;
334 let full = export(fps, None, &format!("full_{name}.wav"));
335 let ranged = export(fps, Some((from, to)), &format!("ranged_{name}.wav"));
336 let want = (f64::from(to - from) / fps * f64::from(RATE)).round() as usize * 2;
337 assert!(ranged.len().abs_diff(want) <= 4, "{name}: the range is {} samples, not {want}", ranged.len());
338 // The first second of the range against the same second of the full file, at the
339 // same sample: any lag but none is a miss.
340 let span = RATE as usize * 2; // one second, two channels
341 let start = at(from) * 2;
342 let worst = |lag: isize| {
343 let b = &full[start.wrapping_add_signed(lag * 2)..];
344 ranged[..span].iter().zip(b).map(|(x, y)| (x - y).abs()).fold(0.0f32, f32::max)
345 };
346 let best = (-2isize..=2).min_by(|&p, &q| worst(p).total_cmp(&worst(q))).unwrap();
347 assert_eq!(best, 0, "{name}: the ranged export sits {best} samples off the full one");
348 // The noise reduction's frames sit on a grid counted from where the mix opened, so the
349 // left-over noise differs a little; the difference stays some 60 dB down.
350 let err = ranged[..span].iter().zip(&full[start..]).map(|(x, y)| f64::from(x - y).powi(2)).sum::<f64>() / span as f64;
351 let err_db = 10.0 * err.log10();
352 assert!(err_db < -50.0, "{name}: the ranged export's first second differs by {err_db:.1} dB rms");
353 }
354}