Repository Public
1//! ORIX Sonata2//! File: crates/sonata-render/src/render.rs3//! Description: Offline rendering through the real-time Processor: range, tails, stems,4//! progress, cancellation; level measurement and explicit normalisation.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use crate::file::AudioData;10use sonata_dsp::analysis::meters::{integrated_lufs, rms, sample_peak, to_db, true_peak_dbtp, LUFS_FLOOR};11use sonata_ir::{seconds_to_samples, DspGraph, Program, Strip};12use sonata_runtime::{engine, AssetProvider, EngineConfig, Factory, Limits, PreparedProgram, ProgramInfo, RegistryFactory};13use std::sync::atomic::{AtomicBool, Ordering};1415/// How the end of the audio is found.16#[derive(Clone, Copy, Debug, PartialEq)]17pub struct Tail {18 /// Longest tail rendered after the musical end, seconds.19 pub max_sec: f64,20 /// The tail ends once the output stayed below this level (dBFS, sample peak) ...21 pub silence_db: f64,22 /// ... for this long, seconds. The silent hold itself is trimmed from the result.23 pub hold_sec: f64,24}2526impl Default for Tail {27 fn default() -> Self {28 Tail { max_sec: 30.0, silence_db: -90.0, hold_sec: 0.25 }29 }30}3132#[derive(Clone, Debug, PartialEq)]33pub struct RenderOptions {34 /// Seconds `[start, end)` of the timeline to render; `None` renders the whole composition.35 /// With a range, notes that began before `start` are not sounded and notes still held at36 /// `end` are released there.37 pub range: Option<(f64, f64)>,38 pub tail: Tail,39 /// Also capture one stem per strip feeding the master sum.40 pub stems: bool,41 pub limits: Limits,42 /// Refuse to render more than this many seconds (content plus tail).43 pub max_duration_sec: f64,44}4546impl Default for RenderOptions {47 fn default() -> Self {48 RenderOptions { range: None, tail: Tail::default(), stems: false, limits: Limits::default(), max_duration_sec: 6.0 * 3600.0 }49 }50}5152#[derive(Clone, Debug, PartialEq)]53pub struct Stem {54 pub strip: Strip,55 pub name: String,56 /// Same length and alignment as the master audio.57 pub audio: AudioData,58}5960#[derive(Clone, Debug, PartialEq)]61pub struct RenderStats {62 pub frames: u64,63 /// Frames of musical content (before the tail).64 pub content_frames: u64,65 pub tail_frames: u64,66 /// True when the tail was cut by `Tail::max_sec` before reaching silence.67 pub tail_truncated: bool,68 /// Graph latency removed from the start, samples.69 pub latency_trimmed: u32,70 pub elapsed_sec: f64,71 /// Seconds of audio per second of computation.72 pub realtime_factor: f64,73 pub peak_voices: u32,74 /// Non-finite samples the engine replaced by silence (0 for a healthy render).75 pub scrubbed_samples: u64,76 pub program: ProgramInfo,77}7879#[derive(Clone, Debug, PartialEq)]80pub struct RenderOutput {81 pub audio: AudioData,82 pub stems: Vec<Stem>,83 pub stats: RenderStats,84}8586#[derive(Clone, Debug, PartialEq)]87pub enum RenderError {88 /// The program or graph could not be prepared (message for the user).89 Prepare(String),90 Cancelled,91 /// The requested duration exceeds `RenderOptions::max_duration_sec`.92 TooLong(f64),93 InvalidRange,94}9596impl std::fmt::Display for RenderError {97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {98 match self {99 RenderError::Prepare(m) => write!(f, "{m}"),100 RenderError::Cancelled => write!(f, "render cancelled"),101 RenderError::TooLong(s) => write!(f, "render of {s:.0} s exceeds the configured maximum duration"),102 RenderError::InvalidRange => write!(f, "invalid render range"),103 }104 }105}106107impl std::error::Error for RenderError {}108109/// Renders a program offline with the registry instruments and effects.110///111/// `graph` must have been built for the sample rate to render at (`graph.sample_rate`).112/// `progress` receives a fraction in [0, 1] about every 8192 frames. Setting `cancel` stops the113/// render at the next chunk and returns [`RenderError::Cancelled`].114///115/// The audio is produced by the same `Processor` code as live playback, chunk for chunk, so a116/// render equals what the device would have received (the device path additionally clamps to117/// [-1, 1]; the render does not, so float exports keep overs and integer exports report clipping).118pub fn render(119 program: &Program,120 graph: &DspGraph,121 assets: &dyn AssetProvider,122 opts: &RenderOptions,123 progress: &mut dyn FnMut(f64),124 cancel: &AtomicBool,125) -> Result<RenderOutput, RenderError> {126 render_with(program, graph, assets, opts, progress, cancel, &RegistryFactory)127}128129/// [`render`] with a custom component factory (tests).130pub fn render_with(131 program: &Program,132 graph: &DspGraph,133 assets: &dyn AssetProvider,134 opts: &RenderOptions,135 progress: &mut dyn FnMut(f64),136 cancel: &AtomicBool,137 factory: &dyn Factory,138) -> Result<RenderOutput, RenderError> {139 let started = std::time::Instant::now();140 let sr = graph.sample_rate;141 let limits = Limits { capture_stems: opts.stems, ..opts.limits };142 let prepared = PreparedProgram::prepare_with(program, graph, sr, 4096, assets, &limits, factory).map_err(RenderError::Prepare)?;143 let info = prepared.info().clone();144 let latency = prepared.total_latency() as u64;145 let stem_meta: Vec<(Strip, u32)> = prepared.stems().collect();146147 let (start, end) = match opts.range {148 Some((a, b)) => {149 if !(a.is_finite() && b.is_finite() && a >= 0.0 && b > a) {150 return Err(RenderError::InvalidRange);151 }152 (seconds_to_samples(a, sr), seconds_to_samples(b, sr))153 }154 None => (0, prepared.end_sample()),155 };156 let content = end.saturating_sub(start);157 let max_tail = seconds_to_samples(opts.tail.max_sec.max(0.0), sr);158 let total_cap = content + max_tail;159 if total_cap as f64 / sr as f64 > opts.max_duration_sec {160 return Err(RenderError::TooLong(total_cap as f64 / sr as f64));161 }162 let hold = seconds_to_samples(opts.tail.hold_sec.max(0.0), sr).max(1);163 let threshold = 10f32.powf(opts.tail.silence_db as f32 / 20.0);164165 let (ctl, mut proc_) = engine(EngineConfig::offline(sr));166 ctl.load(prepared).map_err(|_| RenderError::Prepare("engine refused the program".into()))?;167 ctl.seek_samples(start);168 ctl.play();169170 let mut left: Vec<f32> = Vec::with_capacity((content + hold) as usize);171 let mut right: Vec<f32> = Vec::with_capacity((content + hold) as usize);172 let mut stems: Vec<(Vec<f32>, Vec<f32>)> = stem_meta.iter().map(|_| (Vec::with_capacity(content as usize), Vec::with_capacity(content as usize))).collect();173 let mut produced = 0u64; // frames taken from the engine, latency included174 let mut quiet = 0u64;175 let mut released = opts.range.is_none();176 let mut peak_voices = 0u32;177 let mut next_report = 0u64;178 let mut truncated = false;179 loop {180 if cancel.load(Ordering::Relaxed) {181 return Err(RenderError::Cancelled);182 }183 let out_frames = produced.saturating_sub(latency);184 if !released && proc_.position() >= end {185 // End of a range: release what is held, let tails ring.186 ctl.pause();187 released = true;188 }189 if out_frames >= content {190 if quiet >= hold {191 break;192 }193 if out_frames >= total_cap {194 truncated = quiet < hold && max_tail > 0;195 break;196 }197 }198 let n = {199 let (l, r) = proc_.process_chunk();200 let n = l.len() as u64;201 let skip = latency.saturating_sub(produced).min(n) as usize;202 left.extend_from_slice(&l[skip..]);203 right.extend_from_slice(&r[skip..]);204 // Trailing quiet frames, counted per sample so the trim is exact.205 let taken = n - skip as u64;206 match (skip..n as usize).rev().find(|&i| l[i].abs() > threshold || r[i].abs() > threshold) {207 Some(last) => quiet = n - 1 - last as u64,208 None => quiet += taken,209 }210 n211 };212 for (i, (sl, sr_)) in stems.iter_mut().enumerate() {213 if let Some((l, r)) = proc_.stem_chunk(i) {214 let skip = (stem_meta[i].1 as u64).saturating_sub(produced).min(n) as usize;215 sl.extend_from_slice(&l[skip..]);216 sr_.extend_from_slice(&r[skip..]);217 }218 }219 produced += n;220 peak_voices = peak_voices.max(ctl.shared().active_voices());221 if produced >= next_report {222 progress((produced.saturating_sub(latency) as f64 / (content.max(1) as f64 * 1.02 + hold as f64)).min(0.999));223 next_report = produced + 8192;224 }225 }226 // Trim: never below the content length; drop the silent hold that ended the tail.227 let mut frames = left.len() as u64;228 if !truncated && frames > content {229 frames = frames.saturating_sub(quiet).max(content);230 }231 frames = frames.min(total_cap.max(content));232 left.truncate(frames as usize);233 right.truncate(frames as usize);234 left.resize(frames as usize, 0.0);235 right.resize(frames as usize, 0.0);236 let name_of = |s: Strip| info.strips.iter().find(|i| i.strip == s).map(|i| i.name.clone()).unwrap_or_default();237 let stems = stems238 .into_iter()239 .zip(&stem_meta)240 .map(|((mut l, mut r), (strip, _))| {241 l.resize(frames as usize, 0.0);242 r.resize(frames as usize, 0.0);243 Stem { strip: *strip, name: name_of(*strip), audio: AudioData::stereo(sr, l, r) }244 })245 .collect();246 progress(1.0);247 let elapsed = started.elapsed().as_secs_f64();248 let stats = RenderStats {249 frames,250 content_frames: content,251 tail_frames: frames.saturating_sub(content),252 tail_truncated: truncated,253 latency_trimmed: latency as u32,254 elapsed_sec: elapsed,255 realtime_factor: if elapsed > 0.0 { frames as f64 / sr as f64 / elapsed } else { 0.0 },256 peak_voices,257 scrubbed_samples: ctl.shared().scrubbed_samples(),258 program: info,259 };260 Ok(RenderOutput { audio: AudioData::stereo(sr, left, right), stems, stats })261}262263/// Levels of a rendered buffer.264#[derive(Clone, Copy, Debug, PartialEq)]265pub struct Levels {266 /// Largest sample magnitude over all channels, dBFS.267 pub sample_peak_db: f32,268 /// True peak (4x oversampling, BS.1770-4), dBTP.269 pub true_peak_dbtp: f32,270 /// RMS over all channels, dBFS.271 pub rms_db: f32,272 /// Integrated loudness (BS.1770-4, first two channels), LUFS; -200 when nothing passes the gate.273 pub integrated_lufs: f64,274}275276pub fn measure_levels(audio: &AudioData) -> Levels {277 let mut pk = 0.0f32;278 let mut tp = -200.0f32;279 let mut sq = 0.0f64;280 let mut n = 0usize;281 for c in &audio.channels {282 pk = pk.max(sample_peak(c));283 tp = tp.max(true_peak_dbtp(c, audio.sample_rate as f32));284 sq += (rms(c) as f64).powi(2) * c.len() as f64;285 n += c.len();286 }287 let l = audio.channels.first().map(|c| c.as_slice()).unwrap_or(&[]);288 let r = audio.channels.get(1).map(|c| c.as_slice()).unwrap_or(l);289 Levels {290 sample_peak_db: to_db(pk),291 true_peak_dbtp: tp,292 rms_db: to_db(if n > 0 { (sq / n as f64).sqrt() as f32 } else { 0.0 }),293 integrated_lufs: integrated_lufs(l, r, audio.sample_rate),294 }295}296297/// Explicit normalisation. Never applied by `render` or by the file writers.298#[derive(Clone, Copy, Debug, PartialEq)]299pub enum Normalize {300 /// Scale so the sample peak reaches this level, dBFS.301 SamplePeak(f64),302 /// Scale so the true peak reaches this level, dBTP.303 TruePeak(f64),304 /// Scale to this integrated loudness, LUFS. The gain is reduced if needed so the true peak305 /// stays at or below `max_true_peak_dbtp`.306 Loudness { target_lufs: f64, max_true_peak_dbtp: f64 },307}308309/// Applies one gain to every channel and returns it in dB. Errors on silence (nothing to scale).310pub fn normalize(audio: &mut AudioData, mode: Normalize) -> Result<f64, String> {311 let lv = measure_levels(audio);312 if lv.sample_peak_db <= -150.0 {313 return Err("audio is silent; nothing to normalise".into());314 }315 let gain_db = match mode {316 Normalize::SamplePeak(t) => t - lv.sample_peak_db as f64,317 Normalize::TruePeak(t) => t - lv.true_peak_dbtp as f64,318 Normalize::Loudness { target_lufs, max_true_peak_dbtp } => {319 if lv.integrated_lufs <= LUFS_FLOOR + 1.0 {320 return Err("audio is too quiet or too short for a loudness measurement".into());321 }322 (target_lufs - lv.integrated_lufs).min(max_true_peak_dbtp - lv.true_peak_dbtp as f64)323 }324 };325 if !gain_db.is_finite() {326 return Err("normalisation gain is not finite".into());327 }328 let g = 10f64.powf(gain_db / 20.0) as f32;329 for c in &mut audio.channels {330 for v in c.iter_mut() {331 *v *= g;332 }333 }334 Ok(gain_db)335}336