forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

eq_audio.rs443 lines, 16.5 KiBHistoryRawDownload
1//! The per-clip equalizer where it has to be true: in the samples playback
2//! feeds the device and in the samples an export writes, which are the same
3//! samples by construction — both come off `AudioSession::open_mixed_streams_eq`
4//! and the filter runs inside the per-lane worker, per segment, before the mix.
5//!
6//! Everything here goes through the *front door*: a `Project` is edited with
7//! `set_eq` and then read exactly as `PlaybackSession::seek` reads it
8//! (`audio_segments_from` + `audio_eqs_from` handed to the same opener), or
9//! exported through `engine::export::start`. Nothing calls `EqState` directly —
10//! `eq.rs`'s own unit tests own the filter maths; what is checked here is the
11//! wiring: that a curve reaches its clip, only its clip, and reaches it the same
12//! way in both directions.
13//!
14//! The fixtures are a 440 Hz / 880 Hz stereo tone (`gen_fixtures.sh`), so a low
15//! shelf with its corner above both tones is a flat +12 dB on everything
16//! audible: the expected RMS ratio is 10^(12/20) ≈ 3.98, and it is asserted as a
17//! ratio, never as a level.
18//!
19//! No picture is decoded, so nothing here needs the hardware plugin.
20
21use std::path::{Path, PathBuf};
22use std::time::{Duration, Instant};
23
24use engine::eq::{Band, BandKind, EqParams};
25use engine::export::{ExportSettings, Format};
26use engine::project::{Lane, LaneKind, Source, Speed};
27use engine::scale::FitPolicy;
28use engine::scratch::Scratch;
29use engine::{AudioSession, Clip, ExportHandle, Project};
30
31const RATE: u32 = 44_100;
32const FPS: f64 = 30.0;
33
34/// +12 dB below 2 kHz: above both fixture tones, so every audible sample in
35/// them is lifted by the shelf's full gain.
36const BOOST_DB: f32 = 12.0;
37
38fn asset(name: &str) -> PathBuf {
39 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
40 .join("../../assets")
41 .join(name)
42}
43
44fn boost() -> EqParams {
45 EqParams {
46 bands: vec![Band {
47 freq_hz: 2000.0,
48 gain_db: BOOST_DB,
49 q: 0.707,
50 kind: BandKind::LowShelf,
51 }],
52 }
53}
54
55fn clip(start: u32, source: usize, frames: u32) -> Clip {
56 Clip {
57 speed_keys: Vec::new(),
58 reversed: false,
59 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
60 angle: Default::default(),
61 fade_in: 0,
62 fade_out: 0,
63 transition_out: 0,
64 transition_kind: Default::default(),
65 visualizer: 0,
66 viz_paint: 0,
67 gain_db: 0.0,
68 gain_keys: Vec::new(),
69 pan: 0,
70 pitch: 0.0,
71 transform_keys: Vec::new(),
72 opacity_keys: Vec::new(),
73 color_keys: Vec::new(),
74 effects: Vec::new(),
75 start,
76 in_frame: 0,
77 out_frame: frames,
78 source,
79 link: None,
80 eq: None,
81 color: None,
82 fit: FitPolicy::default(),
83 speed: Speed::NORMAL,
84 transform: None,
85 }
86}
87
88/// One video clip and `audio` on `A1`, from `test_av.mp4` alone.
89fn project(audio: Vec<Clip>) -> Project {
90 let frames = audio.iter().map(Clip::end).max().unwrap_or(30);
91 Project::from_parts(
92 vec![Source::new(asset("test_av.mp4"), 0)],
93 vec![
94 (LaneKind::Video, vec![clip(0, 0, frames)]),
95 (LaneKind::Audio, audio),
96 ],
97 Vec::new(),
98 Vec::new(),
99 Vec::new(),
100 )
101 .expect("a one-source project")
102}
103
104/// What the device would be fed: the exact call `PlaybackSession::seek` makes,
105/// drained to the end. This *is* the feeder path minus the ring buffer.
106fn play(project: &Project) -> Vec<f32> {
107 let sources = project.audio_sources();
108 let segs = project.audio_segments_from(0, FPS);
109 let eqs = project.audio_eqs_from(0, FPS);
110 let (meta, chunks) = AudioSession::open_mixed_streams_eq(&sources, &segs, &eqs)
111 .expect("open the timeline's audio")
112 .expect("the timeline has audio");
113 assert_eq!((meta.sample_rate, meta.channels), (RATE, 2));
114 let mut samples = Vec::new();
115 for chunk in chunks {
116 samples.extend(chunk.samples);
117 }
118 samples
119}
120
121/// Root mean square of `[from, to)` seconds of the interleaved stereo stream.
122fn rms(samples: &[f32], from: f64, to: f64) -> f64 {
123 let at = |secs: f64| (secs * f64::from(RATE)) as usize * 2;
124 let window = &samples[at(from).min(samples.len())..at(to).min(samples.len())];
125 assert!(!window.is_empty(), "no samples in [{from}, {to})");
126 (window
127 .iter()
128 .map(|s| f64::from(*s) * f64::from(*s))
129 .sum::<f64>()
130 / window.len() as f64)
131 .sqrt()
132}
133
134/// The shelf's own gain, to within a fifth of a dB either way -- the filter is
135/// exact, the tone is not perfectly band-limited, and the fixtures' 1 Hz pulse
136/// makes any window a mixture.
137fn assert_boosted(ratio: f64, what: &str) {
138 let db = 20.0 * ratio.log10();
139 println!("{what}: ratio {ratio:.3} = {db:+.2} dB");
140 assert!(
141 (db - f64::from(BOOST_DB)).abs() < 0.5,
142 "{what} measured {db:+.2} dB, the band asks for {BOOST_DB:+.1}"
143 );
144}
145
146fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
147 let started = Instant::now();
148 while !handle.is_finished() {
149 assert!(
150 started.elapsed() < limit,
151 "export did not finish in {limit:?}"
152 );
153 std::thread::sleep(Duration::from_millis(10));
154 }
155 handle.result().expect("a finished export has an outcome")
156}
157
158fn out_path(name: &str, ext: &str) -> Scratch {
159 Scratch::file(&format!("ve_eq_{name}"), ext)
160}
161
162fn meta() -> engine::VideoMeta {
163 engine::demux::Demuxer::open(&asset("test_av.mp4"))
164 .expect("open test_av")
165 .0
166}
167
168/// Samples of a written file back through the engine's own reader.
169fn decode(path: &Path) -> Vec<f32> {
170 let (_, chunks) = AudioSession::open(path)
171 .expect("reopen the export")
172 .expect("the export has audio");
173 let mut samples = Vec::new();
174 for chunk in chunks {
175 samples.extend(chunk.samples);
176 }
177 samples
178}
179
180/// The whole claim in one line: a clip given a band comes out of the feeder
181/// path that much louder than the same clip without it -- and a project nobody
182/// has equalized comes out of the *new* opener bit for bit what the old one
183/// gave, which is the identity promise the rest of the engine rests on.
184#[test]
185fn an_equalized_clip_plays_that_much_louder_and_a_flat_one_not_at_all() {
186 let flat = project(vec![clip(0, 0, 30)]);
187 let mut eqd = flat.clone();
188 assert!(eqd.set_eq(Lane::A1, 0, Some(boost())));
189
190 let plain = play(&flat);
191 let boosted = play(&eqd);
192 assert_eq!(
193 plain.len(),
194 boosted.len(),
195 "the edit is a filter, not a trim"
196 );
197 assert_boosted(
198 rms(&boosted, 0.05, 0.95) / rms(&plain, 0.05, 0.95),
199 "playback",
200 );
201
202 // No equalizer anywhere: the samples are the ones the opener gave before
203 // there was an equalizer at all, to the bit.
204 let sources = flat.audio_sources();
205 let segs = flat.audio_segments_from(0, FPS);
206 let (_, chunks) = AudioSession::open_mixed_streams(&sources, &segs)
207 .expect("open")
208 .expect("has audio");
209 let old: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
210 assert_eq!(old, plain, "an EQ-less project must decode bit-identically");
211
212 // ...and so does one carrying a curve that moves nothing: `is_identity`
213 // short-circuits inside `EqState::process`, and this is the path that says
214 // the short-circuit is really on.
215 let mut identity = flat.clone();
216 assert!(identity.set_eq(Lane::A1, 0, Some(EqParams::default_layout())));
217 assert!(identity.eq_of(Lane::A1, 0).is_some(), "the curve is stored");
218 assert_eq!(
219 play(&identity),
220 plain,
221 "a flat curve must not touch a sample"
222 );
223}
224
225/// The reason the filter lives in the worker and not over the mix: two clips
226/// with different settings must not bleed into each other. One second boosted,
227/// one second not, on one lane, out of one decoder.
228#[test]
229fn a_band_reaches_its_own_clip_and_stops_at_the_cut() {
230 let mut p = project(vec![clip(0, 0, 30), clip(30, 0, 30)]);
231 let plain = play(&p);
232 assert!(p.set_eq(Lane::A1, 1, Some(boost())));
233 let boosted = play(&p);
234
235 assert_boosted(
236 rms(&boosted, 1.05, 1.95) / rms(&plain, 1.05, 1.95),
237 "the equalized second clip",
238 );
239 // The clip before it is untouched -- and untouched to the *bit*, not merely
240 // to a level: a filter whose memory carried across the join would show up
241 // here as a fraction of a dB and pass any ratio test.
242 let second = (1.0 * f64::from(RATE)) as usize * 2;
243 assert_eq!(
244 boosted[..second],
245 plain[..second],
246 "the flat clip before the cut moved"
247 );
248}
249
250/// Two lanes, a band on one of them: the sum must differ by exactly what that
251/// lane's own samples changed by, which is only true if each lane is filtered
252/// before it is added. Filtering the mix instead would smear the curve over the
253/// other lane as well, and this is the difference that would show it.
254#[test]
255fn a_lane_is_equalized_before_the_mix_and_never_after_it() {
256 let mut p = Project::from_parts(
257 vec![Source::new(asset("test_av.mp4"), 0)],
258 vec![
259 (LaneKind::Video, vec![clip(0, 0, 30)]),
260 (LaneKind::Audio, vec![clip(0, 0, 30)]),
261 (LaneKind::Audio, vec![clip(0, 0, 30)]),
262 ],
263 Vec::new(),
264 Vec::new(),
265 Vec::new(),
266 )
267 .expect("a two-audio-lane project");
268 assert_eq!(p.audio_lanes().len(), 2, "both lanes hold something");
269
270 let mixed = play(&p);
271 let a2 = Lane::new(LaneKind::Audio, 1);
272 assert!(p.set_eq(a2, 0, Some(boost())));
273 let mixed_eqd = play(&p);
274
275 // What A2 alone sounds like either way, taken off the single-lane path.
276 let lone = project(vec![clip(0, 0, 30)]);
277 let mut lone_eqd = lone.clone();
278 assert!(lone_eqd.set_eq(Lane::A1, 0, Some(boost())));
279 let (flat, boosted) = (play(&lone), play(&lone_eqd));
280
281 let n = mixed
282 .len()
283 .min(mixed_eqd.len())
284 .min(flat.len())
285 .min(boosted.len());
286 let mut worst = 0.0f32;
287 for i in 0..n {
288 worst = worst.max(((mixed_eqd[i] - mixed[i]) - (boosted[i] - flat[i])).abs());
289 }
290 println!("mix-vs-lane worst difference: {worst:e}");
291 // Not zero: the two runs decode the same source twice and AAC's noise
292 // substitution reseeds per decoder (`open_segments`, measured below 1e-3).
293 assert!(
294 worst < 1e-3,
295 "the mix changed by {worst} more than the equalized lane did -- the filter is on the sum"
296 );
297}
298
299/// The export half of the same claim, through `export::start`: what is written
300/// is what is heard, so both audio-only formats carry the boost at the same
301/// ratio the feeder path measured. Both, because both are lossless and both are
302/// one `run_audio` -- a FLAC that disagreed with the WAV beside it would be the
303/// writer, and this is where that would show.
304#[test]
305fn the_audio_only_exports_carry_the_same_boost_playback_does() {
306 let flat = project(vec![clip(0, 0, 30)]);
307 let mut eqd = flat.clone();
308 assert!(eqd.set_eq(Lane::A1, 0, Some(boost())));
309
310 for format in [Format::Wav, Format::Flac] {
311 let mut written = Vec::new();
312 for (name, project) in [("flat", &flat), ("eqd", &eqd)] {
313 let out = out_path(name, format.ext());
314 let handle = engine::export::start(
315 project.clone(),
316 meta(),
317 &out,
318 &ExportSettings {
319 format,
320 ..Default::default()
321 },
322 None,
323 );
324 wait(&handle, Duration::from_secs(60)).expect("an audio-only export");
325 written.push(decode(&out));
326 std::fs::remove_file(&out).unwrap();
327 }
328 let [plain, boosted] = &written[..] else {
329 unreachable!("two exports")
330 };
331 assert_boosted(
332 rms(boosted, 0.05, 0.95) / rms(plain, 0.05, 0.95),
333 format.name(),
334 );
335 // ...and the same number to the ear: the export is not a second, kinder
336 // filter run at a different point in the chain.
337 let played = rms(&play(&eqd), 0.05, 0.95) / rms(&play(&flat), 0.05, 0.95);
338 let exported = rms(boosted, 0.05, 0.95) / rms(plain, 0.05, 0.95);
339 assert!(
340 (played - exported).abs() < 0.05,
341 "playback boosted by {played:.3} and {} by {exported:.3}",
342 format.name()
343 );
344 }
345}
346
347/// An mp4 export *copies* AAC packets and no filter can reach a copy, so an
348/// equalized lane is decoded, mixed and encoded again instead
349/// (`export::encode_audio`). The claim is the same one the WAV makes: the boost
350/// is in the file, on the clip that was given it and on no other -- and the
351/// track still starts where the picture does, which is what the encoder's own
352/// priming packet is for.
353#[test]
354fn an_mp4_export_carries_the_boost_a_packet_copy_could_not() {
355 let flat = project(vec![clip(0, 0, 30), clip(30, 0, 30)]);
356 let mut eqd = flat.clone();
357 assert!(eqd.set_eq(Lane::A1, 1, Some(boost())));
358
359 let mut written = Vec::new();
360 for (name, project) in [("flat", &flat), ("eqd", &eqd)] {
361 let out = out_path(name, "mp4");
362 let settings = ExportSettings::default();
363 let handle = engine::export::start(project.clone(), meta(), &out, &settings, None);
364 wait(&handle, Duration::from_secs(180)).expect("an equalized timeline exports as mp4");
365 written.push(decode(&out));
366 std::fs::remove_file(&out).unwrap();
367 }
368 let [plain, boosted] = &written[..] else {
369 unreachable!("two exports")
370 };
371
372 // Two seconds of timeline, to within the one 1024-frame packet the length
373 // rounds up to: an encoder delay left uncompensated would show up here as a
374 // whole packet of shift, and in the windows below as a smeared cut.
375 let secs = |s: &[f32]| s.len() as f64 / 2.0 / f64::from(RATE);
376 println!(
377 "mp4 lengths: flat {:.3}s, eqd {:.3}s",
378 secs(plain),
379 secs(boosted)
380 );
381 for samples in [plain, boosted] {
382 assert!(
383 (secs(samples) - 2.0).abs() < 1024.0 / f64::from(RATE),
384 "the exported track is {:.3}s of a 2.000s timeline",
385 secs(samples)
386 );
387 }
388
389 // The boost itself. Not to `assert_boosted`'s fifth of a dB: this file is
390 // AAC at 128 kbps measured against a *copied* one, so a fraction of a dB is
391 // the codec, not the filter. A dB either way is far tighter than the 12 the
392 // band asks for and far wider than any coding noise.
393 let db = 20.0 * (rms(boosted, 1.05, 1.95) / rms(plain, 1.05, 1.95)).log10();
394 println!("mp4 equalized clip: {db:+.2} dB");
395 assert!(
396 (db - f64::from(BOOST_DB)).abs() < 1.0,
397 "the equalized clip in the mp4 measured {db:+.2} dB, the band asks for {BOOST_DB:+.1}"
398 );
399 // The clip before it is the same sound: not to the bit -- this file is a
400 // re-encode and that one is a copy -- but to a fraction of a dB, which is
401 // what says the filter stopped at the cut rather than lifting the lot.
402 let leak = 20.0 * (rms(boosted, 0.05, 0.95) / rms(plain, 0.05, 0.95)).log10();
403 println!("mp4 flat clip moved {leak:+.2} dB");
404 assert!(leak.abs() < 0.5, "the flat clip moved {leak:+.2} dB");
405
406 // ...and a timeline nobody equalized never reaches the encoder at all: its
407 // audio track is still the source's own packets, which
408 // `export::exported_packets_are_the_copied_stream` holds to the byte.
409}
410
411/// A band moved while the timeline is playing: `PlaybackSession::set_eq` writes
412/// the project and reseeks, and a reseek rebuilds the workers from
413/// `audio_eqs_from`. This is that mechanism without a sound device -- the edit,
414/// then the very list the reopen is built from, then the samples it yields.
415#[test]
416fn a_band_changed_mid_play_is_in_the_next_chunk_the_worker_makes() {
417 let mut p = project(vec![clip(0, 0, 30)]);
418 assert!(
419 p.audio_eqs_from(0, FPS)[0][0].is_none(),
420 "flat to begin with"
421 );
422 let before = play(&p);
423
424 assert!(p.set_eq(Lane::A1, 0, Some(boost())));
425 // The reopen list is rebuilt from the project every seek, so the edit is in
426 // it the moment it lands -- no channel has to reach into a running worker.
427 assert_eq!(
428 p.audio_eqs_from(0, FPS)[0][0].as_ref(),
429 Some(&boost()),
430 "the seek's own list carries the new curve"
431 );
432 let after = play(&p);
433 assert_ne!(before, after, "the samples changed");
434 assert_boosted(
435 rms(&after, 0.05, 0.95) / rms(&before, 0.05, 0.95),
436 "after the edit",
437 );
438
439 // And undo is the way back, one step, samples and all.
440 assert!(p.undo());
441 assert!(p.audio_eqs_from(0, FPS)[0][0].is_none());
442 assert_eq!(play(&p), before, "undo puts the flat samples back");
443}