| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | use std::path::PathBuf; |
| 11 | use std::sync::mpsc::Receiver; |
| 12 | use std::time::{Duration, SystemTime, UNIX_EPOCH}; |
| 13 | |
| 14 | use crate::duck::Ducker; |
| 15 | use crate::export::{ExportSettings, Format}; |
| 16 | use crate::loudness::{self, Loudness, Meter}; |
| 17 | use crate::project::{Lane, LaneKind, MAX_CLIP_GAIN_DB, MAX_GAIN_DB, MIN_GAIN_DB}; |
| 18 | use crate::silence::WINDOWS_PER_SEC; |
| 19 | use crate::{AudioChunk, AudioMeta, AudioSession, Clip, PlaybackSession}; |
| 20 | |
| 21 | |
| 22 | |
| 23 | pub 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 | |
| 41 | |
| 42 | pub 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 | |
| 56 | |
| 57 | pub 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 | |
| 72 | |
| 73 | |
| 74 | pub 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 | |
| 89 | |
| 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 | |
| 110 | |
| 111 | |
| 112 | |
| 113 | |
| 114 | pub struct Ducked { |
| 115 | pub rate: u32, |
| 116 | pub channels: usize, |
| 117 | |
| 118 | left: u64, |
| 119 | |
| 120 | at: u64, |
| 121 | |
| 122 | keys: Vec<KeyDuck>, |
| 123 | |
| 124 | |
| 125 | lane: Option<Feed>, |
| 126 | } |
| 127 | |
| 128 | |
| 129 | struct KeyDuck { |
| 130 | key: Feed, |
| 131 | |
| 132 | key_gain: f32, |
| 133 | ducker: Ducker, |
| 134 | } |
| 135 | |
| 136 | |
| 137 | struct Feed { |
| 138 | rx: Receiver<AudioChunk>, |
| 139 | pending: Vec<f32>, |
| 140 | live: bool, |
| 141 | } |
| 142 | |
| 143 | impl Feed { |
| 144 | |
| 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 | |
| 155 | impl Ducked { |
| 156 | |
| 157 | |
| 158 | |
| 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 | |
| 213 | |
| 214 | |
| 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 | |
| 262 | |
| 263 | |
| 264 | type MeasureKey = (u64, Option<Lane>, u32, u32, u64); |
| 265 | |
| 266 | static MEASURED: std::sync::Mutex<Vec<(MeasureKey, Option<Loudness>)>> = std::sync::Mutex::new(Vec::new()); |
| 267 | |
| 268 | fn 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 | |
| 285 | pub 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 | |
| 295 | fn 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 | |
| 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 | |
| 338 | |
| 339 | |
| 340 | pub 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 | |
| 348 | |
| 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 | |
| 372 | pub struct TempWav(pub PathBuf); |
| 373 | |
| 374 | impl Drop for TempWav { |
| 375 | fn drop(&mut self) { |
| 376 | let _ = std::fs::remove_file(&self.0); |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | |
| 381 | |
| 382 | pub 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 | |
| 393 | fn 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 | |
| 414 | pub fn clamp_gain(db: f64) -> f64 { |
| 415 | db.clamp(f64::from(MIN_GAIN_DB), f64::from(MAX_GAIN_DB)) |
| 416 | } |
| 417 | |
| 418 | |
| 419 | |
| 420 | pub struct Plan { |
| 421 | pub lane: Lane, |
| 422 | pub old: f64, |
| 423 | pub clips: Vec<(usize, f64)>, |
| 424 | } |
| 425 | |
| 426 | |
| 427 | pub 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 | |
| 435 | |
| 436 | |
| 437 | |
| 438 | |
| 439 | pub 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 | |
| 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 | |
| 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 | |
| 467 | |
| 468 | pub 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 | |
| 493 | pub const TARGET_ONLINE_LUFS: f64 = -14.0; |
| 494 | |
| 495 | pub const TARGET_TRUE_PEAK: f64 = -1.0; |
| 496 | |
| 497 | pub const PRESETS: [(&str, f64); 3] = [("Online video", -14.0), ("Podcast", -16.0), ("Broadcast", -23.0)]; |
| 498 | |
| 499 | const TOLERANCE_LU: f64 = 0.1; |
| 500 | |
| 501 | const PEAK_TOLERANCE_DB: f64 = 0.05; |
| 502 | |
| 503 | const PASSES: usize = 8; |
| 504 | |
| 505 | |
| 506 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 507 | pub enum Scope { |
| 508 | |
| 509 | Mix, |
| 510 | |
| 511 | Each(Vec<Lane>), |
| 512 | } |
| 513 | |
| 514 | |
| 515 | #[derive(Clone, Debug)] |
| 516 | pub struct LaneChange { |
| 517 | pub lane: Lane, |
| 518 | |
| 519 | pub before: Loudness, |
| 520 | pub after: Loudness, |
| 521 | |
| 522 | pub moved_db: f64, |
| 523 | } |
| 524 | |
| 525 | |
| 526 | #[derive(Clone, Debug)] |
| 527 | pub struct Report { |
| 528 | pub lufs: f64, |
| 529 | pub true_peak: f64, |
| 530 | |
| 531 | |
| 532 | pub before: Loudness, |
| 533 | pub after: Loudness, |
| 534 | pub lanes: Vec<LaneChange>, |
| 535 | |
| 536 | pub reached: bool, |
| 537 | |
| 538 | pub peak_held: bool, |
| 539 | } |
| 540 | |
| 541 | |
| 542 | enum Probe { |
| 543 | Mix, |
| 544 | Lane(Lane), |
| 545 | } |
| 546 | |
| 547 | fn 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 | |
| 560 | pub fn lane_end(s: &PlaybackSession, lane: Lane) -> u32 { |
| 561 | s.lane_clips(lane).iter().map(Clip::end).max().unwrap_or(0) |
| 562 | } |
| 563 | |
| 564 | |
| 565 | pub 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 | |
| 573 | |
| 574 | |
| 575 | #[allow(clippy::too_many_arguments)] |
| 576 | fn 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 | |
| 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 | |
| 630 | |
| 631 | pub 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 | |
| 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 | |
| 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 | |
| 734 | fn 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 | } |