SPB Git

Repository Public

plan.rs 58.5 KB 1,408 lines rust

1//! ORIX Sonata2//! File: crates/sonata-runtime/src/plan.rs3//! Description: PreparedProgram — a Program and its DspGraph turned into a preallocated4//! execution plan for one sample rate: instruments, effects, buffers, event lists, automation.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use crate::shared::{meter_slot, Shared, MAX_BUSES, MAX_TRACKS};10use sonata_dsp::effects::limiter_core::LimiterCore;11use sonata_dsp::Effect;12use sonata_instruments::{Instrument, NoteOn};13use sonata_ir::{14    seconds_to_samples, Articulation, AutomationLane, AutomationTarget, Curve, DspGraph, EffectDesc, EffectSpec, EngineDesc, InstrumentSpec, NodeKind,15    ParamValue, Program, SignaturePoint, Strip, TempoMap, TrackKind, Unit,16};17use std::sync::atomic::Ordering::Relaxed;18use std::sync::Arc;1920/// Internal render quantum in frames. The engine renders in chunks of at most this size, cut at21/// multiples of the quantum on the engine clock and at every note or automation boundary, whatever22/// block size the host asks for. This is what makes offline and real-time results identical.23pub const QUANTUM: usize = 64;2425/// Time constant of the fader/pan smoothing for non-automated changes, seconds.26const FADER_SMOOTH_SEC: f32 = 0.005;27/// Window of the strip RMS meters, seconds.28const RMS_WINDOW_SEC: f32 = 0.3;29/// Release time constant of the master safety limiter, seconds.30const LIMITER_RELEASE_SEC: f32 = 0.08;31/// Interval between interpolated pitch-bend updates, frames.32const BEND_STEP: u64 = 256;3334/// Decoded audio of an imported asset.35#[derive(Clone, Debug, PartialEq)]36pub struct AudioAsset {37    pub sample_rate: u32,38    /// One (mono) or two (stereo) channels of equal length.39    pub channels: Vec<Vec<f32>>,40}4142/// Gives the runtime the decoded audio of the assets a program references. Called off the audio43/// thread, during `prepare` only.44pub trait AssetProvider {45    fn load(&self, asset: &str) -> Result<Arc<AudioAsset>, String>;46}4748/// An asset provider for programs without audio clips.49pub struct NoAssets;5051impl AssetProvider for NoAssets {52    fn load(&self, asset: &str) -> Result<Arc<AudioAsset>, String> {53        Err(format!("asset '{asset}' is not available (no asset provider)"))54    }55}5657/// Where instruments and effects come from. The default is the registry of the DSP crates;58/// tests substitute simple deterministic components.59pub trait Factory {60    fn instrument(&self, spec: &InstrumentSpec, tuning_hz: f64, seed: u64) -> Result<Box<dyn Instrument>, String>;61    fn engine_desc(&self, model: &str) -> Option<EngineDesc>;62    fn effect(&self, kind: &str) -> Option<Box<dyn Effect>>;63    fn effect_desc(&self, kind: &str) -> Option<EffectDesc>;64}6566/// The production factory: `sonata_instruments::create_instrument` and `sonata_dsp::create_effect`.67pub struct RegistryFactory;6869impl Factory for RegistryFactory {70    fn instrument(&self, spec: &InstrumentSpec, tuning_hz: f64, seed: u64) -> Result<Box<dyn Instrument>, String> {71        sonata_instruments::create_instrument(spec, tuning_hz, seed)72    }73    fn engine_desc(&self, model: &str) -> Option<EngineDesc> {74        sonata_instruments::engine_registry().into_iter().find(|e| e.model == model)75    }76    fn effect(&self, kind: &str) -> Option<Box<dyn Effect>> {77        sonata_dsp::create_effect(kind)78    }79    fn effect_desc(&self, kind: &str) -> Option<EffectDesc> {80        sonata_dsp::effect_registry().into_iter().find(|e| e.kind == kind)81    }82}8384/// Resource limits applied by `prepare`.85#[derive(Clone, Copy, Debug, PartialEq)]86pub struct Limits {87    /// Voices preallocated per instrument track.88    pub max_voices: usize,89    /// Largest number of scheduled events (note on, note off, bend steps) accepted.90    pub max_events: usize,91    /// Longest accepted audio asset, seconds.92    pub max_asset_seconds: f64,93    /// Keep the inputs of the master sum in dedicated buffers so the renderer can export stems.94    pub capture_stems: bool,95}9697impl Default for Limits {98    fn default() -> Self {99        Limits { max_voices: 64, max_events: 4_000_000, max_asset_seconds: 3600.0, capture_stems: false }100    }101}102103/// A point of the mixer whose audio can be sent to the tap scope ring.104#[derive(Clone, Copy, Debug, PartialEq, Eq)]105pub enum TapPoint {106    /// The final output (same content as the master scope ring).107    Master,108    /// A track after its inserts and fader.109    Track(u32),110    /// A bus after its inserts and fader.111    Bus(u32),112    /// The raw output of a track's instrument, before any insert.113    Instrument(u32),114}115116/// Description of one effect of a strip, for inspectors and name-to-index mapping.117#[derive(Clone, Debug, PartialEq)]118pub struct EffectInfo {119    pub kind: String,120    /// Parameter names in index order (the index is what `set_effect_param` takes).121    pub params: Vec<String>,122    pub latency: u32,123}124125#[derive(Clone, Debug, PartialEq)]126pub struct StripInfo {127    pub strip: Strip,128    pub name: String,129    pub effects: Vec<EffectInfo>,130    pub instrument_model: Option<String>,131    /// Instrument parameter names in index order.132    pub instrument_params: Vec<String>,133}134135/// Facts about a prepared program, computed off the audio thread.136#[derive(Clone, Debug, PartialEq)]137pub struct ProgramInfo {138    pub sample_rate: u32,139    /// Sample at which the musical content ends (tails excluded).140    pub end_sample: u64,141    /// Latency of the whole graph in samples (output is late by this much).142    pub total_latency: u32,143    pub strips: Vec<StripInfo>,144    pub nodes: usize,145    pub buffers: usize,146    pub events: usize,147    pub automation_lanes: usize,148    /// Heap memory owned by the plan itself (buffers, events, delay lines, assets), bytes.149    /// Instrument and effect internals are not included.150    pub estimated_bytes: usize,151}152153#[derive(Clone, Copy)]154enum EvKind {155    Off,156    On { pitch: f32, freq: f32, velocity: f32, articulation: Articulation, until: u64 },157    Bend { semitones: f32 },158}159160#[derive(Clone, Copy)]161struct Ev {162    sample: u64,163    node: u32,164    id: u64,165    kind: EvKind,166}167168#[derive(Clone, Copy)]169enum LaneTarget {170    Gain(usize),171    Pan(usize),172    EffectParam { node: usize, param: usize },173    EffectMix { node: usize },174    InstrumentParam { node: usize, param: usize },175}176177struct Lane {178    target: LaneTarget,179    /// (sample, value, curve of the segment ending at this point)180    pts: Vec<(u64, f32, Curve)>,181    idx: usize,182}183184impl Lane {185    fn seek(&mut self, s: u64) {186        self.idx = self.pts.partition_point(|p| p.0 <= s).saturating_sub(1);187    }188    fn value_at(&mut self, s: u64) -> f32 {189        while self.idx + 1 < self.pts.len() && self.pts[self.idx + 1].0 <= s {190            self.idx += 1;191        }192        let a = self.pts[self.idx];193        if s <= a.0 || self.idx + 1 >= self.pts.len() {194            return a.1;195        }196        let b = self.pts[self.idx + 1];197        let t = ((s - a.0) as f64 / (b.0 - a.0) as f64) as f32;198        match b.2 {199            Curve::Step => a.1,200            Curve::Linear => a.1 + (b.1 - a.1) * t,201            Curve::Exponential => {202                if a.1 * b.1 > 0.0 {203                    a.1 * (b.1 / a.1).powf(t)204                } else {205                    a.1 + (b.1 - a.1) * t206                }207            }208        }209    }210}211212struct StripState {213    strip: Strip,214    is_track: bool,215    has_pan: bool,216    gain_db: f32,217    pan: f32,218    mute: bool,219    solo: bool,220    gain_override: Option<f32>,221    pan_override: Option<f32>,222    mute_override: Option<bool>,223    solo_override: Option<bool>,224    auto_gain: Option<f32>,225    auto_pan: Option<f32>,226    cur_l: f32,227    cur_r: f32,228    primed: bool,229    ms_l: f32,230    ms_r: f32,231    slot: Option<usize>,232}233234impl StripState {235    /// Target (left gain, right gain, silent) from the fader, pan, mute and solo state.236    /// Constant-power pan law, -3.01 dB at centre: gL = cos(theta), gR = sin(theta),237    /// theta = (pan + 1) * pi / 4. The master strip has no pan stage.238    fn target(&self, solo_active: bool) -> (f32, f32, bool) {239        let db = self.gain_override.or(self.auto_gain).unwrap_or(self.gain_db);240        let silent = self.muted() || (self.is_track && solo_active && !self.soloed()) || db <= -144.0;241        let g = if silent { 0.0 } else { db_to_lin(db) };242        if self.has_pan {243            let theta = (self.pan_override.or(self.auto_pan).unwrap_or(self.pan).clamp(-1.0, 1.0) + 1.0) * std::f32::consts::FRAC_PI_4;244            (g * theta.cos(), g * theta.sin(), silent)245        } else {246            (g, g, silent)247        }248    }249    fn muted(&self) -> bool {250        self.mute_override.unwrap_or(self.mute)251    }252    fn soloed(&self) -> bool {253        self.solo_override.unwrap_or(self.solo)254    }255}256257struct ClipExec {258    asset: Arc<AudioAsset>,259    start: u64,260    offset: u64,261    len: u64,262    gain: f32,263    fade_in: u64,264    fade_out: u64,265}266267struct EffectExec {268    fx: Box<dyn Effect>,269    mix: f32,270    mix_target: f32,271    spec_mix: f32,272    bypass: bool,273    latency: usize,274    dry_l: Vec<f32>,275    dry_r: Vec<f32>,276    dry_pos: usize,277}278279enum Exec {280    Instrument { inst: Box<dyn Instrument> },281    Clips { clips: Vec<ClipExec> },282    Effect(Box<EffectExec>),283    Fader { strip: usize },284    Send { gain: f32 },285    Sum,286    Delay { l: Vec<f32>, r: Vec<f32>, pos: usize },287    Limiter(Box<LimiterCore>),288    Output,289}290291struct Node {292    exec: Exec,293    inputs: Vec<u32>,294    out: u32,295}296297type Buf = [Vec<f32>; 2];298299/// A program ready to be played: everything it needs was allocated by [`PreparedProgram::prepare`].300pub struct PreparedProgram {301    sample_rate: u32,302    tuning_hz: f64,303    nodes: Vec<Node>,304    bufs: Vec<Buf>,305    scratch: Buf,306    out_buf: usize,307    events: Vec<Ev>,308    cursor: usize,309    lanes: Vec<Lane>,310    auto_bounds: Vec<u64>,311    auto_cursor: usize,312    strips: Vec<StripState>,313    solo_active: bool,314    /// (track id, instrument node index)315    track_inst: Vec<(u32, usize)>,316    /// (strip, effect index, node index)317    fx_nodes: Vec<(Strip, u32, usize)>,318    /// (strip, fader node index)319    fader_nodes: Vec<(Strip, usize)>,320    stems: Vec<(Strip, u32, usize)>,321    limiter_node: Option<usize>,322    beats: Vec<(u64, bool)>,323    tempo_map: TempoMap,324    signatures: Vec<SignaturePoint>,325    end_sample: u64,326    total_latency: u32,327    tap_node: Option<usize>,328    info: ProgramInfo,329}330331fn db_to_lin(db: f32) -> f32 {332    10f32.powf(db / 20.0)333}334335fn all_finite(l: &[f32], r: &[f32]) -> bool {336    let mut acc = 0.0f32;337    for i in 0..l.len() {338        acc += l[i] * 0.0 + r[i] * 0.0;339    }340    acc == 0.0341}342343fn configure_effect(fx: &mut dyn Effect, desc: &EffectDesc, spec: &EffectSpec) -> Result<(), String> {344    let apply = |fx: &mut dyn Effect, name: &str, value: &ParamValue| -> Result<(), String> {345        let (i, p) = desc.params.iter().enumerate().find(|(_, p)| p.name == name).ok_or(format!("effect '{}' has no parameter '{}'", desc.kind, name))?;346        match (p.unit, value) {347            (Unit::Choice, ParamValue::Text(t)) => {348                let c = p.choices.iter().position(|c| c == t).ok_or(format!("effect '{}': '{}' is not a choice of '{}'", desc.kind, t, name))?;349                fx.set_choice(i, c);350            }351            (Unit::Choice, _) => return Err(format!("effect '{}': parameter '{}' expects a choice", desc.kind, name)),352            (_, ParamValue::Num(v)) => {353                if !v.is_finite() {354                    return Err(format!("effect '{}': parameter '{}' is not finite", desc.kind, name));355                }356                fx.set_param(i, (*v).clamp(p.min, p.max) as f32);357            }358            _ => return Err(format!("effect '{}': parameter '{}' expects a number", desc.kind, name)),359        }360        Ok(())361    };362    if let Some(preset) = &spec.preset {363        let pr = desc.presets.iter().find(|p| &p.name == preset).ok_or(format!("effect '{}' has no preset '{}'", desc.kind, preset))?;364        for (k, v) in &pr.values {365            apply(fx, k, &ParamValue::Num(*v))?;366        }367        for (k, v) in &pr.choices {368            apply(fx, k, &ParamValue::Text(v.clone()))?;369        }370    }371    for (k, v) in &spec.params {372        apply(fx, k, v)?;373    }374    Ok(())375}376377fn beat_grid(program: &Program, sample_rate: u32) -> Vec<(u64, bool)> {378    use sonata_ir::Rational;379    let mut beats = Vec::new();380    if program.signatures.is_empty() {381        return beats;382    }383    let mut pos = Rational::ZERO;384    let mut sig_i = 0;385    let mut bar_start = Rational::ZERO;386    let last = &program.signatures[program.signatures.len() - 1];387    let limit = program.end.checked_add(last.bar_length().checked_mul(Rational::from_int(2)).unwrap_or(Rational::ONE)).unwrap_or(program.end);388    while pos <= limit && beats.len() < 400_000 {389        while sig_i + 1 < program.signatures.len() && program.signatures[sig_i + 1].at <= pos {390            sig_i += 1;391            bar_start = program.signatures[sig_i].at;392        }393        let sig = &program.signatures[sig_i];394        let in_bar = pos.checked_sub(bar_start).and_then(|d| d.checked_div(sig.bar_length()));395        let accent = in_bar.map(|q| q.is_integer()).unwrap_or(false);396        beats.push((seconds_to_samples(program.tempo_map.seconds_at(pos), sample_rate), accent));397        match pos.checked_add(sig.beat_length()) {398            Some(p) => pos = p,399            None => break,400        }401    }402    beats403}404405impl PreparedProgram {406    /// Builds the execution plan with the registry components. See [`PreparedProgram::prepare_with`].407    pub fn prepare(408        program: &Program,409        graph: &DspGraph,410        sample_rate: u32,411        max_block: usize,412        assets: &dyn AssetProvider,413        limits: &Limits,414    ) -> Result<PreparedProgram, String> {415        Self::prepare_with(program, graph, sample_rate, max_block, assets, limits, &RegistryFactory)416    }417418    /// Builds the execution plan. Runs off the audio thread and performs every allocation the419    /// program will ever need. `graph` must have been built for `sample_rate`. `max_block` is the420    /// largest host block (it only sizes nothing here: the engine renders in [`QUANTUM`] chunks;421    /// it is validated to be non-zero).422    pub fn prepare_with(423        program: &Program,424        graph: &DspGraph,425        sample_rate: u32,426        max_block: usize,427        assets: &dyn AssetProvider,428        limits: &Limits,429        factory: &dyn Factory,430    ) -> Result<PreparedProgram, String> {431        if !(8_000..=384_000).contains(&sample_rate) {432            return Err(format!("sample rate {sample_rate} Hz is outside [8000, 384000]"));433        }434        if max_block == 0 {435            return Err("max_block must be at least 1".into());436        }437        if graph.sample_rate != sample_rate {438            return Err(format!("graph was built for {} Hz, engine runs at {} Hz", graph.sample_rate, sample_rate));439        }440        graph.validate()?;441        program.tempo_map.validate()?;442        if program.tracks.len() > MAX_TRACKS || program.buses.len() > MAX_BUSES {443            return Err(format!(444                "program has {} tracks and {} buses; the engine supports {MAX_TRACKS} and {MAX_BUSES}",445                program.tracks.len(),446                program.buses.len()447            ));448        }449        let sr = sample_rate as f32;450451        // Strips: tracks, then buses, then master.452        let mut strips = Vec::with_capacity(program.tracks.len() + program.buses.len() + 1);453        let mk = |strip: Strip, is_track: bool, has_pan: bool, gain_db: f64, pan: f64, mute: bool, solo: bool| StripState {454            strip,455            is_track,456            has_pan,457            gain_db: gain_db as f32,458            pan: pan as f32,459            mute,460            solo,461            gain_override: None,462            pan_override: None,463            mute_override: None,464            solo_override: None,465            auto_gain: None,466            auto_pan: None,467            cur_l: 0.0,468            cur_r: 0.0,469            primed: false,470            ms_l: 0.0,471            ms_r: 0.0,472            slot: if strip == Strip::Master { None } else { meter_slot(strip) },473        };474        for t in &program.tracks {475            strips.push(mk(Strip::Track(t.id), true, true, t.gain_db, t.pan, t.mute, t.solo));476        }477        for b in &program.buses {478            strips.push(mk(Strip::Bus(b.id), false, true, b.gain_db, b.pan, b.mute, false));479        }480        strips.push(mk(Strip::Master, false, false, program.master.gain_db, 0.0, false, false));481        let strip_index = |s: Strip| strips.iter().position(|x| x.strip == s).ok_or(format!("graph references missing strip {s:?}"));482        let track_of = |id: u32| program.tracks.iter().find(|t| t.id == id).ok_or(format!("graph references missing track {id}"));483484        // Buffer plan along the topological order, with reuse.485        let n_nodes = graph.nodes.len();486        let mut consumers = vec![0u32; n_nodes];487        for e in &graph.edges {488            consumers[e.from as usize] += 1;489        }490        let master_sum = graph.nodes.iter().find(|n| matches!(n.kind, NodeKind::Sum { strip: Strip::Master })).map(|n| n.id);491        let mut pinned = vec![false; n_nodes];492        if limits.capture_stems {493            if let Some(ms) = master_sum {494                for i in graph.inputs_of(ms) {495                    pinned[i as usize] = true;496                }497            }498        }499        let mut buf_of = vec![u32::MAX; n_nodes];500        let mut free: Vec<u32> = Vec::new();501        let mut n_bufs = 0u32;502        let mut remaining = consumers.clone();503        for &id in &graph.order {504            let gn = &graph.nodes[id as usize];505            let inputs: Vec<u32> = graph.inputs_of(id).collect();506            if matches!(gn.kind, NodeKind::Output) {507                // The output node aliases its input buffer, which therefore must stay alive.508                buf_of[id as usize] = buf_of[inputs[0] as usize];509                continue;510            }511            let b = free.pop().unwrap_or_else(|| {512                n_bufs += 1;513                n_bufs - 1514            });515            buf_of[id as usize] = b;516            for i in inputs {517                remaining[i as usize] -= 1;518                let feeds_output = graph.edges.iter().any(|e| e.from == i && matches!(graph.nodes[e.to as usize].kind, NodeKind::Output));519                if remaining[i as usize] == 0 && !pinned[i as usize] && !feeds_output {520                    free.push(buf_of[i as usize]);521                }522            }523            if consumers[id as usize] == 0 {524                free.push(b);525            }526        }527528        let mut nodes: Vec<Node> = Vec::with_capacity(n_nodes);529        let mut events: Vec<Ev> = Vec::new();530        let mut track_inst = Vec::new();531        let mut fx_nodes = Vec::new();532        let mut fader_nodes = Vec::new();533        let mut limiter_node = None;534        let mut out_buf = usize::MAX;535        let mut info_fx: Vec<(Strip, EffectInfo)> = Vec::new();536        let mut bytes = 0usize;537        let mut engine_descs: Vec<(usize, EngineDesc)> = Vec::new();538539        for &id in &graph.order {540            let gn = &graph.nodes[id as usize];541            let mut inputs: Vec<u32> = graph.inputs_of(id).map(|i| buf_of[i as usize]).collect();542            // Sum in ascending node id so the order of additions is deterministic.543            let mut in_ids: Vec<u32> = graph.inputs_of(id).collect();544            in_ids.sort_unstable();545            if matches!(gn.kind, NodeKind::Sum { .. }) {546                inputs = in_ids.iter().map(|i| buf_of[*i as usize]).collect();547            }548            let node_index = nodes.len();549            let exec = match &gn.kind {550                NodeKind::Instrument { track } => {551                    let t = track_of(*track)?;552                    if t.kind != TrackKind::Instrument {553                        return Err(format!("track '{}' is not an instrument track", t.name));554                    }555                    let spec = t.instrument.as_ref().ok_or(format!("track '{}' has no instrument", t.name))?;556                    let seed = program.seed ^ (0x9E37_79B9_7F4A_7C15u64.wrapping_mul(t.id as u64 + 1));557                    let mut inst = factory.instrument(spec, program.tuning_hz, seed).map_err(|e| format!("track '{}': {e}", t.name))?;558                    inst.prepare(sr, QUANTUM, limits.max_voices.max(1));559                    let mut last_on: u64 = 0;560                    for n in &t.notes {561                        if !(n.pitch.is_finite() && n.start_sec.is_finite() && n.end_sec.is_finite()) {562                            return Err(format!("track '{}' contains a note with a non-finite value", t.name));563                        }564                        let on = seconds_to_samples(n.start_sec, sample_rate);565                        let off = seconds_to_samples(n.end_sec, sample_rate).max(on + 1);566                        last_on = last_on.max(off);567                        let kind = EvKind::On {568                            pitch: n.pitch as f32,569                            freq: program.pitch_to_hz(n.pitch) as f32,570                            velocity: n.velocity.clamp(0.0, 1.0),571                            articulation: n.articulation,572                            until: off,573                        };574                        events.push(Ev { sample: on, node: node_index as u32, id: n.id, kind });575                        events.push(Ev { sample: off, node: node_index as u32, id: n.id, kind: EvKind::Off });576                        // Pitch curve: linear interpolation between bend points, updated every BEND_STEP frames.577                        for w in 0..n.bend.len() {578                            let p = n.bend[w];579                            let s0 = seconds_to_samples(n.start_sec + p.offset_sec.max(0.0), sample_rate).clamp(on, off);580                            events.push(Ev { sample: s0, node: node_index as u32, id: n.id, kind: EvKind::Bend { semitones: p.semitones as f32 } });581                            if let Some(q) = n.bend.get(w + 1) {582                                let s1 = seconds_to_samples(n.start_sec + q.offset_sec.max(0.0), sample_rate).clamp(on, off);583                                let mut s = s0 + BEND_STEP;584                                while s < s1 {585                                    let t = (s - s0) as f64 / (s1 - s0) as f64;586                                    events.push(Ev {587                                        sample: s,588                                        node: node_index as u32,589                                        id: n.id,590                                        kind: EvKind::Bend { semitones: (p.semitones + (q.semitones - p.semitones) * t) as f32 },591                                    });592                                    s += BEND_STEP;593                                }594                            }595                        }596                        if events.len() > limits.max_events {597                            return Err(format!("program schedules more than {} events", limits.max_events));598                        }599                    }600                    track_inst.push((t.id, node_index));601                    if let Some(d) = factory.engine_desc(&spec.model) {602                        engine_descs.push((node_index, d));603                    }604                    Exec::Instrument { inst }605                }606                NodeKind::AudioClips { track } => {607                    let t = track_of(*track)?;608                    let mut clips = Vec::with_capacity(t.clips.len());609                    for c in &t.clips {610                        let raw = assets.load(&c.asset).map_err(|e| format!("track '{}': {e}", t.name))?;611                        if raw.channels.is_empty() || raw.channels.len() > 2 || raw.channels.iter().any(|ch| ch.len() != raw.channels[0].len()) {612                            return Err(format!("asset '{}' must have one or two channels of equal length", c.asset));613                        }614                        if raw.sample_rate == 0 || raw.channels[0].len() as f64 / raw.sample_rate as f64 > limits.max_asset_seconds {615                            return Err(format!("asset '{}' is longer than {} s or has no sample rate", c.asset, limits.max_asset_seconds));616                        }617                        let asset = if raw.sample_rate == sample_rate {618                            raw619                        } else {620                            let rs = sonata_dsp::analysis::resample::Resampler::new(raw.sample_rate, sample_rate);621                            Arc::new(AudioAsset { sample_rate, channels: raw.channels.iter().map(|ch| rs.process(ch)).collect() })622                        };623                        let frames = asset.channels[0].len() as u64;624                        bytes += asset.channels.len() * frames as usize * 4;625                        let offset = seconds_to_samples(c.offset_sec, sample_rate).min(frames);626                        let avail = frames - offset;627                        let len = c.length_sec.map(|l| seconds_to_samples(l, sample_rate).min(avail)).unwrap_or(avail);628                        clips.push(ClipExec {629                            asset,630                            start: seconds_to_samples(c.start_sec, sample_rate),631                            offset,632                            len,633                            gain: db_to_lin(c.gain_db as f32),634                            fade_in: seconds_to_samples(c.fade_in_sec, sample_rate).min(len),635                            fade_out: seconds_to_samples(c.fade_out_sec, sample_rate).min(len),636                        });637                    }638                    Exec::Clips { clips }639                }640                NodeKind::Effect { strip, index, spec } => {641                    let desc = factory.effect_desc(&spec.kind).ok_or(format!("unknown effect '{}'", spec.kind))?;642                    let mut fx = factory.effect(&spec.kind).ok_or(format!("effect '{}' is not implemented", spec.kind))?;643                    fx.prepare(sr, QUANTUM);644                    configure_effect(fx.as_mut(), &desc, spec)?;645                    fx.reset();646                    let latency = fx.latency();647                    if latency != gn.latency {648                        return Err(format!("effect '{}' reports {} samples of latency but the graph was compensated for {}", spec.kind, latency, gn.latency));649                    }650                    if !(0.0..=1.0).contains(&spec.mix) {651                        return Err(format!("effect '{}' mix {} is outside [0, 1]", spec.kind, spec.mix));652                    }653                    fx_nodes.push((*strip, *index, node_index));654                    info_fx.push((*strip, EffectInfo { kind: spec.kind.clone(), params: desc.params.iter().map(|p| p.name.clone()).collect(), latency }));655                    bytes += latency as usize * 8;656                    let m = if spec.bypass { 0.0 } else { spec.mix as f32 };657                    Exec::Effect(Box::new(EffectExec {658                        fx,659                        mix: m,660                        mix_target: m,661                        spec_mix: spec.mix as f32,662                        bypass: spec.bypass,663                        latency: latency as usize,664                        dry_l: vec![0.0; latency as usize],665                        dry_r: vec![0.0; latency as usize],666                        dry_pos: 0,667                    }))668                }669                NodeKind::Fader { strip } => {670                    fader_nodes.push((*strip, node_index));671                    Exec::Fader { strip: strip_index(*strip)? }672                }673                NodeKind::Send { gain_db, .. } => Exec::Send { gain: db_to_lin(*gain_db as f32) },674                NodeKind::Sum { .. } => Exec::Sum,675                NodeKind::LatencyDelay { samples } => {676                    bytes += *samples as usize * 8;677                    Exec::Delay { l: vec![0.0; *samples as usize], r: vec![0.0; *samples as usize], pos: 0 }678                }679                NodeKind::Limiter { ceiling_db } => {680                    limiter_node = Some(node_index);681                    bytes += gn.latency as usize * 20;682                    Exec::Limiter(Box::new(LimiterCore::new(sr, gn.latency as usize, LIMITER_RELEASE_SEC, *ceiling_db as f32)))683                }684                NodeKind::Output => {685                    out_buf = buf_of[id as usize] as usize;686                    Exec::Output687                }688            };689            if gn.channels_out != 2 || (gn.channels_in != 2 && gn.channels_in != 0) {690                return Err("the engine runs stereo graphs only".into());691            }692            nodes.push(Node { exec, inputs, out: buf_of[id as usize] });693        }694        if out_buf == usize::MAX {695            return Err("graph has no output".into());696        }697698        // Events: note-offs before note-ons at the same sample, then by id (deterministic).699        events.sort_by(|a, b| {700            let rank = |k: &EvKind| match k {701                EvKind::Off => 0,702                EvKind::On { .. } => 1,703                EvKind::Bend { .. } => 2,704            };705            a.sample.cmp(&b.sample).then(rank(&a.kind).cmp(&rank(&b.kind))).then(a.id.cmp(&b.id)).then(a.node.cmp(&b.node))706        });707708        // Automation lanes.709        let mut lanes = Vec::new();710        let mut auto_bounds = Vec::new();711        let mut add_lanes = |strip: Strip, src: &[AutomationLane], model: Option<&str>| -> Result<(), String> {712            let si = strip_index(strip)?;713            for lane in src {714                if lane.points.is_empty() {715                    continue;716                }717                let target = match &lane.target {718                    AutomationTarget::Gain => LaneTarget::Gain(si),719                    AutomationTarget::Pan => LaneTarget::Pan(si),720                    AutomationTarget::Effect { index, param } => {721                        let node = fx_nodes722                            .iter()723                            .find(|(s, i, _)| *s == strip && i == index)724                            .map(|x| x.2)725                            .ok_or(format!("automation targets missing effect {index} of {strip:?}"))?;726                        if param == "mix" {727                            LaneTarget::EffectMix { node }728                        } else {729                            let fi =730                                info_fx.iter().filter(|(s, _)| *s == strip).nth(*index as usize).map(|x| &x.1).ok_or("automation targets a missing effect")?;731                            let p = fi.params.iter().position(|p| p == param).ok_or(format!("effect '{}' has no parameter '{}'", fi.kind, param))?;732                            LaneTarget::EffectParam { node, param: p }733                        }734                    }735                    AutomationTarget::Instrument { param } => {736                        let Strip::Track(tid) = strip else { return Err("instrument automation outside a track".into()) };737                        let node = track_inst.iter().find(|(t, _)| *t == tid).map(|x| x.1).ok_or("instrument automation on a track without instrument")?;738                        let desc = engine_descs739                            .iter()740                            .find(|(n, _)| *n == node)741                            .map(|x| &x.1)742                            .ok_or(format!("engine '{}' publishes no parameter table", model.unwrap_or("?")))?;743                        let p = desc.params.iter().position(|p| &p.name == param).ok_or(format!("engine '{}' has no parameter '{}'", desc.model, param))?;744                        LaneTarget::InstrumentParam { node, param: p }745                    }746                };747                let pts: Vec<(u64, f32, Curve)> = lane.points.iter().map(|p| (seconds_to_samples(p.at_sec, sample_rate), p.value as f32, p.curve)).collect();748                if pts.windows(2).any(|w| w[1].0 < w[0].0) || pts.iter().any(|p| !p.1.is_finite()) {749                    return Err("automation points must be sorted and finite".into());750                }751                auto_bounds.extend(pts.iter().map(|p| p.0));752                lanes.push(Lane { target, pts, idx: 0 });753            }754            Ok(())755        };756        for t in &program.tracks {757            add_lanes(Strip::Track(t.id), &t.automation, t.instrument.as_ref().map(|i| i.model.as_str()))?;758        }759        for b in &program.buses {760            add_lanes(Strip::Bus(b.id), &b.automation, None)?;761        }762        add_lanes(Strip::Master, &program.master.automation, None)?;763        auto_bounds.sort_unstable();764        auto_bounds.dedup();765766        // Stems: the inputs of the master sum, traced back to the strip they belong to.767        let mut stems = Vec::new();768        if limits.capture_stems {769            if let Some(ms) = master_sum {770                let mut ins: Vec<u32> = graph.inputs_of(ms).collect();771                ins.sort_unstable();772                for i in ins {773                    let mut cur = i;774                    let strip = loop {775                        match &graph.nodes[cur as usize].kind {776                            NodeKind::Fader { strip } => break Some(*strip),777                            NodeKind::Send { from, .. } => break Some(*from),778                            NodeKind::LatencyDelay { .. } => match graph.inputs_of(cur).next() {779                                Some(p) => cur = p,780                                None => break None,781                            },782                            _ => break None,783                        }784                    };785                    if let Some(s) = strip {786                        stems.push((s, graph.nodes[i as usize].total_latency, buf_of[i as usize] as usize));787                    }788                }789            }790        }791792        let end_sample = seconds_to_samples(program.end_sec, sample_rate).max(events.last().map(|e| e.sample).unwrap_or(0));793        let bufs: Vec<Buf> = (0..n_bufs).map(|_| [vec![0.0; QUANTUM], vec![0.0; QUANTUM]]).collect();794        bytes += n_bufs as usize * QUANTUM * 8 + events.len() * std::mem::size_of::<Ev>() + lanes.iter().map(|l| l.pts.len() * 16).sum::<usize>();795        let beats = beat_grid(program, sample_rate);796        bytes += beats.len() * 16;797798        let mut strip_infos = Vec::new();799        for s in &strips {800            let (name, model) = match s.strip {801                Strip::Track(id) => {802                    let t = track_of(id)?;803                    (t.name.clone(), t.instrument.as_ref().map(|i| i.model.clone()))804                }805                Strip::Bus(id) => (program.buses.iter().find(|b| b.id == id).map(|b| b.name.clone()).unwrap_or_default(), None),806                Strip::Master => ("master".to_string(), None),807            };808            let instrument_params = match s.strip {809                Strip::Track(id) => track_inst810                    .iter()811                    .find(|(t, _)| *t == id)812                    .and_then(|(_, n)| engine_descs.iter().find(|(m, _)| m == n))813                    .map(|(_, d)| d.params.iter().map(|p| p.name.clone()).collect())814                    .unwrap_or_default(),815                _ => Vec::new(),816            };817            strip_infos.push(StripInfo {818                strip: s.strip,819                name,820                effects: info_fx.iter().filter(|(st, _)| *st == s.strip).map(|x| x.1.clone()).collect(),821                instrument_model: model,822                instrument_params,823            });824        }825        let info = ProgramInfo {826            sample_rate,827            end_sample,828            total_latency: graph.total_latency,829            strips: strip_infos,830            nodes: nodes.len(),831            buffers: n_bufs as usize,832            events: events.len(),833            automation_lanes: lanes.len(),834            estimated_bytes: bytes,835        };836837        let mut p = PreparedProgram {838            sample_rate,839            tuning_hz: program.tuning_hz,840            nodes,841            bufs,842            scratch: [vec![0.0; QUANTUM], vec![0.0; QUANTUM]],843            out_buf,844            events,845            cursor: 0,846            lanes,847            auto_bounds,848            auto_cursor: 0,849            strips,850            solo_active: false,851            track_inst,852            fx_nodes,853            fader_nodes,854            stems,855            limiter_node,856            beats,857            tempo_map: program.tempo_map.clone(),858            signatures: program.signatures.clone(),859            end_sample,860            total_latency: graph.total_latency,861            tap_node: None,862            info,863        };864        p.refresh_solo();865        Ok(p)866    }867868    pub fn info(&self) -> &ProgramInfo {869        &self.info870    }871    pub fn sample_rate(&self) -> u32 {872        self.sample_rate873    }874    pub fn end_sample(&self) -> u64 {875        self.end_sample876    }877    pub fn total_latency(&self) -> u32 {878        self.total_latency879    }880881    /// Strips whose signal feeds the master sum, with the latency already accumulated at that882    /// point. Empty unless prepared with `Limits::capture_stems`.883    pub fn stems(&self) -> impl Iterator<Item = (Strip, u32)> + '_ {884        self.stems.iter().map(|s| (s.0, s.1))885    }886887    /// Audio of stem `index` (order of [`PreparedProgram::stems`]) for the chunk just rendered.888    pub(crate) fn stem_chunk(&self, index: usize, n: usize) -> (&[f32], &[f32]) {889        let b = &self.bufs[self.stems[index].2];890        (&b[0][..n], &b[1][..n])891    }892893    pub(crate) fn output_chunk(&self, n: usize) -> (&[f32], &[f32]) {894        let b = &self.bufs[self.out_buf];895        (&b[0][..n], &b[1][..n])896    }897898    fn refresh_solo(&mut self) {899        self.solo_active = self.strips.iter().any(|s| s.is_track && s.soloed());900    }901902    fn strip_mut(&mut self, strip: Strip) -> Option<&mut StripState> {903        self.strips.iter_mut().find(|s| s.strip == strip)904    }905906    pub(crate) fn set_gain(&mut self, strip: Strip, db: Option<f32>) {907        if let Some(s) = self.strip_mut(strip) {908            s.gain_override = db.filter(|v| !v.is_nan()).map(|v| v.clamp(-144.0, 24.0));909        }910    }911    pub(crate) fn set_pan(&mut self, strip: Strip, pan: Option<f32>) {912        if let Some(s) = self.strip_mut(strip) {913            s.pan_override = pan.filter(|v| v.is_finite()).map(|v| v.clamp(-1.0, 1.0));914        }915    }916    pub(crate) fn set_mute(&mut self, strip: Strip, mute: Option<bool>) {917        if let Some(s) = self.strip_mut(strip) {918            s.mute_override = mute;919        }920    }921    pub(crate) fn set_solo(&mut self, strip: Strip, solo: Option<bool>) {922        if let Some(s) = self.strip_mut(strip) {923            s.solo_override = solo;924        }925        self.refresh_solo();926    }927928    fn fx_mut(&mut self, strip: Strip, index: u32) -> Option<&mut EffectExec> {929        let node = self.fx_nodes.iter().find(|(s, i, _)| *s == strip && *i == index)?.2;930        match &mut self.nodes[node].exec {931            Exec::Effect(e) => Some(e),932            _ => None,933        }934    }935    pub(crate) fn set_effect_param(&mut self, strip: Strip, index: u32, param: u32, value: f32) {936        if let (Some(e), true) = (self.fx_mut(strip, index), value.is_finite()) {937            e.fx.set_param(param as usize, value);938        }939    }940    pub(crate) fn set_effect_mix(&mut self, strip: Strip, index: u32, mix: f32) {941        if let (Some(e), true) = (self.fx_mut(strip, index), mix.is_finite()) {942            e.spec_mix = mix.clamp(0.0, 1.0);943            e.mix_target = if e.bypass { 0.0 } else { e.spec_mix };944        }945    }946    pub(crate) fn set_effect_bypass(&mut self, strip: Strip, index: u32, bypass: bool) {947        if let Some(e) = self.fx_mut(strip, index) {948            e.bypass = bypass;949            e.mix_target = if bypass { 0.0 } else { e.spec_mix };950        }951    }952953    fn inst_mut(&mut self, track: u32) -> Option<&mut Box<dyn Instrument>> {954        let node = self.track_inst.iter().find(|(t, _)| *t == track)?.1;955        match &mut self.nodes[node].exec {956            Exec::Instrument { inst } => Some(inst),957            _ => None,958        }959    }960    pub(crate) fn set_instrument_param(&mut self, track: u32, param: u32, value: f32) {961        if let (Some(i), true) = (self.inst_mut(track), value.is_finite()) {962            i.set_param(param as usize, value);963        }964    }965    pub(crate) fn live_note_on(&mut self, track: u32, id: u64, pitch: f32, velocity: f32) {966        let tuning = self.tuning_hz as f32;967        if let (Some(i), true) = (self.inst_mut(track), pitch.is_finite() && velocity.is_finite()) {968            let pitch = pitch.clamp(0.0, 135.0);969            i.note_on(&NoteOn {970                id,971                pitch,972                freq: tuning * ((pitch - 69.0) / 12.0).exp2(),973                velocity: velocity.clamp(0.0, 1.0),974                articulation: Articulation::Normal,975            });976        }977    }978    pub(crate) fn live_note_off(&mut self, track: u32, id: u64) {979        if let Some(i) = self.inst_mut(track) {980            i.note_off(id);981        }982    }983    pub(crate) fn live_bend(&mut self, track: u32, id: u64, semitones: f32) {984        if let (Some(i), true) = (self.inst_mut(track), semitones.is_finite()) {985            i.pitch_bend(id, semitones);986        }987    }988    pub(crate) fn live_sustain(&mut self, track: u32, down: bool) {989        if let Some(i) = self.inst_mut(track) {990            i.sustain(down);991        }992    }993994    pub(crate) fn set_tap(&mut self, tap: TapPoint) {995        self.tap_node = match tap {996            TapPoint::Master => None,997            TapPoint::Track(id) => self.fader_nodes.iter().find(|(s, _)| *s == Strip::Track(id)).map(|x| x.1),998            TapPoint::Bus(id) => self.fader_nodes.iter().find(|(s, _)| *s == Strip::Bus(id)).map(|x| x.1),999            TapPoint::Instrument(id) => self.track_inst.iter().find(|(t, _)| *t == id).map(|x| x.1),1000        };1001    }1002    pub(crate) fn has_tap(&self) -> bool {1003        self.tap_node.is_some()1004    }10051006    /// Copies the live overrides (gain, pan, mute, solo) of strips that also exist in `old`.1007    pub(crate) fn adopt_overrides(&mut self, old: &PreparedProgram) {1008        for s in &mut self.strips {1009            if let Some(o) = old.strips.iter().find(|o| o.strip == s.strip) {1010                s.gain_override = o.gain_override;1011                s.pan_override = o.pan_override;1012                s.mute_override = o.mute_override;1013                s.solo_override = o.solo_override;1014            }1015        }1016        self.refresh_solo();1017    }10181019    /// Releases every sounding note (tails ring out).1020    pub(crate) fn all_notes_off(&mut self) {1021        for n in &mut self.nodes {1022            if let Exec::Instrument { inst } = &mut n.exec {1023                inst.all_notes_off();1024            }1025        }1026    }10271028    /// Silences everything at once: instruments, effects, delay lines, smoothing.1029    pub(crate) fn panic(&mut self) {1030        for n in &mut self.nodes {1031            match &mut n.exec {1032                Exec::Instrument { inst } => inst.reset(),1033                Exec::Effect(e) => {1034                    e.fx.reset();1035                    e.dry_l.fill(0.0);1036                    e.dry_r.fill(0.0);1037                }1038                Exec::Delay { l, r, .. } => {1039                    l.fill(0.0);1040                    r.fill(0.0);1041                }1042                Exec::Limiter(l) => l.reset(),1043                _ => {}1044            }1045        }1046    }10471048    /// Moves the event and automation cursors to `pos`. Notes that started before `pos` are not1049    /// retriggered. Does not touch what is currently sounding.1050    pub(crate) fn locate(&mut self, pos: u64) {1051        self.cursor = self.events.partition_point(|e| e.sample < pos);1052        self.auto_cursor = self.auto_bounds.partition_point(|b| *b <= pos);1053        for l in &mut self.lanes {1054            l.seek(pos);1055        }1056    }10571058    /// Like [`locate`](Self::locate), then restarts the notes that are sounding at `pos` (started1059    /// before it, ending after it), so a hot swap does not drop held notes. At most the 8192 events1060    /// preceding `pos` are examined (bounded work on the audio thread); older notes are not chased.1061    pub(crate) fn locate_chasing(&mut self, pos: u64) {1062        self.locate(pos);1063        let lo = self.cursor.saturating_sub(8192);1064        for i in lo..self.cursor {1065            let e = self.events[i];1066            if let EvKind::On { pitch, freq, velocity, articulation, until } = e.kind {1067                if until > pos {1068                    if let Exec::Instrument { inst } = &mut self.nodes[e.node as usize].exec {1069                        inst.note_on(&NoteOn { id: e.id, pitch, freq, velocity, articulation });1070                    }1071                }1072            }1073        }1074    }10751076    /// First sample after `pos` at which a chunk must end (note or automation boundary).1077    pub(crate) fn next_boundary(&mut self, pos: u64) -> u64 {1078        let mut b = u64::MAX;1079        let mut c = self.cursor;1080        while c < self.events.len() && self.events[c].sample <= pos {1081            c += 1;1082        }1083        if c < self.events.len() {1084            b = self.events[c].sample;1085        }1086        while self.auto_cursor < self.auto_bounds.len() && self.auto_bounds[self.auto_cursor] <= pos {1087            self.auto_cursor += 1;1088        }1089        if self.auto_cursor < self.auto_bounds.len() {1090            b = b.min(self.auto_bounds[self.auto_cursor]);1091        }1092        b1093    }10941095    /// Next metronome beat at or after `pos`: (sample, accent).1096    pub(crate) fn next_beat(&self, pos: u64) -> Option<(u64, bool)> {1097        let i = self.beats.partition_point(|b| b.0 < pos);1098        self.beats.get(i).copied()1099    }11001101    /// Beat length in samples and beats per bar at `pos` (for the count-in).1102    pub(crate) fn beat_at(&self, pos: u64) -> (u64, u32) {1103        let whole = self.tempo_map.position_at_seconds(pos as f64 / self.sample_rate as f64);1104        let mut sig = &self.signatures[0];1105        for s in &self.signatures {1106            if s.at.to_f64() <= whole + 1e-9 {1107                sig = s;1108            }1109        }1110        let mut tp = &self.tempo_map.points[0];1111        for p in &self.tempo_map.points {1112            if p.at.to_f64() <= whole + 1e-9 {1113                tp = p;1114            }1115        }1116        let beat_sec = tp.seconds_per_whole() / sig.denominator.max(1) as f64;1117        (((beat_sec * self.sample_rate as f64) + 0.5).floor().max(1.0) as u64, sig.numerator.max(1))1118    }11191120    pub(crate) fn limiter_reduction_db(&self) -> f32 {1121        match self.limiter_node.map(|n| &self.nodes[n].exec) {1122            Some(Exec::Limiter(l)) => l.reduction_db(),1123            _ => 0.0,1124        }1125    }11261127    pub(crate) fn active_voices(&self) -> usize {1128        self.track_inst1129            .iter()1130            .map(|(_, n)| match &self.nodes[*n].exec {1131                Exec::Instrument { inst } => inst.active_voices(),1132                _ => 0,1133            })1134            .sum()1135    }11361137    /// Renders `n <= QUANTUM` frames starting at timeline sample `pos`. When `playing`, events at1138    /// `pos` fire first and automation is applied; the caller guarantees that no boundary lies1139    /// strictly inside `(pos, pos + n)`. The result is read with `output_chunk`.1140    pub(crate) fn render(&mut self, pos: u64, n: usize, playing: bool, shared: &Shared) {1141        debug_assert!(n > 0 && n <= QUANTUM);1142        if playing {1143            while self.cursor < self.events.len() && self.events[self.cursor].sample <= pos {1144                let e = self.events[self.cursor];1145                self.cursor += 1;1146                if let Exec::Instrument { inst } = &mut self.nodes[e.node as usize].exec {1147                    match e.kind {1148                        EvKind::On { pitch, freq, velocity, articulation, .. } => inst.note_on(&NoteOn { id: e.id, pitch, freq, velocity, articulation }),1149                        EvKind::Off => inst.note_off(e.id),1150                        EvKind::Bend { semitones } => inst.pitch_bend(e.id, semitones),1151                    }1152                }1153            }1154        }1155        // First chunk of a strip: start from the values in effect at `pos`, without a ramp.1156        let solo_active = self.solo_active;1157        if self.strips.iter().any(|s| !s.primed) {1158            for li in 0..self.lanes.len() {1159                match self.lanes[li].target {1160                    LaneTarget::Gain(s) if !self.strips[s].primed => self.strips[s].auto_gain = Some(self.lanes[li].value_at(pos)),1161                    LaneTarget::Pan(s) if !self.strips[s].primed => self.strips[s].auto_pan = Some(self.lanes[li].value_at(pos)),1162                    _ => {}1163                }1164            }1165            for s in self.strips.iter_mut().filter(|s| !s.primed) {1166                let (l, r, _) = s.target(solo_active);1167                s.cur_l = l;1168                s.cur_r = r;1169                s.primed = true;1170            }1171        }1172        // Automation: parameters take the value at the chunk start, faders ramp linearly to the1173        // value at the chunk's last sample (a step is therefore declicked over the chunk that follows it).1174        for li in 0..self.lanes.len() {1175            let target = self.lanes[li].target;1176            match target {1177                LaneTarget::Gain(s) => self.strips[s].auto_gain = Some(self.lanes[li].value_at(pos + if playing { n as u64 - 1 } else { 0 })),1178                LaneTarget::Pan(s) => self.strips[s].auto_pan = Some(self.lanes[li].value_at(pos + if playing { n as u64 - 1 } else { 0 })),1179                LaneTarget::EffectParam { node, param } => {1180                    let v = self.lanes[li].value_at(pos);1181                    if let Exec::Effect(e) = &mut self.nodes[node].exec {1182                        e.fx.set_param(param, v);1183                    }1184                }1185                LaneTarget::EffectMix { node } => {1186                    let v = self.lanes[li].value_at(pos).clamp(0.0, 1.0);1187                    if let Exec::Effect(e) = &mut self.nodes[node].exec {1188                        e.spec_mix = v;1189                        e.mix_target = if e.bypass { 0.0 } else { v };1190                    }1191                }1192                LaneTarget::InstrumentParam { node, param } => {1193                    let v = self.lanes[li].value_at(pos);1194                    if let Exec::Instrument { inst } = &mut self.nodes[node].exec {1195                        inst.set_param(param, v);1196                    }1197                }1198            }1199        }12001201        let sr = self.sample_rate as f32;1202        let smooth = 1.0 - (-(n as f32) / (FADER_SMOOTH_SEC * sr)).exp();1203        let ms_keep = (-(n as f32) / (RMS_WINDOW_SEC * sr)).exp();1204        let mut scrubbed = 0u64;12051206        for ni in 0..self.nodes.len() {1207            let out_i = self.nodes[ni].out as usize;1208            if matches!(self.nodes[ni].exec, Exec::Output) {1209                continue;1210            }1211            let mut out = std::mem::take(&mut self.bufs[out_i]);1212            let (ol, or) = {1213                let (a, b) = out.split_at_mut(1);1214                (&mut a[0][..n], &mut b[0][..n])1215            };1216            let node = &mut self.nodes[ni];1217            let in0 = node.inputs.first().map(|i| *i as usize);1218            match &mut node.exec {1219                Exec::Instrument { inst } => {1220                    ol.fill(0.0);1221                    or.fill(0.0);1222                    inst.process(ol, or);1223                    if !all_finite(ol, or) {1224                        ol.fill(0.0);1225                        or.fill(0.0);1226                        inst.reset();1227                        scrubbed += n as u64;1228                    }1229                }1230                Exec::Clips { clips } => {1231                    ol.fill(0.0);1232                    or.fill(0.0);1233                    if playing {1234                        for c in clips.iter() {1235                            if c.len == 0 || pos + n as u64 <= c.start || pos >= c.start + c.len {1236                                continue;1237                            }1238                            let l = &c.asset.channels[0];1239                            let r = c.asset.channels.get(1).unwrap_or(l);1240                            for i in 0..n {1241                                let t = pos + i as u64;1242                                if t < c.start || t >= c.start + c.len {1243                                    continue;1244                                }1245                                let k = t - c.start;1246                                let mut g = c.gain;1247                                if k < c.fade_in {1248                                    g *= k as f32 / c.fade_in as f32;1249                                }1250                                if c.len - k <= c.fade_out {1251                                    g *= (c.len - k) as f32 / c.fade_out as f32;1252                                }1253                                let src = (c.offset + k) as usize;1254                                ol[i] += l[src] * g;1255                                or[i] += r[src] * g;1256                            }1257                        }1258                        if !all_finite(ol, or) {1259                            ol.fill(0.0);1260                            or.fill(0.0);1261                            scrubbed += n as u64;1262                        }1263                    }1264                }1265                Exec::Effect(e) => {1266                    let inp = &self.bufs[in0.unwrap_or(out_i)];1267                    let (il, ir) = (&inp[0][..n], &inp[1][..n]);1268                    // Dry path, delayed by the effect's latency so dry and wet stay aligned.1269                    let (dl, dr) = {1270                        let (a, b) = self.scratch.split_at_mut(1);1271                        (&mut a[0][..n], &mut b[0][..n])1272                    };1273                    if e.latency == 0 {1274                        dl.copy_from_slice(il);1275                        dr.copy_from_slice(ir);1276                    } else {1277                        for i in 0..n {1278                            dl[i] = e.dry_l[e.dry_pos];1279                            dr[i] = e.dry_r[e.dry_pos];1280                            e.dry_l[e.dry_pos] = il[i];1281                            e.dry_r[e.dry_pos] = ir[i];1282                            e.dry_pos = (e.dry_pos + 1) % e.latency;1283                        }1284                    }1285                    if e.mix == 0.0 && e.mix_target == 0.0 {1286                        // Fully dry (mix 0 or bypassed): the effect is not run, the latency is kept.1287                        ol.copy_from_slice(dl);1288                        or.copy_from_slice(dr);1289                    } else {1290                        ol.copy_from_slice(il);1291                        or.copy_from_slice(ir);1292                        e.fx.process(ol, or);1293                        if !all_finite(ol, or) {1294                            ol.fill(0.0);1295                            or.fill(0.0);1296                            e.fx.reset();1297                            scrubbed += n as u64;1298                        }1299                        let step = (e.mix_target - e.mix) / n as f32;1300                        let mut m = e.mix;1301                        for i in 0..n {1302                            m += step;1303                            ol[i] = dl[i] + (ol[i] - dl[i]) * m;1304                            or[i] = dr[i] + (or[i] - dr[i]) * m;1305                        }1306                        e.mix = e.mix_target;1307                    }1308                }1309                Exec::Fader { strip } => {1310                    let inp = &self.bufs[in0.unwrap_or(out_i)];1311                    let (il, ir) = (&inp[0][..n], &inp[1][..n]);1312                    let s = &mut self.strips[*strip];1313                    let automated = (s.auto_gain.is_some() && s.gain_override.is_none()) || (s.auto_pan.is_some() && s.pan_override.is_none());1314                    let (tl, tr, silent) = s.target(solo_active);1315                    let (el, er) = if automated && !silent { (tl, tr) } else { (s.cur_l + (tl - s.cur_l) * smooth, s.cur_r + (tr - s.cur_r) * smooth) };1316                    let (sl, sr_) = ((el - s.cur_l) / n as f32, (er - s.cur_r) / n as f32);1317                    let (mut gl, mut gr) = (s.cur_l, s.cur_r);1318                    let (mut pk_l, mut pk_r, mut sq_l, mut sq_r, mut overs) = (0.0f32, 0.0f32, 0.0f32, 0.0f32, 0u32);1319                    for i in 0..n {1320                        gl += sl;1321                        gr += sr_;1322                        let (a, b) = (il[i] * gl, ir[i] * gr);1323                        ol[i] = a;1324                        or[i] = b;1325                        pk_l = pk_l.max(a.abs());1326                        pk_r = pk_r.max(b.abs());1327                        sq_l += a * a;1328                        sq_r += b * b;1329                        overs += (a.abs() >= 1.0 || b.abs() >= 1.0) as u32;1330                    }1331                    s.cur_l = if (el - tl).abs() < 1e-9 { tl } else { el };1332                    s.cur_r = if (er - tr).abs() < 1e-9 { tr } else { er };1333                    s.ms_l = s.ms_l * ms_keep + (1.0 - ms_keep) * sq_l / n as f32;1334                    s.ms_r = s.ms_r * ms_keep + (1.0 - ms_keep) * sq_r / n as f32;1335                    if s.ms_l < 1e-20 {1336                        s.ms_l = 0.0;1337                    }1338                    if s.ms_r < 1e-20 {1339                        s.ms_r = 0.0;1340                    }1341                    if let Some(slot) = s.slot {1342                        shared.meter_write(slot, pk_l, pk_r, s.ms_l, s.ms_r, overs);1343                    }1344                }1345                Exec::Send { gain } => {1346                    let inp = &self.bufs[in0.unwrap_or(out_i)];1347                    for i in 0..n {1348                        ol[i] = inp[0][i] * *gain;1349                        or[i] = inp[1][i] * *gain;1350                    }1351                }1352                Exec::Sum => {1353                    ol.fill(0.0);1354                    or.fill(0.0);1355                    for inp in &node.inputs {1356                        let b = &self.bufs[*inp as usize];1357                        for i in 0..n {1358                            ol[i] += b[0][i];1359                            or[i] += b[1][i];1360                        }1361                    }1362                }1363                Exec::Delay { l, r, pos: dp } => {1364                    let inp = &self.bufs[in0.unwrap_or(out_i)];1365                    if l.is_empty() {1366                        ol.copy_from_slice(&inp[0][..n]);1367                        or.copy_from_slice(&inp[1][..n]);1368                    } else {1369                        for i in 0..n {1370                            ol[i] = l[*dp];1371                            or[i] = r[*dp];1372                            l[*dp] = inp[0][i];1373                            r[*dp] = inp[1][i];1374                            *dp = (*dp + 1) % l.len();1375                        }1376                    }1377                }1378                Exec::Limiter(lim) => {1379                    let inp = &self.bufs[in0.unwrap_or(out_i)];1380                    ol.copy_from_slice(&inp[0][..n]);1381                    or.copy_from_slice(&inp[1][..n]);1382                    if !all_finite(ol, or) {1383                        for i in 0..n {1384                            if !ol[i].is_finite() {1385                                ol[i] = 0.0;1386                                scrubbed += 1;1387                            }1388                            if !or[i].is_finite() {1389                                or[i] = 0.0;1390                                scrubbed += 1;1391                            }1392                        }1393                    }1394                    lim.process(ol, or);1395                }1396                Exec::Output => {}1397            }1398            if self.tap_node == Some(ni) {1399                shared.tap_scope.write(ol, or);1400            }1401            self.bufs[out_i] = out;1402        }1403        if scrubbed > 0 {1404            shared.scrubbed.fetch_add(scrubbed, Relaxed);1405        }1406    }1407}1408
Files main
Menu

Theme