forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB6a8d990Tahinli15 days ago1049 commits

normalize.rs746 lines, 27.3 KiBHistoryRawDownload
1//! Loudness measurement and normalization of the timeline: the core `normalize`
2//! (MCP) and the mix card's Normalize (GUI) share.
3//!
4//! A lane is measured the way the engine plays it (clip speeds, equalizers,
5//! fades, gaps and its ducks included, lane gain not applied -- the caller adds
6//! it), the mix by rendering it the way an export writes it. [`normalize`] moves
7//! lane gain, with the part of a boost past the lane cap going on the lane's
8//! clips as clip gain, and measures after each change until the level lands.
9
10use std::path::PathBuf;
11use std::sync::mpsc::Receiver;
12use std::time::{Duration, SystemTime, UNIX_EPOCH};
13
14use crate::duck::Ducker;
15use crate::export::{ExportSettings, Format};
16use crate::loudness::{self, Loudness, Meter};
17use crate::project::{Lane, LaneKind, MAX_CLIP_GAIN_DB, MAX_GAIN_DB, MIN_GAIN_DB};
18use crate::silence::WINDOWS_PER_SEC;
19use crate::{AudioChunk, AudioMeta, AudioSession, Clip, PlaybackSession};
20
21/// The refusal for reading `what` (a target's name) while a source it plays is offline: named,
22/// with its path and the fix, the way the mix refuses. `None` when every source it reads is on disk.
23pub fn offline_refusal_for(s: &PlaybackSession, what: impl std::fmt::Display, sources: &[usize]) -> Option<String> {
24 let offline: Vec<String> = s
25 .offline_sources()
26 .into_iter()
27 .filter(|(i, _)| sources.contains(i))
28 .map(|(i, p)| format!("src:{i} {}", p.display()))
29 .collect();
30 if offline.is_empty() {
31 return None;
32 }
33 Some(format!(
34 "reading {what} refused: {} source(s) offline (moved or deleted): {}; media_relink each one, or project_open with search",
35 offline.len(),
36 offline.join(", ")
37 ))
38}
39
40/// The reason a mix cannot be rendered while sources are offline: named, with the fix, the way
41/// `export` refuses. `None` when every source is on disk.
42pub fn offline_refusal(s: &PlaybackSession) -> Option<String> {
43 let offline = s.offline_sources();
44 if offline.is_empty() {
45 return None;
46 }
47 let names: Vec<String> = offline.iter().map(|(i, p)| format!("src:{i} {}", p.display())).collect();
48 Some(format!(
49 "rendering the mix refused: {} source(s) offline (moved or deleted): {}; media_relink each one, or project_open with search",
50 offline.len(),
51 names.join(", ")
52 ))
53}
54
55/// `l` moved by `db`, as the engine plays it with a lane gain. Every finite
56/// level shifts by the same amount; the loudness range is a difference and stays.
57pub fn shifted(l: Loudness, db: f64) -> Loudness {
58 let up = |x: f64| if x.is_finite() { x + db } else { x };
59 Loudness {
60 integrated_lufs: up(l.integrated_lufs),
61 range_lu: l.range_lu,
62 true_peak_dbtp: up(l.true_peak_dbtp),
63 sample_peak_dbfs: up(l.sample_peak_dbfs),
64 momentary_max_lufs: up(l.momentary_max_lufs),
65 short_term_max_lufs: up(l.short_term_max_lufs),
66 analysed_secs: l.analysed_secs,
67 lra_samples: l.lra_samples,
68 }
69}
70
71/// The sound a lane makes from timeline frame `from`, as the engine plays it:
72/// clip speeds, equalizers, fades, gaps and the lane's voice processors included. Lane gain is not applied.
73/// `None` when the file set has no audio.
74pub fn open_lane(
75 s: &PlaybackSession,
76 lane: Lane,
77 from: u32,
78 fps: f64,
79) -> Result<Option<(AudioMeta, Receiver<AudioChunk>)>, String> {
80 let used: Vec<usize> = s.lane_clips(lane).iter().map(|c| c.source).collect();
81 if let Some(why) = offline_refusal_for(s, lane.label(), &used) {
82 return Err(why);
83 }
84 let (project, _) = s.export_snapshot();
85 let segs = project.lane_segments_from(lane, from, fps);
86 let speeds = project.lane_speeds_from(lane, from, fps);
87 let eqs = project.lane_eqs_from(lane, from, fps);
88 // The fade envelope carries each clip's own gain as well as its fades, the
89 // same envelope playback and export are handed.
90 let fades = project.lane_fades_from(lane, from, fps);
91 let sources: Vec<(PathBuf, usize)> = project
92 .sources()
93 .iter()
94 .map(|src| (src.path.clone(), src.audio_stream))
95 .collect();
96 let opened = AudioSession::open_multi_streams_speed_at_fade(&sources, &segs, &eqs, &speeds, &fades, fps, None)
97 .map_err(|e| format!("reading {}: {e}", lane.label()))?;
98 let voice = s.lane_voice(lane);
99 Ok(opened.map(|(meta, rx)| match voice.is_active() {
100 true => {
101 let rx = crate::voice::spawn_stage(rx, &voice, meta.sample_rate, usize::from(meta.channels));
102 (meta, rx)
103 }
104 false => (meta, rx),
105 }))
106}
107
108
109/// The lane under a duck, read the way the mixer plays it: the key lane's sound
110/// after its gain keys the duck, and the duck reduces this lane's own sound.
111/// Read from timeline frame 0, so the detector has the same history it has in
112/// the mix. Gain is not applied to the lane, only to the keys. A lane can have
113/// several ducks; each one is applied in turn, as the mixer applies them.
114pub struct Ducked {
115 pub rate: u32,
116 pub channels: usize,
117 /// Frames still to read, up to the end of the span.
118 left: u64,
119 /// The first frame of the next block.
120 at: u64,
121 /// One per duck on the lane, in the order the lane holds them.
122 keys: Vec<KeyDuck>,
123 /// The lane's own sound; `None` when only the duck's gain is wanted, in
124 /// which case each block is that gain (1.0 at rest) and the lane is unread.
125 lane: Option<Feed>,
126}
127
128/// One duck on a lane: its key's sound, the key's lane gain and the detector.
129struct KeyDuck {
130 key: Feed,
131 /// The key's lane gain as a factor, not dB.
132 key_gain: f32,
133 ducker: Ducker,
134}
135
136/// One stream's chunks, drained a block at a time.
137struct Feed {
138 rx: Receiver<AudioChunk>,
139 pending: Vec<f32>,
140 live: bool,
141}
142
143impl Feed {
144 /// Waits for a chunk unless one is pending already or the stream has ended.
145 fn fill(&mut self) {
146 while self.live && self.pending.is_empty() {
147 match self.rx.recv() {
148 Ok(chunk) => self.pending = chunk.samples,
149 Err(_) => self.live = false,
150 }
151 }
152 }
153}
154
155impl Ducked {
156 /// The ducks on `lane`, read up to timeline frame `to`. `None` when there is
157 /// nothing to duck: no duck, no duck whose key lane has clips, or no sound
158 /// to read.
159 pub fn open(
160 s: &PlaybackSession,
161 lane: Lane,
162 to: u32,
163 fps: f64,
164 gain_only: bool,
165 ) -> Result<Option<Self>, String> {
166 let mut keys = Vec::new();
167 let mut first: Option<(u32, usize)> = None;
168 for duck in s.lane_duck_list(lane) {
169 let key_lane = Lane::new(LaneKind::Audio, duck.under);
170 if s.lane_clips(key_lane).is_empty() {
171 continue;
172 }
173 let Some((meta, key_rx)) = open_lane(s, key_lane, 0, fps)? else {
174 continue;
175 };
176 first.get_or_insert((meta.sample_rate, usize::from(meta.channels).max(1)));
177 keys.push(KeyDuck {
178 key: Feed {
179 rx: key_rx,
180 pending: Vec::new(),
181 live: true,
182 },
183 key_gain: 10f32.powf(s.lane_gain_db(key_lane) / 20.0),
184 ducker: Ducker::new(&duck, meta.sample_rate),
185 });
186 }
187 let Some((rate, channels)) = first else {
188 return Ok(None);
189 };
190 let lane_feed = if gain_only {
191 None
192 } else {
193 match open_lane(s, lane, 0, fps)? {
194 Some((_, rx)) => Some(Feed {
195 rx,
196 pending: Vec::new(),
197 live: true,
198 }),
199 None => return Ok(None),
200 }
201 };
202 Ok(Some(Self {
203 rate,
204 channels,
205 left: (f64::from(to) / fps * f64::from(rate)).round() as u64,
206 at: 0,
207 keys,
208 lane: lane_feed,
209 }))
210 }
211
212 /// The next block of ducked samples (interleaved) and the frame it starts
213 /// at, or `None` once the span or the lane's sound is done. Blocks follow
214 /// the mixer's: the frames every live stream has pending, no more.
215 #[allow(clippy::should_implement_trait)]
216 pub fn next(&mut self) -> Option<(u64, Vec<f32>)> {
217 let ch = self.channels;
218 for k in self.keys.iter_mut() {
219 k.key.fill();
220 }
221 if let Some(lane) = self.lane.as_mut() {
222 lane.fill();
223 if !lane.live && lane.pending.is_empty() {
224 return None;
225 }
226 }
227 let frames = self
228 .keys
229 .iter()
230 .map(|k| &k.key)
231 .chain(self.lane.as_ref())
232 .filter(|f| !f.pending.is_empty())
233 .map(|f| f.pending.len() / ch)
234 .min()?;
235 let frames = frames.min(usize::try_from(self.left).unwrap_or(usize::MAX));
236 if frames == 0 {
237 return None;
238 }
239 self.left -= frames as u64;
240 let n = frames * ch;
241 let mut block: Vec<f32> = match self.lane.as_mut() {
242 Some(feed) if feed.pending.is_empty() => vec![0.0; n],
243 Some(feed) => feed.pending.drain(..n).collect(),
244 None => vec![1.0; n],
245 };
246 for k in self.keys.iter_mut() {
247 let gain = k.key_gain;
248 let key: Vec<f32> = if k.key.pending.is_empty() {
249 vec![0.0; n]
250 } else {
251 k.key.pending.drain(..n).map(|x| x * gain).collect()
252 };
253 k.ducker.process(&key, &mut block, ch);
254 }
255 let at = self.at;
256 self.at += frames as u64;
257 Some((at, block))
258 }
259}
260
261/// The sound a lane makes over timeline frames `from..to`, as the engine plays
262/// it: clip speeds, equalizers and gaps included, and its duck if it has one.
263/// Lane gain is not applied; the caller adds it. `None` when there is no sound.
264type MeasureKey = (u64, Option<Lane>, u32, u32, u64);
265
266static MEASURED: std::sync::Mutex<Vec<(MeasureKey, Option<Loudness>)>> = std::sync::Mutex::new(Vec::new());
267
268fn remembered(
269 key: MeasureKey,
270 measure: impl FnOnce() -> Result<Option<Loudness>, String>,
271) -> Result<Option<Loudness>, String> {
272 if let Some(hit) = MEASURED.lock().ok().and_then(|m| m.iter().find(|(k, _)| *k == key).map(|(_, l)| *l)) {
273 return Ok(hit);
274 }
275 let got = measure()?;
276 if let Ok(mut m) = MEASURED.lock() {
277 if m.len() >= 32 {
278 m.remove(0);
279 }
280 m.push((key, got));
281 }
282 Ok(got)
283}
284
285pub fn measure_lane(
286 s: &PlaybackSession,
287 lane: Lane,
288 from: u32,
289 to: u32,
290 fps: f64,
291) -> Result<Option<Loudness>, String> {
292 remembered((s.revision(), Some(lane), from, to, fps.to_bits()), || measure_lane_now(s, lane, from, to, fps))
293}
294
295fn measure_lane_now(
296 s: &PlaybackSession,
297 lane: Lane,
298 from: u32,
299 to: u32,
300 fps: f64,
301) -> Result<Option<Loudness>, String> {
302 if let Some(mut ducked) = Ducked::open(s, lane, to, fps, false)? {
303 let from_at = (f64::from(from) / fps * f64::from(ducked.rate)).round() as u64;
304 let ch = ducked.channels;
305 let mut meter = Meter::new(ducked.rate, ducked.channels as u16);
306 while let Some((at, block)) = ducked.next() {
307 let skip = from_at.saturating_sub(at).min((block.len() / ch) as u64);
308 meter.push(&block[skip as usize * ch..]);
309 }
310 return Ok(Some(meter.finish()));
311 }
312 let Some((meta, rx)) = open_lane(s, lane, from, fps)? else {
313 return Ok(None);
314 };
315 let channels = usize::from(meta.channels).max(1);
316 // The span in interleaved samples; the engine plays past it, so stop there.
317 let mut left = (to > from).then(|| {
318 let frames = f64::from(to - from) / fps * f64::from(meta.sample_rate);
319 frames.round() as usize * channels
320 });
321 let mut meter = Meter::new(meta.sample_rate, meta.channels);
322 for chunk in rx {
323 let mut part: &[f32] = &chunk.samples;
324 if let Some(n) = left.as_mut() {
325 let take = (*n).min(part.len());
326 part = &part[..take];
327 *n -= take;
328 }
329 meter.push(part);
330 if left == Some(0) {
331 break;
332 }
333 }
334 Ok(Some(meter.finish()))
335}
336
337/// The dB a lane's duck takes off each 20 ms window of timeline time, from time
338/// 0 to frame `to`, indexed by window: the power mean of the duck's gain over
339/// the window. Empty when the lane has no duck that does anything.
340pub fn duck_offsets(s: &PlaybackSession, lane: Lane, to: u32, fps: f64) -> Result<Vec<f32>, String> {
341 let Some(mut ducked) = Ducked::open(s, lane, to, fps, true)? else {
342 return Ok(Vec::new());
343 };
344 let w = u64::from(WINDOWS_PER_SEC);
345 let rate = u64::from(ducked.rate);
346 let windows = (f64::from(to) / fps * f64::from(WINDOWS_PER_SEC)).ceil() as usize + 1;
347 // Power sum and count per window, over channel 0 (the gain is the same in
348 // every channel).
349 let mut power = vec![(0f64, 0u64); windows];
350 while let Some((at, gains)) = ducked.next() {
351 for (i, g) in gains.iter().step_by(ducked.channels).enumerate() {
352 let k = ((at + i as u64) * w / rate) as usize;
353 if let Some(slot) = power.get_mut(k) {
354 slot.0 += f64::from(*g) * f64::from(*g);
355 slot.1 += 1;
356 }
357 }
358 }
359 Ok(power
360 .iter()
361 .map(|&(sum, n)| {
362 if n == 0 {
363 0.0
364 } else {
365 (10.0 * (sum / n as f64).max(1e-12).log10()) as f32
366 }
367 })
368 .collect())
369}
370
371/// Deletes its file when dropped, so a failed render leaves nothing behind.
372pub struct TempWav(pub PathBuf);
373
374impl Drop for TempWav {
375 fn drop(&mut self) {
376 let _ = std::fs::remove_file(&self.0);
377 }
378}
379
380/// The mix (see `render_mix`) measured over timeline frames `from..to`. `end` is the
381/// timeline length, so a span that covers all of it is measured without a cut.
382pub fn measure_mix(
383 s: &PlaybackSession,
384 from: u32,
385 to: u32,
386 fps: f64,
387 end: u32,
388) -> Result<Loudness, String> {
389 remembered((s.revision(), None, from, to.min(end), fps.to_bits()), || measure_mix_now(s, from, to, fps, end).map(Some))?
390 .ok_or_else(|| "the mix has no sound track".to_string())
391}
392
393fn measure_mix_now(
394 s: &PlaybackSession,
395 from: u32,
396 to: u32,
397 fps: f64,
398 end: u32,
399) -> Result<Loudness, String> {
400 let wav = render_mix(s)?;
401 let range = (from > 0 || to < end).then(|| {
402 let end_s = if to >= end {
403 f64::INFINITY
404 } else {
405 f64::from(to) / fps
406 };
407 (f64::from(from) / fps, end_s)
408 });
409 loudness::measure_file(&wav.0, 0, range)
410 .map_err(|e| format!("measuring the mix: {e}"))?
411 .ok_or_else(|| "the mix has no sound track".to_string())
412}
413
414pub fn clamp_gain(db: f64) -> f64 {
415 db.clamp(f64::from(MIN_GAIN_DB), f64::from(MAX_GAIN_DB))
416}
417
418/// A lane `normalize` sets, with the gains it held before: its lane gain, and each clip's
419/// (index, clip gain) for the part of a boost the lane cap leaves, which goes on the clips.
420pub struct Plan {
421 pub lane: Lane,
422 pub old: f64,
423 pub clips: Vec<(usize, f64)>,
424}
425
426/// A lane as it stands before a normalize changes anything.
427pub fn plan_of(s: &PlaybackSession, lane: Lane) -> Plan {
428 let clips = (0..s.lane_clips(lane).len())
429 .map(|i| (i, f64::from(s.clip_gain_of(lane, i).unwrap_or(0.0))))
430 .collect();
431 Plan { lane, old: f64::from(s.lane_gain_db(lane)), clips }
432}
433
434/// Sets each plan's lane to its old gain plus `gain`, clamped to the lane range. The part of a boost
435/// past the lane's +12 dB cap goes on the lane's clips instead: each clip's gain is its old one plus
436/// that rest, clamped to the clip range, so a clip that already has gain keeps it. Returns the lanes
437/// that could not take all of it, as (name, wanted, got): `wanted` is the lane gain asked for and
438/// `got` the lane gain reached with the clips' best take added.
439pub fn set_plans(s: &mut PlaybackSession, plans: &[Plan], gain: f64) -> Vec<(String, f64, f64)> {
440 let mut clamped = Vec::new();
441 for p in plans {
442 let wanted = p.old + gain;
443 let lane_db = clamp_gain(wanted);
444 let rest = (wanted - f64::from(MAX_GAIN_DB)).max(0.0);
445 s.set_lane_gain_db(p.lane, lane_db as f32);
446 // The gain each clip took on top of its old one.
447 let mut took = Vec::with_capacity(p.clips.len());
448 for &(i, old) in &p.clips {
449 let to = (old + rest).min(f64::from(MAX_CLIP_GAIN_DB));
450 s.set_clip_gain(p.lane, i, to as f32);
451 took.push(to - old);
452 }
453 if wanted > f64::from(MAX_GAIN_DB) {
454 // The lane is held only when no clip can take the whole rest.
455 let best = took.iter().copied().fold(0.0_f64, f64::max);
456 if rest - best > 0.05 {
457 clamped.push((p.lane.label(), wanted, f64::from(MAX_GAIN_DB) + best));
458 }
459 } else if lane_db != wanted {
460 clamped.push((p.lane.label(), wanted, lane_db));
461 }
462 }
463 clamped
464}
465
466/// The whole timeline rendered the way an export writes it (every unmuted lane at its gain) to a
467/// temporary WAV, removed when the returned guard drops.
468pub fn render_mix(s: &PlaybackSession) -> Result<TempWav, String> {
469 if let Some(why) = offline_refusal(s) {
470 return Err(why);
471 }
472 let nanos = SystemTime::now()
473 .duration_since(UNIX_EPOCH)
474 .map_or(0, |d| d.as_nanos());
475 let wav =
476 TempWav(std::env::temp_dir().join(format!("edith-mix-{}-{nanos}.wav", std::process::id())));
477 let settings = ExportSettings {
478 format: Format::Wav,
479 ..ExportSettings::default()
480 };
481 let handle = s.export_to_with(&wav.0, &settings);
482 let outcome = loop {
483 if let Some(r) = handle.result() {
484 break r;
485 }
486 std::thread::sleep(Duration::from_millis(20));
487 };
488 outcome.map_err(|e| format!("rendering the mix: {e}"))?;
489 Ok(wav)
490}
491
492/// The integrated target online video aims for (YouTube, Spotify), in LUFS.
493pub const TARGET_ONLINE_LUFS: f64 = -14.0;
494/// The true-peak ceiling a normalize holds the sound to, in dBTP.
495pub const TARGET_TRUE_PEAK: f64 = -1.0;
496/// The targets a picker offers: online video, streaming speech and broadcast (EBU R128).
497pub const PRESETS: [(&str, f64); 3] = [("Online video", -14.0), ("Podcast", -16.0), ("Broadcast", -23.0)];
498/// How close the level has to land, in LU, before a normalize stops refining.
499const TOLERANCE_LU: f64 = 0.1;
500/// How far a true peak may sit over the ceiling, in dB, before the gain is cut back.
501const PEAK_TOLERANCE_DB: f64 = 0.05;
502/// Measure-and-correct rounds after the first gain.
503const PASSES: usize = 8;
504
505/// What a normalize works on.
506#[derive(Clone, Debug, PartialEq, Eq)]
507pub enum Scope {
508 /// Every unmuted audio lane with clips, moved by one common gain so the mix lands on target.
509 Mix,
510 /// Each lane on its own: every one set so that it alone measures the target.
511 Each(Vec<Lane>),
512}
513
514/// One lane's change.
515#[derive(Clone, Debug)]
516pub struct LaneChange {
517 pub lane: Lane,
518 /// The lane alone, before and after (lane gain included).
519 pub before: Loudness,
520 pub after: Loudness,
521 /// The gain the lane moved by in total, lane gain and clip gain, in dB.
522 pub moved_db: f64,
523}
524
525/// What a normalize did, measured.
526#[derive(Clone, Debug)]
527pub struct Report {
528 pub lufs: f64,
529 pub true_peak: f64,
530 /// The mix (for `Scope::Mix`) or the lane (for `Each` with one lane) before and after; for
531 /// `Each` with several lanes, the mix is not measured and these are the first lane's.
532 pub before: Loudness,
533 pub after: Loudness,
534 pub lanes: Vec<LaneChange>,
535 /// Whether the level landed on the target (within 0.1 LU).
536 pub reached: bool,
537 /// Whether the true-peak ceiling, rather than the target, set the final level.
538 pub peak_held: bool,
539}
540
541/// What `normalize` measures at each step.
542enum Probe {
543 Mix,
544 Lane(Lane),
545}
546
547fn measure_probe(s: &PlaybackSession, probe: &Probe, fps: f64, end: u32) -> Result<Loudness, String> {
548 match probe {
549 Probe::Mix => measure_mix(s, 0, end, fps, end),
550 Probe::Lane(lane) => {
551 let g = f64::from(s.lane_gain_db(*lane));
552 let l = measure_lane(s, *lane, 0, lane_end(s, *lane), fps)?
553 .ok_or_else(|| format!("{} has no sound to measure", lane.label()))?;
554 Ok(shifted(l, g))
555 }
556 }
557}
558
559/// The frame a lane's last clip ends at.
560pub fn lane_end(s: &PlaybackSession, lane: Lane) -> u32 {
561 s.lane_clips(lane).iter().map(Clip::end).max().unwrap_or(0)
562}
563
564/// The audio lanes a mix normalize moves: unmuted, with clips.
565pub fn mix_lanes(s: &PlaybackSession) -> Vec<Lane> {
566 s.lanes()
567 .into_iter()
568 .filter(|l| l.kind == LaneKind::Audio && !s.lane_clips(*l).is_empty() && !s.lane_muted(*l))
569 .collect()
570}
571
572/// Moves `lanes` by one common gain until `probe` measures `lufs` with the peaks under `tp`:
573/// the first gain is predicted from `first`, then measured and corrected. Returns the final
574/// measurement and whether the ceiling cut the level short.
575#[allow(clippy::too_many_arguments)]
576fn settle(
577 s: &mut PlaybackSession,
578 lanes: &[Lane],
579 first: &Loudness,
580 lufs: f64,
581 tp: f64,
582 mix: bool,
583 fps: f64,
584 end: u32,
585) -> Result<(Loudness, bool, bool), String> {
586 let plans: Vec<Plan> = lanes.iter().map(|&l| plan_of(s, l)).collect();
587 let mut gain = loudness::gain_to_target(first, lufs, tp);
588 if gain.abs() < 0.01 {
589 let over = if first.true_peak_dbtp.is_finite() { first.true_peak_dbtp - tp } else { 0.0 };
590 return Ok((*first, over >= -PEAK_TOLERANCE_DB && (lufs - first.integrated_lufs).abs() > TOLERANCE_LU, false));
591 }
592 set_plans(s, &plans, gain);
593 let probe_of = |s: &PlaybackSession| -> Result<Loudness, String> {
594 match (mix, lanes.first()) {
595 (false, Some(&l)) => measure_probe(s, &Probe::Lane(l), fps, end),
596 _ => measure_probe(s, &Probe::Mix, fps, end),
597 }
598 };
599 let mut after = probe_of(s)?;
600 let mut cut = false;
601 for _ in 0..PASSES {
602 if !after.integrated_lufs.is_finite() {
603 break;
604 }
605 let miss = lufs - after.integrated_lufs;
606 let over = if after.true_peak_dbtp.is_finite() { after.true_peak_dbtp - tp } else { 0.0 };
607 if miss.abs() <= TOLERANCE_LU && over <= PEAK_TOLERANCE_DB {
608 break;
609 }
610 // Gain moves the level and the peaks about equally: a step up stops at the ceiling.
611 let mut step = miss;
612 if over > PEAK_TOLERANCE_DB {
613 step = step.min(-over);
614 cut = true;
615 } else if step > -over {
616 step = -over;
617 cut = true;
618 }
619 if step.abs() < 0.01 {
620 break;
621 }
622 gain += step;
623 set_plans(s, &plans, gain);
624 after = probe_of(s)?;
625 }
626 Ok((after, cut, true))
627}
628
629/// Loudness-normalizes the timeline to `lufs` (integrated) with the true peak held under `tp`
630/// dBTP. One undo step. Nothing changes when a lane cannot be measured or is locked.
631pub fn normalize(s: &mut PlaybackSession, scope: &Scope, lufs: f64, tp: f64) -> Result<Report, String> {
632 if !(-70.0..=0.0).contains(&lufs) {
633 return Err(format!("lufs {lufs} is out of range; it must be -70 to 0"));
634 }
635 if !(-20.0..=0.0).contains(&tp) {
636 return Err(format!("true_peak {tp} is out of range; it must be -20 to 0"));
637 }
638 let fps = s.meta().frame_rate;
639 let end = (s.timeline_duration() * fps).round() as u32;
640 let lanes = match scope {
641 Scope::Mix => mix_lanes(s),
642 Scope::Each(l) => l.clone(),
643 };
644 if lanes.is_empty() {
645 return Err("the mix has no unmuted audio lane with clips to move".into());
646 }
647 for l in &lanes {
648 if l.kind != LaneKind::Audio {
649 return Err(format!("{} is not an audio lane", l.label()));
650 }
651 if s.lane_clips(*l).is_empty() {
652 return Err(format!("{} has no clips to normalize", l.label()));
653 }
654 if s.lane_locked(*l) {
655 return Err(format!("lane {} is locked: unlock it first", l.label()));
656 }
657 }
658 // Everything is measured before anything changes, so a lane that cannot be read changes nothing.
659 let mut befores = Vec::new();
660 for &l in &lanes {
661 befores.push(measure_probe(s, &Probe::Lane(l), fps, end)?);
662 }
663 let mix_before = match scope {
664 Scope::Mix => Some(measure_probe(s, &Probe::Mix, fps, end)?),
665 Scope::Each(_) => None,
666 };
667 if mix_before.as_ref().is_some_and(|m| !m.integrated_lufs.is_finite()) {
668 return Err("the mix is silent: there is no loudness to normalize".into());
669 }
670 let start_plans: Vec<Plan> = lanes.iter().map(|&l| plan_of(s, l)).collect();
671 let pushed = s.history_pushes();
672 s.begin_batch();
673 let run = (|| -> Result<(Vec<Loudness>, Option<Loudness>, bool, bool), String> {
674 match scope {
675 Scope::Mix => {
676 let before = mix_before.as_ref().expect("a mix is measured");
677 let (after, cut, moved) = settle(s, &lanes, before, lufs, tp, true, fps, end)?;
678 let afters = if !moved {
679 befores.clone()
680 } else {
681 lanes.iter().map(|&l| measure_probe(s, &Probe::Lane(l), fps, end)).collect::<Result<Vec<_>, _>>()?
682 };
683 let reached = (lufs - after.integrated_lufs).abs() <= TOLERANCE_LU + 1e-6;
684 Ok((afters, Some(after), reached, cut))
685 }
686 Scope::Each(_) => {
687 let mut afters = Vec::new();
688 let (mut reached, mut held) = (true, false);
689 for (i, &l) in lanes.iter().enumerate() {
690 if !befores[i].integrated_lufs.is_finite() {
691 afters.push(befores[i]);
692 continue;
693 }
694 let (after, cut, _) = settle(s, &[l], &befores[i], lufs, tp, false, fps, end)?;
695 reached &= (lufs - after.integrated_lufs).abs() <= TOLERANCE_LU + 1e-6;
696 held |= cut;
697 afters.push(after);
698 }
699 Ok((afters, None, reached, held))
700 }
701 }
702 })();
703 s.end_batch();
704 let (afters, mix_after, reached, peak_held) = match run {
705 Ok(v) => v,
706 Err(e) => {
707 // Take the half-done change back; the undo history keeps no trace of a failure.
708 if s.history_pushes() > pushed {
709 s.undo();
710 s.clear_redo();
711 }
712 return Err(e);
713 }
714 };
715 let changes: Vec<LaneChange> = lanes
716 .iter()
717 .zip(start_plans.iter())
718 .zip(befores.iter().zip(afters.iter()))
719 .map(|((&lane, plan), (b, a))| LaneChange {
720 lane,
721 before: *b,
722 after: *a,
723 moved_db: total_moved(s, plan),
724 })
725 .collect();
726 let (before, after) = match (mix_before, mix_after) {
727 (Some(b), Some(a)) => (b, a),
728 _ => (changes[0].before, changes[0].after),
729 };
730 Ok(Report { lufs, true_peak: tp, before, after, lanes: changes, reached, peak_held })
731}
732
733/// The gain a plan's lane really moved by in total: its lane gain, and the mean clip gain on top.
734fn total_moved(s: &PlaybackSession, p: &Plan) -> f64 {
735 let lane = f64::from(s.lane_gain_db(p.lane)) - p.old;
736 if p.clips.is_empty() {
737 return lane;
738 }
739 let clip: f64 = p
740 .clips
741 .iter()
742 .map(|&(i, old)| f64::from(s.clip_gain_of(p.lane, i).unwrap_or(0.0)) - old)
743 .sum::<f64>()
744 / p.clips.len() as f64;
745 lane + clip
746}