forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBf7fa0feTahinli25 days ago1027 commits

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