mirror of
https://github.com/storytold/soundcraft.git
synced 2026-12-02 20:22:27 -05:00
Merge main into fredapps/macos-plugin-entitlements
This commit is contained in:
commit
bc1642a9f0
9 files changed
+1423
-14
No files matched your search
@@ -0,0 +1,119 @@
|
||||
//! Existing commands/history and saved session PCM for bounded send automation.
|
||||
use craft_audio::AudioBuffer;
|
||||
use serde_json::json;
|
||||
use soundcraft_engine::{Engine, io};
|
||||
use soundcraft_model::{AutoParam, ChannelFormat, Clip, FileFormat, Route, Session, TrackKind};
|
||||
use soundcraft_time::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
fn fixture() -> Engine {
|
||||
let mut s = Session::default();
|
||||
let t = s.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Original"));
|
||||
let buffer = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.25; 512]] };
|
||||
let src = io::add_source(&mut s, "Original synthetic", buffer, None, FileFormat::Wav);
|
||||
let cid = s.new_clip_id();
|
||||
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "Original", src, 0, 0, 512));
|
||||
s.track_mut(t).unwrap().mixer.output = Route::None;
|
||||
let mut e = Engine::new(s);
|
||||
e.execute("mix.new_bus", &json!({"name":"Send","format":"stereo"})).unwrap();
|
||||
e.execute("mix.send", &json!({"track":"Original","bus":"Send","slot":"A","level_db":0})).unwrap();
|
||||
e.execute("track.new", &json!({"name":"Return","kind":"aux","format":"stereo"})).unwrap();
|
||||
let bus = e.session().busses.iter().find(|b| b.name == "Send").unwrap().id;
|
||||
let aux = e.session().tracks.iter().find(|t| t.kind == TrackKind::Aux).unwrap().id;
|
||||
e.session_mut().track_mut(aux).unwrap().mixer.input = Route::Bus(bus);
|
||||
e.mark_clean();
|
||||
e
|
||||
}
|
||||
fn render(e: &Engine) -> Vec<Vec<f32>> {
|
||||
let out = soundcraft_mix::render_range(e.session(), Range::new(0, 512), 37);
|
||||
assert_eq!(out.len(), 2);
|
||||
assert!(out.iter().all(|c| c.len() == 512));
|
||||
out
|
||||
}
|
||||
fn point(e: &mut Engine, param: &str, at: i64, value: f32) {
|
||||
e.execute("automation.set_point", &json!({"track":"Original","param":param,"at":at,"value":value})).unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn commands_undo_redo_reuse_renderer_and_preserve_render_state() {
|
||||
let mut e = fixture();
|
||||
let baseline = render(&e);
|
||||
point(&mut e, "send_a_pan", 0, -1.0);
|
||||
point(&mut e, "send_a_pan", 173, 1.0);
|
||||
point(&mut e, "send_a_mute", 0, 0.0);
|
||||
let before = render(&e);
|
||||
point(&mut e, "send_a_mute", 97, 1.0);
|
||||
let after = render(&e);
|
||||
assert_ne!(before, after);
|
||||
assert_ne!(baseline, before);
|
||||
let arc = e.session_arc();
|
||||
let serialized = e.session().to_json().unwrap();
|
||||
let revision = e.revision;
|
||||
let history = e.undo_history();
|
||||
let dirty = e.is_dirty();
|
||||
let mut mix = soundcraft_mix::MixEngine::new(48_000.0, 512);
|
||||
let mut out = vec![vec![0.0; 512]; 2];
|
||||
mix.render(e.session(), 0, 512, &mut out);
|
||||
assert_eq!(out, after);
|
||||
mix.render(e.session(), 97, 13, &mut out);
|
||||
assert!(Arc::ptr_eq(&arc, &e.session_arc()));
|
||||
assert_eq!(serialized, e.session().to_json().unwrap());
|
||||
assert_eq!(revision, e.revision);
|
||||
assert_eq!(history, e.undo_history());
|
||||
assert_eq!(dirty, e.is_dirty());
|
||||
assert!(e.undo());
|
||||
assert_eq!(render(&e), before);
|
||||
mix.render(e.session(), 0, 512, &mut out);
|
||||
assert_eq!(out, before);
|
||||
assert!(e.redo());
|
||||
assert_eq!(render(&e), after);
|
||||
mix.render(e.session(), 0, 512, &mut out);
|
||||
assert_eq!(out, after);
|
||||
e.execute("mix.automation_mode", &json!({"track":"Original","mode":"off"})).unwrap();
|
||||
assert_eq!(render(&e), baseline);
|
||||
}
|
||||
#[test]
|
||||
fn lane_commands_survive_folder_and_bundle_save_reopen_with_exact_pcm() {
|
||||
let mut e = fixture();
|
||||
e.execute("mix.send_level", &json!({"track":"Original","slot":"A","pan":0.5,"mute":true})).unwrap();
|
||||
point(&mut e, "send_a_pan", 37, -1.0);
|
||||
point(&mut e, "send_a_pan", 401, 1.0);
|
||||
point(&mut e, "send_a_mute", 0, 0.0);
|
||||
e.execute("automation.write_range", &json!({"track":"Original","param":"send_a_mute","start":97,"end":173,"value":1.0})).unwrap();
|
||||
let expected = render(&e);
|
||||
assert!(expected.iter().flatten().any(|v| v.abs() > 0.05));
|
||||
let dir = std::env::temp_dir().join(format!("soundcraft-send-automation-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let path = dir.join("Original/Send.scraft").to_string_lossy().into_owned();
|
||||
io::save_session(&mut e, &path).unwrap();
|
||||
let mut reopened = Engine::default();
|
||||
assert!(io::open_session(&mut reopened, &path).unwrap().is_empty());
|
||||
assert_eq!(render(&reopened), expected);
|
||||
let tr = reopened.session().tracks.iter().find(|t| t.name == "Original").unwrap();
|
||||
assert_eq!(tr.lane(&AutoParam::SendPan(0)).unwrap().points.len(), 2);
|
||||
assert!(!reopened.is_dirty());
|
||||
assert!(!reopened.can_undo());
|
||||
let (bundle, _) = io::session_bundle(e.session()).unwrap();
|
||||
let mut bundled = Engine::default();
|
||||
io::open_session_bytes(&mut bundled, "Send.scraftz", &bundle).unwrap();
|
||||
assert_eq!(render(&bundled), expected);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn absent_enabled_field_keeps_legacy_reader_behavior() {
|
||||
let mut e = fixture();
|
||||
point(&mut e, "send_a_pan", 0, -1.0);
|
||||
point(&mut e, "send_a_mute", 0, 0.0);
|
||||
let expected = render(&e);
|
||||
assert!(expected.iter().flatten().any(|v| v.abs() > 0.05));
|
||||
let mut json = serde_json::to_value(e.session()).unwrap();
|
||||
for track in json["tracks"].as_array_mut().unwrap() {
|
||||
for lane in track["automation"].as_array_mut().unwrap() {
|
||||
lane.as_object_mut().unwrap().remove("enabled");
|
||||
}
|
||||
}
|
||||
let mut old: Session = serde_json::from_value(json).unwrap();
|
||||
old.pool = e.session().pool.clone();
|
||||
let tr = old.tracks.iter().find(|t| t.name == "Original").unwrap();
|
||||
assert!(tr.automation.iter().all(|l| !l.enabled));
|
||||
assert_eq!(soundcraft_mix::render_range(&old, Range::new(0, 512), 100), expected);
|
||||
}
|
||||
+37
-7
@@ -70,6 +70,7 @@ mod midi;
|
||||
mod offline;
|
||||
mod pan;
|
||||
mod routing;
|
||||
mod send_automation;
|
||||
mod strip;
|
||||
mod threads;
|
||||
|
||||
@@ -362,7 +363,7 @@ impl MixEngine {
|
||||
}
|
||||
for b in &s.busses {
|
||||
let n = b.format.channels().clamp(1, MAX_CHANNELS);
|
||||
let bus = self.busses.entry(b.id).or_insert_with(|| BusBuf { fmt: b.format, buf: Vec::new() });
|
||||
let bus = self.busses.entry(b.id).or_insert_with(|| BusBuf { fmt: b.format, buf: Vec::new(), age: send_automation::SignalAge::Empty });
|
||||
bus.fmt = b.format;
|
||||
if bus.buf.len() != n {
|
||||
bus.buf = vec![vec![0.0; mb]; n];
|
||||
@@ -454,6 +455,7 @@ impl MixEngine {
|
||||
}
|
||||
self.ensure_synced(s);
|
||||
for b in self.busses.values_mut() {
|
||||
b.age = send_automation::SignalAge::Empty;
|
||||
for c in b.buf.iter_mut() {
|
||||
c.iter_mut().take(frames).for_each(|x| *x = 0.0);
|
||||
}
|
||||
@@ -508,9 +510,11 @@ impl MixEngine {
|
||||
let ch = st.buf.len();
|
||||
st.align.set(lmax_t.saturating_sub(st.latency), ch);
|
||||
st.align.process(&mut st.buf, frames);
|
||||
st.send_post_age = st.send_post_age.delayed(st.align.len);
|
||||
if t.mixer.sends.iter().flatten().any(|x| x.pre_fader) {
|
||||
st.align_pre.set(lmax_t.saturating_sub(st.latency), ch);
|
||||
st.align_pre.process(&mut st.pre, frames);
|
||||
st.send_pre_age = st.send_pre_age.delayed(st.align_pre.len);
|
||||
}
|
||||
let waits = match &t.mixer.output {
|
||||
Route::Main => true,
|
||||
@@ -546,6 +550,7 @@ impl MixEngine {
|
||||
let ch = st.buf.len();
|
||||
st.align.set(if pdc { lmax_a.saturating_sub(st.latency) } else { 0 }, ch);
|
||||
st.align.process(&mut st.buf, frames);
|
||||
st.send_post_age = st.send_post_age.delayed(st.align.len);
|
||||
st.out_extra.set(0, ch);
|
||||
self.route_strip(t, &mut st, pos, frames);
|
||||
self.strips.insert(t.id, st);
|
||||
@@ -643,22 +648,41 @@ impl MixEngine {
|
||||
let law = self.pan_law;
|
||||
for (i, snd) in t.mixer.sends.iter().enumerate() {
|
||||
let Some(snd) = snd else { continue };
|
||||
if snd.mute || strip.muted {
|
||||
if strip.muted {
|
||||
continue;
|
||||
}
|
||||
let src = if snd.pre_fader { &strip.pre } else { &strip.buf };
|
||||
let age = if snd.pre_fader { strip.send_pre_age } else { strip.send_post_age };
|
||||
let clock = age.clock(pos);
|
||||
let Route::Bus(b) = &snd.target else { continue };
|
||||
let Some(dst) = self.busses.get_mut(b) else { continue };
|
||||
let ordinary = !src_fmt.is_ambisonic() && !dst.fmt.is_ambisonic();
|
||||
let mute = ordinary.then(|| send_automation::Reader::for_send(t, AutoParam::SendMute, i, clock.at(0))).flatten();
|
||||
if mute.is_none() && snd.mute {
|
||||
continue;
|
||||
}
|
||||
let lvl = send_level(t, i, snd.level_db, pos);
|
||||
let gain = db_to_gain(lvl);
|
||||
let src = if snd.pre_fader { &strip.pre } else { &strip.buf };
|
||||
let Route::Bus(b) = &snd.target else { continue };
|
||||
let Some(dst) = self.busses.get_mut(b) else { continue };
|
||||
if gain <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
dst.age.include(age);
|
||||
let pan = (ordinary && src.len() == 1 && dst.fmt == ChannelFormat::Stereo)
|
||||
.then(|| send_automation::Reader::for_send(t, AutoParam::SendPan, i, clock.at(0)))
|
||||
.flatten();
|
||||
if let Some(pan) = pan {
|
||||
send_automation::apply_mono_stereo(src, frames, &mut dst.buf, gain, law, clock, pan, mute);
|
||||
continue;
|
||||
}
|
||||
// Mono sends use the send's own pan; stereo sends go straight to L/R.
|
||||
let stereo = if src.len() == 1 { [snd.pan, 0.0] } else { [-1.0, 1.0] };
|
||||
let surround = snd.surround.as_ref().or(if snd.follow_main_pan { t.mixer.surround.as_ref() } else { None });
|
||||
let m = build_matrix(src_fmt, src.len(), dst.fmt, dst.buf.len(), &PanSpec { stereo, surround }, law);
|
||||
apply_matrix(src, frames, &mut dst.buf, &m, gain);
|
||||
if let Some(mute) = mute {
|
||||
send_automation::apply_gated(src, frames, &mut dst.buf, &m, gain, clock, mute);
|
||||
} else {
|
||||
apply_matrix(src, frames, &mut dst.buf, &m, gain);
|
||||
}
|
||||
}
|
||||
let src: &[Vec<f32>] = match &t.mixer.output {
|
||||
Route::Main | Route::Bus(_) if strip.out_extra.len > 0 => {
|
||||
@@ -677,7 +701,10 @@ impl MixEngine {
|
||||
let (dst, dst_fmt) = match &t.mixer.output {
|
||||
Route::Main => (&mut self.main, self.main_fmt),
|
||||
Route::Bus(b) => match self.busses.get_mut(b) {
|
||||
Some(d) => (&mut d.buf, d.fmt),
|
||||
Some(d) => {
|
||||
d.age.include(strip.send_post_age.delayed(strip.out_extra.len));
|
||||
(&mut d.buf, d.fmt)
|
||||
}
|
||||
None => return,
|
||||
},
|
||||
_ => return,
|
||||
@@ -711,3 +738,6 @@ mod click;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod send_age_tests;
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{ChannelFormat, MAX_CHANNELS, PanLaw, Speaker, SpeakerPos, SurroundPan, SurroundParams, db_to_gain, gains};
|
||||
|
||||
/// Per-block routing gains: `m[src][dst]`.
|
||||
type Matrix = [[f32; MAX_CHANNELS]; MAX_CHANNELS];
|
||||
pub(crate) type Matrix = [[f32; MAX_CHANNELS]; MAX_CHANNELS];
|
||||
|
||||
/// How a source is panned: the stereo pan pair (mono uses `[0]`) and the optional surround pan.
|
||||
pub(crate) struct PanSpec<'a> {
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_audio::AudioBuffer;
|
||||
use soundcraft_dsp::Plugin;
|
||||
|
||||
use super::send_automation::SignalAge;
|
||||
use super::strip::{Block, BusBuf, LiveInput, MAX_LATENCY, PluginSlot, Strip, process_strip};
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn known_bus_ages_accumulate_and_mixed_ages_keep_the_legacy_clock() {
|
||||
let mut bus = SignalAge::Empty;
|
||||
assert_eq!(bus.input(), SignalAge::Known(0));
|
||||
bus.include(SignalAge::Known(71));
|
||||
bus.include(SignalAge::Known(71));
|
||||
assert_eq!(bus, SignalAge::Known(71));
|
||||
let aux_pre = bus.delayed(23);
|
||||
let aux_post = aux_pre.delayed(48);
|
||||
assert_eq!(aux_pre, SignalAge::Known(94));
|
||||
assert_eq!(aux_post, SignalAge::Known(142));
|
||||
assert_eq!(aux_pre.clock(300).at(0), 206);
|
||||
assert_eq!(aux_post.clock(300).at(0), 158);
|
||||
let nested = aux_post.delayed(71);
|
||||
assert_eq!(nested, SignalAge::Known(213));
|
||||
bus.include(SignalAge::Known(142));
|
||||
assert_eq!(bus, SignalAge::Mixed);
|
||||
assert_eq!(bus.delayed(71).clock(300).at(0), 300);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn age_overflow_preserves_audio_with_the_legacy_clock_fallback() {
|
||||
let age = SignalAge::Known(u64::MAX).delayed(1);
|
||||
assert_eq!(age, SignalAge::Mixed);
|
||||
assert_eq!(age.clock(-7).at(3), -4);
|
||||
let mut bus = SignalAge::Known(71);
|
||||
bus.include(SignalAge::Empty);
|
||||
assert_eq!(bus, SignalAge::Known(71));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn processed_insert_age_is_uncapped_while_pdc_stays_capped_and_overflow_falls_back() {
|
||||
struct DeclaredDelay {
|
||||
inner: Box<dyn Plugin>,
|
||||
latency: usize,
|
||||
}
|
||||
impl Plugin for DeclaredDelay {
|
||||
fn info(&self) -> &'static soundcraft_dsp::PluginInfo {
|
||||
self.inner.info()
|
||||
}
|
||||
fn prepare(&mut self, rate: f32, block: usize, channels: usize) {
|
||||
self.inner.prepare(rate, block, channels);
|
||||
}
|
||||
fn reset(&mut self) {
|
||||
self.inner.reset();
|
||||
}
|
||||
fn set_param(&mut self, id: &str, value: f32) -> bool {
|
||||
self.inner.set_param(id, value)
|
||||
}
|
||||
fn param(&self, id: &str) -> Option<f32> {
|
||||
self.inner.param(id)
|
||||
}
|
||||
fn process(&mut self, io: &mut [Vec<f32>], frames: usize) {
|
||||
self.inner.process(io, frames);
|
||||
}
|
||||
fn latency(&self) -> usize {
|
||||
self.latency
|
||||
}
|
||||
}
|
||||
fn slot(latency: usize) -> PluginSlot {
|
||||
let mut inner = soundcraft_dsp::create("gain").unwrap();
|
||||
inner.prepare(48_000.0, 16, 1);
|
||||
PluginSlot::test_instance("gain".into(), 1, Box::new(DeclaredDelay { inner, latency }))
|
||||
}
|
||||
let mut source = Session::default();
|
||||
source.edit.delay_compensation = false;
|
||||
let audio = source.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
|
||||
let source_id = soundcraft_model::SourceId(900);
|
||||
source.pool.insert(source_id, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.25; 16]] })));
|
||||
let clip = source.new_clip_id();
|
||||
let track = source.track_mut(audio).unwrap();
|
||||
track.playlist_mut().unwrap().clips.push(Clip::audio(clip, "Declared-age reference", source_id, 0, 0, 16));
|
||||
track.mixer.inserts[0] = Some(soundcraft_model::Insert::new("gain"));
|
||||
track.mixer.inserts[1] = Some(soundcraft_model::Insert::new("gain"));
|
||||
let mut pre = soundcraft_model::SendSlot::new(Route::None);
|
||||
pre.pre_fader = true;
|
||||
track.mixer.sends[0] = Some(pre);
|
||||
let mut strip = Strip::new();
|
||||
strip.buf = vec![vec![0.0; 16]];
|
||||
strip.scratch = vec![0.0; 16];
|
||||
strip.plugins = vec![Some(slot(MAX_LATENCY + 5)), Some(slot(MAX_LATENCY + 9))];
|
||||
let busses = HashMap::new();
|
||||
let live = LiveInput { input: &[], midi: &[], ports: None, midi_lost: 0, monitor_only: false, recording: false };
|
||||
let blk = Block { pos: 0, frames: 16, any_solo: false };
|
||||
process_strip(&source, source.track(audio).unwrap(), &mut strip, &busses, &live, blk);
|
||||
let declared_sum = 2 * MAX_LATENCY as u64 + 14;
|
||||
assert_eq!(strip.latency, MAX_LATENCY, "the existing PDC cap remains unchanged");
|
||||
assert_eq!(strip.send_pre_age, SignalAge::Known(declared_sum));
|
||||
assert_eq!(strip.send_post_age, SignalAge::Known(declared_sum));
|
||||
assert_eq!(strip.align.len, 0);
|
||||
assert_eq!(strip.align_pre.len, 0);
|
||||
assert_eq!(strip.pre, vec![vec![0.25; 16]]);
|
||||
assert_eq!(strip.buf, strip.pre, "declared age metadata never changes the processed PCM");
|
||||
|
||||
let bus = source.add_bus("Overflowing known input", ChannelFormat::Mono);
|
||||
let aux = source.add_track(TrackKind::Aux, ChannelFormat::Mono, None);
|
||||
let track = source.track_mut(aux).unwrap();
|
||||
track.mixer.input = Route::Bus(bus);
|
||||
track.mixer.inserts[0] = Some(soundcraft_model::Insert::new("gain"));
|
||||
let busses = HashMap::from([(bus, BusBuf { fmt: ChannelFormat::Mono, buf: vec![vec![0.25; 16]], age: SignalAge::Known(u64::MAX) })]);
|
||||
let mut aux_strip = Strip::new();
|
||||
aux_strip.buf = vec![vec![0.0; 16]];
|
||||
aux_strip.plugins = vec![Some(slot(1))];
|
||||
process_strip(&source, source.track(aux).unwrap(), &mut aux_strip, &busses, &live, blk);
|
||||
assert_eq!(aux_strip.latency, 1);
|
||||
assert_eq!(aux_strip.send_pre_age, SignalAge::Mixed);
|
||||
assert_eq!(aux_strip.send_post_age, SignalAge::Mixed);
|
||||
assert_eq!(aux_strip.send_post_age.clock(300).at(0), 300);
|
||||
assert_eq!(aux_strip.buf, vec![vec![0.25; 16]], "overflow preserves the output instead of silencing it");
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
//! Local send playback: sample-exact mono-to-stereo pan and stepped ordinary-bus mute.
|
||||
//! No document mutation, allocation, locks or persistent cursor survive a callback/seek.
|
||||
|
||||
use super::MAX_CHANNELS;
|
||||
use super::pan::Matrix;
|
||||
use soundcraft_dsp::pan::{PanLaw, gains};
|
||||
use soundcraft_model::{AutoParam, AutomationPoint, Track};
|
||||
use soundcraft_time::Samples;
|
||||
|
||||
/// Source-sample age metadata only; it never changes routing or audio delay compensation.
|
||||
/// A mixed-age sum has no single source clock, so new send readers retain their legacy clock.
|
||||
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum SignalAge {
|
||||
#[default]
|
||||
Empty,
|
||||
Known(u64),
|
||||
Mixed,
|
||||
}
|
||||
|
||||
impl SignalAge {
|
||||
pub(crate) fn input(self) -> Self {
|
||||
match self {
|
||||
Self::Empty => Self::Known(0),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn delayed(self, frames: usize) -> Self {
|
||||
match self {
|
||||
Self::Known(age) => u64::try_from(frames).ok().and_then(|frames| age.checked_add(frames)).map_or(Self::Mixed, Self::Known),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn include(&mut self, contribution: Self) {
|
||||
*self = match (*self, contribution) {
|
||||
(Self::Empty, age) | (age, Self::Empty) => age,
|
||||
(Self::Known(a), Self::Known(b)) if a == b => Self::Known(a),
|
||||
_ => Self::Mixed,
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) fn clock(self, position: Samples) -> Clock {
|
||||
let age = match self {
|
||||
Self::Known(age) => age,
|
||||
Self::Empty | Self::Mixed => 0,
|
||||
};
|
||||
Clock::new(position, age)
|
||||
}
|
||||
}
|
||||
|
||||
/// A forward cursor rebuilt at each callback's absolute position. Like the existing mixer
|
||||
/// readers, this deliberately ignores lane.enabled; global suspension/migration is separate.
|
||||
/// Nonfinite or decreasing-time lanes fall back to the static control for the whole callback.
|
||||
/// Finite values clamp to the control range; duplicate times deterministically use the last knot.
|
||||
pub(super) struct Reader<'a> {
|
||||
points: &'a [AutomationPoint],
|
||||
next: usize,
|
||||
mute: bool,
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
pub(super) fn for_send(t: &'a Track, param: fn(u8) -> AutoParam, slot: usize, pos: Samples) -> Option<Self> {
|
||||
if !t.mixer.automation_mode.reads() {
|
||||
return None;
|
||||
}
|
||||
let param = param(u8::try_from(slot).ok()?);
|
||||
let lane = t.lane(¶m)?;
|
||||
let points = &lane.points;
|
||||
if points.is_empty() || points.iter().any(|p| !p.value.is_finite()) || points.windows(2).any(|p| p[0].at > p[1].at) {
|
||||
return None;
|
||||
}
|
||||
Some(Self { points, next: points.partition_point(|p| p.at <= pos), mute: matches!(param, AutoParam::SendMute(_)) })
|
||||
}
|
||||
|
||||
pub(super) fn value(&mut self, pos: Samples) -> f32 {
|
||||
while self.points.get(self.next).is_some_and(|p| p.at <= pos) {
|
||||
self.next = self.next.saturating_add(1);
|
||||
}
|
||||
let Some(a) = self.points.get(self.next.saturating_sub(1)) else { return 0.0 };
|
||||
let lo = if self.mute { 0.0 } else { -1.0 };
|
||||
let av = a.value.clamp(lo, 1.0);
|
||||
if self.next == 0 || self.mute {
|
||||
return av;
|
||||
}
|
||||
let Some(b) = self.points.get(self.next) else { return av };
|
||||
// Valid timestamps may span i64::MIN..MAX. Widen before subtraction, and interpolate
|
||||
// bounded values in f64 so neither timestamp nor value arithmetic can overflow.
|
||||
let width = i128::from(b.at) - i128::from(a.at);
|
||||
if width <= 0 {
|
||||
return av;
|
||||
}
|
||||
let fraction = ((i128::from(pos) - i128::from(a.at)) as f64 / width as f64).clamp(0.0, 1.0);
|
||||
(f64::from(av) + (f64::from(b.value.clamp(lo, 1.0)) - f64::from(av)) * fraction) as f32
|
||||
}
|
||||
}
|
||||
|
||||
/// Timeline position represented by a delayed source tap. Widen the entire expression before
|
||||
/// clamping, so advancing a frame near MIN/MAX does not lose an earlier delay subtraction.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Clock {
|
||||
position: Samples,
|
||||
age: u64,
|
||||
}
|
||||
|
||||
impl Clock {
|
||||
pub(super) fn new(position: Samples, age: u64) -> Self {
|
||||
Self { position, age }
|
||||
}
|
||||
|
||||
pub(super) fn at(self, frame: usize) -> Samples {
|
||||
let frame = i128::try_from(frame).unwrap_or(i128::MAX);
|
||||
let at = i128::from(self.position).saturating_add(frame).saturating_sub(i128::from(self.age));
|
||||
at.clamp(i128::from(Samples::MIN), i128::from(Samples::MAX)) as Samples
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Samples> for Clock {
|
||||
fn from(position: Samples) -> Self {
|
||||
Self::new(position, 0)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn frame_position(pos: Samples, frame: usize) -> Samples {
|
||||
Clock::from(pos).at(frame)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn apply_mono_stereo(
|
||||
src: &[Vec<f32>],
|
||||
frames: usize,
|
||||
dst: &mut [Vec<f32>],
|
||||
gain: f32,
|
||||
law: PanLaw,
|
||||
pos: impl Into<Clock>,
|
||||
mut pan: Reader<'_>,
|
||||
mut mute: Option<Reader<'_>>,
|
||||
) {
|
||||
let clock = pos.into();
|
||||
let Some(src) = src.first() else { return };
|
||||
for (i, sample) in src.iter().enumerate().take(frames) {
|
||||
let at = clock.at(i);
|
||||
if mute.as_mut().is_some_and(|m| m.value(at) >= 0.5) {
|
||||
continue;
|
||||
}
|
||||
let (left, right) = gains(pan.value(at), law);
|
||||
for (channel, factor) in [(0, left), (1, right)] {
|
||||
if let Some(out) = dst.get_mut(channel).and_then(|c| c.get_mut(i)) {
|
||||
*out += sample * gain * factor;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the existing static routing matrix (including mono folds and surround positions),
|
||||
/// applying only the exact mute gate. Sparse taps are prepared on the stack once per block.
|
||||
pub(super) fn apply_gated(
|
||||
src: &[Vec<f32>],
|
||||
frames: usize,
|
||||
dst: &mut [Vec<f32>],
|
||||
matrix: &Matrix,
|
||||
gain: f32,
|
||||
pos: impl Into<Clock>,
|
||||
mut mute: Reader<'_>,
|
||||
) {
|
||||
let clock = pos.into();
|
||||
let mut taps = [[(0usize, 0.0f32); MAX_CHANNELS]; MAX_CHANNELS];
|
||||
let mut counts = [0usize; MAX_CHANNELS];
|
||||
for (d, (taps, count)) in taps.iter_mut().zip(counts.iter_mut()).enumerate().take(dst.len()) {
|
||||
for (s, row) in matrix.iter().enumerate().take(src.len().min(MAX_CHANNELS)) {
|
||||
let g = row.get(d).copied().unwrap_or(0.0);
|
||||
if g != 0.0
|
||||
&& let Some(tap) = taps.get_mut(*count)
|
||||
{
|
||||
*tap = (s, g);
|
||||
*count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
for i in 0..frames {
|
||||
if mute.value(clock.at(i)) >= 0.5 {
|
||||
continue;
|
||||
}
|
||||
for (d, channel) in dst.iter_mut().enumerate().take(MAX_CHANNELS) {
|
||||
let Some(out) = channel.get_mut(i) else { continue };
|
||||
let mut acc = 0.0;
|
||||
for &(s, g) in taps.get(d).and_then(|t| counts.get(d).and_then(|n| t.get(..*n))).unwrap_or(&[]) {
|
||||
acc += src.get(s).and_then(|c| c.get(i)).copied().unwrap_or(0.0) * gain * g;
|
||||
}
|
||||
*out += acc;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use soundcraft_model::{AutomationLane, ChannelFormat, Session, TrackKind};
|
||||
|
||||
fn track(points: &[(i64, f32)], mute: bool) -> Track {
|
||||
let mut s = Session::default();
|
||||
let id = s.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
|
||||
let t = s.track_mut(id).unwrap();
|
||||
let mut lane = AutomationLane::new(if mute { AutoParam::SendMute(0) } else { AutoParam::SendPan(0) });
|
||||
lane.points = points.iter().map(|&(at, value)| AutomationPoint { at, value }).collect();
|
||||
t.automation.push(lane);
|
||||
t.clone()
|
||||
}
|
||||
#[test]
|
||||
fn wide_interpolation_does_not_overflow() {
|
||||
let t = track(&[(i64::MIN, -1.0), (i64::MAX, 1.0)], false);
|
||||
let mut r = Reader::for_send(&t, AutoParam::SendPan, 0, i64::MIN).unwrap();
|
||||
assert_eq!(r.value(i64::MIN), -1.0);
|
||||
assert!(r.value(0).abs() < 1e-7);
|
||||
assert_eq!(r.value(i64::MAX), 1.0);
|
||||
assert_eq!(frame_position(i64::MAX - 1, 3), i64::MAX);
|
||||
}
|
||||
#[test]
|
||||
fn endpoints_duplicates_and_finite_extremes_are_deterministic() {
|
||||
let t = track(&[(3, -f32::MAX), (3, 0.25), (7, f32::MAX)], false);
|
||||
let mut r = Reader::for_send(&t, AutoParam::SendPan, 0, 0).unwrap();
|
||||
assert_eq!(r.value(0), -1.0);
|
||||
assert_eq!(r.value(3), 0.25);
|
||||
assert_eq!(r.value(5), 0.625);
|
||||
assert_eq!(r.value(9), 1.0);
|
||||
let t = track(&[(i64::MIN, -f32::MAX), (i64::MAX, f32::MAX)], true);
|
||||
let mut r = Reader::for_send(&t, AutoParam::SendMute, 0, i64::MIN).unwrap();
|
||||
assert_eq!(r.value(0), 0.0);
|
||||
assert_eq!(r.value(i64::MAX), 1.0);
|
||||
}
|
||||
#[test]
|
||||
fn short_buffers_and_saturating_positions_do_not_panic() {
|
||||
let t = track(&[(i64::MIN, 0.0), (i64::MAX, 1.0)], true);
|
||||
let r = Reader::for_send(&t, AutoParam::SendMute, 0, i64::MAX - 1).unwrap();
|
||||
let mut dst = vec![vec![0.0; 1]];
|
||||
let mut matrix = [[0.0; MAX_CHANNELS]; MAX_CHANNELS];
|
||||
matrix[0][0] = 1.0;
|
||||
apply_gated(&[vec![0.25; 2]], 4, &mut dst, &matrix, 1.0, i64::MAX - 1, r);
|
||||
assert_eq!(dst, vec![vec![0.25]]);
|
||||
let t = track(&[(i64::MIN, -1.0), (i64::MAX, 1.0)], false);
|
||||
let r = Reader::for_send(&t, AutoParam::SendPan, 0, i64::MAX - 1).unwrap();
|
||||
apply_mono_stereo(&[vec![0.25; 2]], 4, &mut [], 1.0, PanLaw::Minus3, i64::MAX - 1, r, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_clock_clamps_after_the_composite_delay_expression() {
|
||||
assert_eq!(Clock::new(i64::MIN + 5, 10).at(8), i64::MIN + 3);
|
||||
assert_eq!(Clock::new(i64::MAX, 10).at(3), i64::MAX - 7);
|
||||
assert_eq!(Clock::new(i64::MAX, 10).at(20), i64::MAX);
|
||||
assert_eq!(Clock::new(-5, 10).at(3), -12);
|
||||
assert_eq!(Clock::new(i64::MAX, u64::MAX).at(0), i64::MIN);
|
||||
assert_eq!(Clock::new(i64::MIN, u64::MAX).at(0), i64::MIN);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delayed_reader_seed_and_gate_advancement_use_the_same_clock() {
|
||||
let t = track(&[(0, 0.0), (30, 1.0), (40, 0.0)], true);
|
||||
let clock = Clock::new(45, 25);
|
||||
let reader = Reader::for_send(&t, AutoParam::SendMute, 0, clock.at(0)).unwrap();
|
||||
let mut matrix = [[0.0; MAX_CHANNELS]; MAX_CHANNELS];
|
||||
matrix[0][0] = 1.0;
|
||||
let mut destination = vec![vec![0.0; 25]];
|
||||
apply_gated(&[vec![0.25; 25]], 25, &mut destination, &matrix, 1.0, clock, reader);
|
||||
assert_eq!(destination[0], (0..25).map(|frame| if (10..20).contains(&frame) { 0.0 } else { 0.25 }).collect::<Vec<_>>());
|
||||
}
|
||||
}
|
||||
+33
-6
@@ -5,6 +5,7 @@ use super::live_midi::{LiveMidi, LiveNotes, MidiPorts, midi_thru};
|
||||
use super::midi::{chase_controllers, schedule_notes};
|
||||
use super::pan::{PanSpec, apply_matrix, build_matrix, identity_matrix};
|
||||
use super::routing::solo_muted;
|
||||
use super::send_automation::SignalAge;
|
||||
use super::{
|
||||
AutoParam, BusId, ChannelFormat, MAX_CHANNELS, PanLaw, Plugin, Range, Route, Samples, Session, SourceAudio, Track, TrackId, TrackKind, Transport,
|
||||
db_to_gain,
|
||||
@@ -16,6 +17,8 @@ use std::sync::Arc;
|
||||
pub(crate) struct BusBuf {
|
||||
pub(crate) fmt: ChannelFormat,
|
||||
pub(crate) buf: Vec<Vec<f32>>,
|
||||
/// Age shared by the routed contributions in this block, or Mixed when they differ.
|
||||
pub(crate) age: SignalAge,
|
||||
}
|
||||
|
||||
pub(crate) struct PluginSlot {
|
||||
@@ -35,6 +38,13 @@ pub(crate) struct PluginSlot {
|
||||
pub(crate) retried: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl PluginSlot {
|
||||
pub(crate) fn test_instance(id: String, ch: usize, plugin: Box<dyn Plugin>) -> Self {
|
||||
Self { id, ch, plugin, applied: Vec::new(), lanes: Vec::new(), failed: false, retried: false }
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Strip {
|
||||
pub(crate) buf: Vec<Vec<f32>>,
|
||||
/// Pre-fader copy for pre-fader sends.
|
||||
@@ -59,6 +69,9 @@ pub(crate) struct Strip {
|
||||
clipbuf: Vec<Vec<f32>>,
|
||||
/// Total latency of the active inserts (samples).
|
||||
pub(crate) latency: usize,
|
||||
/// Sample ages of the selected send taps after their actual applied alignment.
|
||||
pub(crate) send_pre_age: SignalAge,
|
||||
pub(crate) send_post_age: SignalAge,
|
||||
/// Delay compensation: align this strip with the slowest one (post- and pre-fader paths),
|
||||
/// plus extra delay for direct-to-main outputs so they line up with aux returns.
|
||||
pub(crate) align: DelayLine,
|
||||
@@ -157,6 +170,8 @@ impl Strip {
|
||||
clip_fx: HashMap::new(),
|
||||
clipbuf: Vec::new(),
|
||||
latency: 0,
|
||||
send_pre_age: SignalAge::Known(0),
|
||||
send_post_age: SignalAge::Known(0),
|
||||
align: DelayLine::default(),
|
||||
align_pre: DelayLine::default(),
|
||||
out_extra: DelayLine::default(),
|
||||
@@ -289,10 +304,11 @@ fn render_audio_clips(s: &Session, t: &Track, strip: &mut Strip, blk: Block) {
|
||||
}
|
||||
|
||||
/// An aux or folder reads the bus its input is routed from.
|
||||
fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, frames: usize) {
|
||||
fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, frames: usize) -> SignalAge {
|
||||
if let Route::Bus(b) = &t.mixer.input
|
||||
&& let Some(src) = busses.get(b)
|
||||
{
|
||||
let input_age = src.age.input();
|
||||
let (ns, nd) = (src.buf.len(), strip.buf.len());
|
||||
let dst_fmt = strip_format(t, nd);
|
||||
let m = if src.fmt == dst_fmt && ns == nd {
|
||||
@@ -308,7 +324,9 @@ fn read_aux_bus(t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, f
|
||||
build_matrix(src.fmt, ns, dst_fmt, nd, &PanSpec { stereo, surround: None }, PanLaw::Minus3)
|
||||
};
|
||||
apply_matrix(&src.buf, frames, &mut strip.buf, &m, 1.0);
|
||||
return input_age;
|
||||
}
|
||||
SignalAge::Known(0)
|
||||
}
|
||||
|
||||
/// Render the track's instrument into the strip.
|
||||
@@ -393,10 +411,12 @@ fn render_instrument(s: &Session, t: &Track, strip: &mut Strip, live: &LiveInput
|
||||
}
|
||||
|
||||
/// Run the active inserts in order; records their latency and the first gain reduction.
|
||||
fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport) {
|
||||
fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport, input_age: SignalAge) {
|
||||
let Block { pos, frames, .. } = blk;
|
||||
let mut gr = 0.0f32;
|
||||
let mut latency = strip.instrument.as_ref().filter(|i| !i.failed).map_or(0, |i| i.plugin.latency());
|
||||
let inst_latency = strip.instrument.as_ref().filter(|i| !i.failed).map_or(0, |i| i.plugin.latency());
|
||||
let mut latency = inst_latency;
|
||||
let mut send_age = input_age.delayed(inst_latency);
|
||||
for (i, ins) in t.mixer.inserts.iter().enumerate() {
|
||||
let (Some(ins), Some(Some(slot))) = (ins, strip.plugins.get_mut(i)) else { continue };
|
||||
if !ins.active || ins.bypass || slot.failed {
|
||||
@@ -409,13 +429,17 @@ fn run_inserts(t: &Track, strip: &mut Strip, blk: Block, transport: &Transport)
|
||||
strip.failures.record(i);
|
||||
continue;
|
||||
}
|
||||
latency = latency.saturating_add(slot.plugin.latency());
|
||||
let declared_latency = slot.plugin.latency();
|
||||
latency = latency.saturating_add(declared_latency);
|
||||
send_age = send_age.delayed(declared_latency);
|
||||
if gr == 0.0 {
|
||||
gr = slot.plugin.gain_reduction_db();
|
||||
}
|
||||
}
|
||||
strip.gr = gr;
|
||||
strip.latency = latency.min(MAX_LATENCY);
|
||||
strip.send_pre_age = send_age;
|
||||
strip.send_post_age = send_age;
|
||||
}
|
||||
|
||||
/// Fader gain (volume, trim and VCA automation), read at every sample of the block.
|
||||
@@ -466,6 +490,7 @@ fn gate_mute_automation(t: &Track, strip: &mut Strip, blk: Block) {
|
||||
pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &HashMap<BusId, BusBuf>, live: &LiveInput<'_>, blk: Block) {
|
||||
let Block { pos, frames, any_solo } = blk;
|
||||
zero_buf(&mut strip.buf, frames);
|
||||
let mut input_age = SignalAge::Known(0);
|
||||
let transport = transport_at(s, pos, !live.monitor_only, live.recording);
|
||||
match t.kind {
|
||||
TrackKind::Audio if !live.input.is_empty() && (t.mixer.input_monitor || (t.mixer.record_arm && (live.monitor_only || live.recording))) => {
|
||||
@@ -476,7 +501,9 @@ pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &
|
||||
// doing so, to release its notes).
|
||||
TrackKind::Instrument | TrackKind::Midi if live.monitor_only && !midi_thru(t) && !strip.live.touched() => {}
|
||||
TrackKind::Audio => render_audio_clips(s, t, strip, blk),
|
||||
TrackKind::Aux | TrackKind::Folder => read_aux_bus(t, strip, busses, frames),
|
||||
TrackKind::Aux | TrackKind::Folder => {
|
||||
input_age = read_aux_bus(t, strip, busses, frames);
|
||||
}
|
||||
TrackKind::Instrument | TrackKind::Midi => render_instrument(s, t, strip, live, blk, &transport),
|
||||
_ => {}
|
||||
}
|
||||
@@ -486,7 +513,7 @@ pub(crate) fn process_strip(s: &Session, t: &Track, strip: &mut Strip, busses: &
|
||||
c.iter_mut().take(frames).for_each(|x| *x *= trim);
|
||||
}
|
||||
}
|
||||
run_inserts(t, strip, blk, &transport);
|
||||
run_inserts(t, strip, blk, &transport, input_age);
|
||||
let soloed_out = solo_muted(s, t, any_solo);
|
||||
strip.muted = t.mixer.mute || soloed_out;
|
||||
if t.mixer.sends.iter().flatten().any(|x| x.pre_fader) {
|
||||
|
||||
@@ -0,0 +1,435 @@
|
||||
//! Independent PCM references for the bounded send consumers, with no hosted plugins/devices.
|
||||
use craft_audio::AudioBuffer;
|
||||
use soundcraft_dsp::pan::PanLaw;
|
||||
use soundcraft_mix::{MixEngine, render_bus, render_range};
|
||||
use soundcraft_model::{
|
||||
AutoParam, AutomationLane, AutomationMode, AutomationPoint, BusId, ChannelFormat, Clip, Route, SendSlot, Session, SourceAudio, SourceId, TrackId,
|
||||
TrackKind,
|
||||
};
|
||||
use soundcraft_time::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
const LEN: usize = 640;
|
||||
const PAN: [(i64, f32); 3] = [(37, -1.0), (173, 0.75), (401, 1.0)];
|
||||
const MUTE: [(i64, f32); 5] = [(37, 0.0), (97, 1.0), (173, 0.0), (257, 1.0), (349, 0.0)];
|
||||
|
||||
fn fixture(format: ChannelFormat) -> (Session, TrackId, BusId) {
|
||||
let mut s = Session::default();
|
||||
let t = s.add_track(TrackKind::Audio, format, None);
|
||||
let src = SourceId(900);
|
||||
let channels = (0..format.channels()).map(|ch| (0..LEN).map(|n| signal(ch, n)).collect()).collect();
|
||||
s.pool.insert(src, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels })));
|
||||
let cid = s.new_clip_id();
|
||||
s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "Original synthetic", src, 0, 0, LEN as i64));
|
||||
let bus = s.add_bus("Send", ChannelFormat::Stereo);
|
||||
let aux = s.add_track(TrackKind::Aux, ChannelFormat::Stereo, None);
|
||||
s.track_mut(aux).unwrap().mixer.input = Route::Bus(bus);
|
||||
let tr = s.track_mut(t).unwrap();
|
||||
tr.mixer.output = Route::None;
|
||||
let mut send = SendSlot::new(Route::Bus(bus));
|
||||
send.level_db = 0.0;
|
||||
tr.mixer.sends[0] = Some(send);
|
||||
(s, t, bus)
|
||||
}
|
||||
fn signal(ch: usize, n: usize) -> f32 {
|
||||
if n % 17 < 9 { 0.25 + ch as f32 / 100.0 } else { -0.125 - ch as f32 / 200.0 }
|
||||
}
|
||||
fn lane(s: &mut Session, t: TrackId, param: AutoParam, points: &[(i64, f32)]) {
|
||||
let mut lane = AutomationLane::new(param);
|
||||
for &(at, value) in points {
|
||||
lane.set_point(at, value);
|
||||
}
|
||||
s.track_mut(t).unwrap().automation.push(lane);
|
||||
}
|
||||
fn automated() -> (Session, TrackId, BusId) {
|
||||
let (mut s, t, bus) = fixture(ChannelFormat::Mono);
|
||||
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
|
||||
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
|
||||
(s, t, bus)
|
||||
}
|
||||
// The expectation never calls AutomationLane::value_at, pan::gains or any mixer helper.
|
||||
fn expected_pan(at: i64) -> f64 {
|
||||
if at <= PAN[0].0 {
|
||||
return f64::from(PAN[0].1);
|
||||
}
|
||||
for pair in PAN.windows(2) {
|
||||
if at < pair[1].0 {
|
||||
let f = (at - pair[0].0) as f64 / (pair[1].0 - pair[0].0) as f64;
|
||||
return f64::from(pair[0].1) + f64::from(pair[1].1 - pair[0].1) * f;
|
||||
}
|
||||
}
|
||||
f64::from(PAN[2].1)
|
||||
}
|
||||
fn muted(at: i64) -> bool {
|
||||
MUTE.iter().rev().find(|p| p.0 <= at).unwrap_or(&MUTE[0]).1 >= 0.5
|
||||
}
|
||||
fn pan_factors(p: f64, law: PanLaw) -> [f64; 2] {
|
||||
if law == PanLaw::Zero {
|
||||
return [(1.0 - p).min(1.0), (1.0 + p).min(1.0)];
|
||||
}
|
||||
let depth = match law {
|
||||
PanLaw::Minus3 => -3.0,
|
||||
PanLaw::Minus4_5 => -4.5,
|
||||
PanLaw::Minus6 => -6.0,
|
||||
PanLaw::Zero => 0.0,
|
||||
};
|
||||
let angle = (p + 1.0) * std::f64::consts::PI / 4.0;
|
||||
[angle.cos().max(0.0).powf(depth / -3.0103), angle.sin().max(0.0).powf(depth / -3.0103)]
|
||||
}
|
||||
fn assert_shape(out: &[Vec<f32>], channels: usize, frames: usize) {
|
||||
assert_eq!(out.len(), channels);
|
||||
for channel in out {
|
||||
assert_eq!(channel.len(), frames);
|
||||
}
|
||||
}
|
||||
fn check(out: &[Vec<f32>], start: i64, frames: usize, law: PanLaw, scale: f64) {
|
||||
assert_shape(out, 2, frames);
|
||||
for (ch, values) in out.iter().enumerate() {
|
||||
for (n, &actual) in values.iter().enumerate() {
|
||||
let at = start + n as i64;
|
||||
let reference = if muted(at) { 0.0 } else { f64::from(signal(0, at as usize)) * scale * pan_factors(expected_pan(at), law)[ch] };
|
||||
assert!((f64::from(actual) - reference).abs() < 2e-7, "channel {ch}, at {at}: {actual} vs {reference}");
|
||||
}
|
||||
}
|
||||
}
|
||||
fn chunks(eng: &mut MixEngine, s: &Session, start: i64, length: usize, sizes: &[usize]) -> Vec<Vec<f32>> {
|
||||
let mut out = vec![Vec::new(), Vec::new()];
|
||||
let mut offset = 0;
|
||||
let mut k = 0;
|
||||
while offset < length {
|
||||
let n = sizes[k % sizes.len()].min(length - offset);
|
||||
let mut block = vec![vec![0.0; n]; 2];
|
||||
eng.render(s, start + offset as i64, n, &mut block);
|
||||
for (out, block) in out.iter_mut().zip(block) {
|
||||
out.extend(block);
|
||||
}
|
||||
offset += n;
|
||||
k += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pan_and_mute_match_independent_pcm_across_chunks() {
|
||||
let (s, _, bus) = automated();
|
||||
for block in [1, 37, 64, 100, 512, 1024] {
|
||||
let mut e = MixEngine::new(48_000.0, block.max(16));
|
||||
let out = chunks(&mut e, &s, 0, LEN, &[block]);
|
||||
check(&out, 0, LEN, PanLaw::Minus3, 1.0);
|
||||
}
|
||||
let mut e = MixEngine::new(48_000.0, 1024);
|
||||
check(&chunks(&mut e, &s, 0, LEN, &[1, 37, 64, 3, 100, 19]), 0, LEN, PanLaw::Minus3, 1.0);
|
||||
check(&render_bus(&s, bus, Range::new(0, LEN as i64), 37), 0, LEN, PanLaw::Minus3, 1.0);
|
||||
}
|
||||
#[test]
|
||||
fn all_pan_laws_match_numeric_reference_and_static_calibration() {
|
||||
let (s, _, _) = automated();
|
||||
for law in [PanLaw::Minus3, PanLaw::Minus4_5, PanLaw::Minus6, PanLaw::Zero] {
|
||||
let mut e = MixEngine::new(48_000.0, 1024);
|
||||
e.pan_law = law;
|
||||
check(&chunks(&mut e, &s, 0, LEN, &[100]), 0, LEN, law, 1.0);
|
||||
for at in [0, 77, 173, 349, 401] {
|
||||
let (mut reference, t, _) = fixture(ChannelFormat::Mono);
|
||||
reference.track_mut(t).unwrap().mixer.sends[0].as_mut().unwrap().pan = expected_pan(at) as f32;
|
||||
let mut static_engine = MixEngine::new(48_000.0, 16);
|
||||
static_engine.pan_law = law;
|
||||
let static_pcm = chunks(&mut static_engine, &reference, at, 1, &[1]);
|
||||
let automated_pcm = chunks(&mut e, &s, at, 1, &[1]);
|
||||
assert_shape(&automated_pcm, 2, 1);
|
||||
assert_shape(&static_pcm, 2, 1);
|
||||
assert_eq!(automated_pcm, static_pcm);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn seeking_used_engine_has_no_cursor_history() {
|
||||
let (s, _, _) = automated();
|
||||
let mut e = MixEngine::new(48_000.0, 1024);
|
||||
let _ = chunks(&mut e, &s, 0, 520, &[100]);
|
||||
for at in [31, 77, 97, 98, 173, 256, 257, 301] {
|
||||
let out = chunks(&mut e, &s, at, 31, &[17, 1, 13]);
|
||||
check(&out, at, 31, PanLaw::Minus3, 1.0);
|
||||
let mut fresh = MixEngine::new(48_000.0, 1024);
|
||||
assert_eq!(out, chunks(&mut fresh, &s, at, 31, &[17, 1, 13]));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn loop_wrap_and_tiny_final_chunks_use_absolute_knots() {
|
||||
let (s, _, _) = automated();
|
||||
let mut e = MixEngine::new(48_000.0, 1024);
|
||||
// Same loop splitting as playback: do not render past the loop end before wrapping.
|
||||
for _ in 0..3 {
|
||||
check(&chunks(&mut e, &s, 37, 264, &[100, 63]), 37, 264, PanLaw::Minus3, 1.0);
|
||||
}
|
||||
for _ in 0..2 {
|
||||
check(&chunks(&mut e, &s, 97, 76, &[37]), 97, 76, PanLaw::Minus3, 1.0);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn modes_and_lane_enabled_preserve_existing_reader_policy() {
|
||||
for mode in AutomationMode::ALL {
|
||||
let (mut s, t, _) = automated();
|
||||
let tr = s.track_mut(t).unwrap();
|
||||
tr.mixer.automation_mode = mode;
|
||||
tr.mixer.sends[0].as_mut().unwrap().mute = true;
|
||||
for lane in &mut tr.automation {
|
||||
lane.enabled = false;
|
||||
}
|
||||
let out = render_range(&s, Range::new(0, LEN as i64), 37);
|
||||
assert_shape(&out, 2, LEN);
|
||||
if mode == AutomationMode::Off {
|
||||
assert!(out.iter().flatten().all(|v| *v == 0.0));
|
||||
} else {
|
||||
check(&out, 0, LEN, PanLaw::Minus3, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn missing_and_empty_lanes_keep_static_pan_and_mute() {
|
||||
let (mut s, t, _) = fixture(ChannelFormat::Mono);
|
||||
let reference = render_range(&s, Range::new(0, LEN as i64), 100);
|
||||
lane(&mut s, t, AutoParam::SendPan(0), &[]);
|
||||
lane(&mut s, t, AutoParam::SendMute(0), &[]);
|
||||
assert_eq!(render_range(&s, Range::new(0, LEN as i64), 100), reference);
|
||||
s.track_mut(t).unwrap().mixer.sends[0].as_mut().unwrap().mute = true;
|
||||
assert!(render_range(&s, Range::new(0, LEN as i64), 100).iter().flatten().all(|v| *v == 0.0));
|
||||
}
|
||||
#[test]
|
||||
fn static_matrix_mute_steps_and_threshold_match_reference() {
|
||||
let (mut s, t, bus) = fixture(ChannelFormat::Stereo);
|
||||
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 100);
|
||||
lane(&mut s, t, AutoParam::SendMute(0), &[(0, 0.49), (97, 0.5), (173, 0.0)]);
|
||||
let out = render_bus(&s, bus, Range::new(0, LEN as i64), 100);
|
||||
assert_shape(&out, 2, LEN);
|
||||
assert_shape(&reference, 2, LEN);
|
||||
assert_eq!(out.len(), reference.len());
|
||||
for (actual, reference) in out.iter().zip(reference) {
|
||||
assert_eq!(actual.len(), reference.len());
|
||||
for (i, (&a, r)) in actual.iter().zip(reference).enumerate() {
|
||||
assert_eq!(a, if (97..173).contains(&i) { 0.0 } else { r });
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn mute_preserves_routing_for_mono_surround_and_sixteen_channels() {
|
||||
for fmt in [ChannelFormat::Mono, ChannelFormat::Stereo, ChannelFormat::Surround51, ChannelFormat::Atmos714, ChannelFormat::Atmos916] {
|
||||
let (mut s, t, bus) = fixture(fmt);
|
||||
s.busses.iter_mut().find(|b| b.id == bus).unwrap().format = fmt;
|
||||
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
|
||||
assert!(reference.iter().flatten().any(|v| v.abs() > 0.05));
|
||||
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
|
||||
let out = render_bus(&s, bus, Range::new(0, LEN as i64), 100);
|
||||
assert_shape(&out, fmt.channels(), LEN);
|
||||
assert_shape(&reference, fmt.channels(), LEN);
|
||||
assert_eq!(out.len(), reference.len());
|
||||
for (actual, reference) in out.iter().zip(reference) {
|
||||
assert_eq!(actual.len(), reference.len());
|
||||
for (i, (&a, r)) in actual.iter().zip(reference).enumerate() {
|
||||
assert_eq!(a, if muted(i as i64) { 0.0 } else { r });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn wider_source_and_destination_send_pan_keep_static_routing() {
|
||||
for (src_fmt, dst_fmt) in [
|
||||
(ChannelFormat::Stereo, ChannelFormat::Stereo),
|
||||
(ChannelFormat::Mono, ChannelFormat::Surround51),
|
||||
(ChannelFormat::Surround51, ChannelFormat::Stereo),
|
||||
] {
|
||||
let (mut s, t, bus) = fixture(src_fmt);
|
||||
s.busses.iter_mut().find(|b| b.id == bus).unwrap().format = dst_fmt;
|
||||
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
|
||||
assert!(reference.iter().flatten().any(|v| v.abs() > 0.05));
|
||||
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
|
||||
assert_shape(&reference, dst_fmt.channels(), LEN);
|
||||
let actual = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
|
||||
assert_shape(&actual, dst_fmt.channels(), LEN);
|
||||
assert_eq!(actual, reference);
|
||||
assert_eq!(render_bus(&s, bus, Range::new(0, LEN as i64), 37), reference);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn pre_post_fader_send_level_and_direct_output_are_preserved() {
|
||||
for pre in [false, true] {
|
||||
let (mut s, t, bus) = automated();
|
||||
let tr = s.track_mut(t).unwrap();
|
||||
tr.mixer.volume_db = -6.0;
|
||||
let snd = tr.mixer.sends[0].as_mut().unwrap();
|
||||
snd.pre_fader = pre;
|
||||
snd.level_db = -3.0;
|
||||
let factor = 10.0f64.powf((-3.0 + if pre { 0.0 } else { -6.0 }) / 20.0);
|
||||
check(&render_range(&s, Range::new(0, LEN as i64), 37), 0, LEN, PanLaw::Minus3, factor);
|
||||
// Keep the direct path isolated from the Aux while comparing source-main PCM.
|
||||
let aux = s.tracks.iter().find(|tr| tr.kind == TrackKind::Aux).unwrap().id;
|
||||
s.track_mut(aux).unwrap().inactive = true;
|
||||
s.track_mut(t).unwrap().mixer.output = Route::Main;
|
||||
let direct = render_range(&s, Range::new(0, LEN as i64), 37);
|
||||
s.track_mut(t).unwrap().automation.clear();
|
||||
s.track_mut(t).unwrap().mixer.sends[0] = None;
|
||||
assert_eq!(render_range(&s, Range::new(0, LEN as i64), 37), direct);
|
||||
assert_eq!(s.bus(bus).unwrap().format, ChannelFormat::Stereo);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn track_solo_and_vca_suppression_cannot_be_unmuted_by_send_lane() {
|
||||
for suppression in [0, 1, 2] {
|
||||
let (mut s, t, _) = automated();
|
||||
s.track_mut(t).unwrap().mixer.sends[0].as_mut().unwrap().pre_fader = true;
|
||||
match suppression {
|
||||
0 => s.track_mut(t).unwrap().mixer.mute = true,
|
||||
1 => {
|
||||
let other = s.add_track(TrackKind::Audio, ChannelFormat::Mono, None);
|
||||
s.track_mut(other).unwrap().mixer.solo = true;
|
||||
}
|
||||
_ => {
|
||||
let vca = s.add_track(TrackKind::Vca, ChannelFormat::Mono, None);
|
||||
s.track_mut(vca).unwrap().mixer.mute = true;
|
||||
s.track_mut(t).unwrap().mixer.vca = Some(vca.0);
|
||||
}
|
||||
}
|
||||
assert!(render_range(&s, Range::new(0, LEN as i64), 100).iter().flatten().all(|v| *v == 0.0));
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn slots_a_and_j_and_absent_slots_do_not_drive_each_other() {
|
||||
let (mut s, t, bus) = fixture(ChannelFormat::Mono);
|
||||
let other = s.add_bus("J", ChannelFormat::Stereo);
|
||||
let mut send = SendSlot::new(Route::Bus(other));
|
||||
send.level_db = 0.0;
|
||||
s.track_mut(t).unwrap().mixer.sends[9] = Some(send);
|
||||
let reference = render_bus(&s, bus, Range::new(0, LEN as i64), 37);
|
||||
assert!(reference.iter().flatten().any(|v| v.abs() > 0.05));
|
||||
lane(&mut s, t, AutoParam::SendPan(9), &PAN);
|
||||
lane(&mut s, t, AutoParam::SendMute(9), &MUTE);
|
||||
lane(&mut s, t, AutoParam::SendMute(8), &[(0, 1.0)]);
|
||||
assert_eq!(render_bus(&s, bus, Range::new(0, LEN as i64), 37), reference);
|
||||
check(&render_bus(&s, other, Range::new(0, LEN as i64), 100), 0, LEN, PanLaw::Minus3, 1.0);
|
||||
}
|
||||
#[test]
|
||||
fn malformed_lanes_fall_back_without_changing_document() {
|
||||
for points in [
|
||||
vec![AutomationPoint { at: 3, value: -1.0 }, AutomationPoint { at: 1, value: 1.0 }],
|
||||
vec![AutomationPoint { at: 0, value: f32::NAN }],
|
||||
vec![AutomationPoint { at: 0, value: f32::INFINITY }],
|
||||
] {
|
||||
let (mut s, t, _) = fixture(ChannelFormat::Mono);
|
||||
let reference = render_range(&s, Range::new(0, LEN as i64), 100);
|
||||
for param in [AutoParam::SendPan(0), AutoParam::SendMute(0)] {
|
||||
let mut lane = AutomationLane::new(param);
|
||||
lane.points = points.clone();
|
||||
s.track_mut(t).unwrap().automation.push(lane);
|
||||
}
|
||||
let before: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
|
||||
assert_eq!(render_range(&s, Range::new(0, LEN as i64), 100), reference);
|
||||
let after: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
|
||||
assert_eq!(before, after);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stereo_sends_keep_legacy_left_right_routing_for_every_static_pan() {
|
||||
for static_pan in [-1.0, -0.75, 0.0, 0.75, 1.0, f32::NAN, f32::INFINITY] {
|
||||
for state in ["absent", "empty", "off", "malformed", "active"] {
|
||||
for pre in [false, true] {
|
||||
for gated in [false, true] {
|
||||
let (mut s, t, bus) = fixture(ChannelFormat::Stereo);
|
||||
let tr = s.track_mut(t).unwrap();
|
||||
tr.mixer.volume_db = -6.0;
|
||||
let send = tr.mixer.sends[0].as_mut().unwrap();
|
||||
send.pan = static_pan;
|
||||
send.pre_fader = pre;
|
||||
send.level_db = -3.0;
|
||||
match state {
|
||||
"absent" => {}
|
||||
"empty" => lane(&mut s, t, AutoParam::SendPan(0), &[]),
|
||||
"off" => {
|
||||
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
|
||||
s.track_mut(t).unwrap().mixer.automation_mode = AutomationMode::Off;
|
||||
}
|
||||
"malformed" => {
|
||||
let mut pan = AutomationLane::new(AutoParam::SendPan(0));
|
||||
pan.points = vec![AutomationPoint { at: 173, value: 1.0 }, AutomationPoint { at: 37, value: -1.0 }];
|
||||
s.track_mut(t).unwrap().automation.push(pan);
|
||||
}
|
||||
"active" => lane(&mut s, t, AutoParam::SendPan(0), &PAN),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
if gated {
|
||||
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
|
||||
}
|
||||
let scale = 10.0f64.powf((-3.0 + if pre { 0.0 } else { -6.0 }) / 20.0);
|
||||
for block in [1, 37, 100] {
|
||||
let out = render_bus(&s, bus, Range::new(0, LEN as i64), block);
|
||||
assert_shape(&out, 2, LEN);
|
||||
for (ch, channel) in out.iter().enumerate() {
|
||||
for (n, &actual) in channel.iter().enumerate() {
|
||||
// Existing stereo sends route channels directly to L/R. This reference
|
||||
// does not call either routing matrices or a pan helper.
|
||||
let expected = if gated && state != "off" && muted(n as i64) { 0.0 } else { f64::from(signal(ch, n)) * scale };
|
||||
assert!(
|
||||
(f64::from(actual) - expected).abs() < 2e-7,
|
||||
"{state} pre={pre} gated={gated} ch={ch} at={n}: {actual} != {expected}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(s.track(t).unwrap().mixer.sends[0].as_ref().unwrap().pan.to_bits(), static_pan.to_bits());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inactive_mono_send_lanes_match_independent_static_controls() {
|
||||
for state in ["absent", "empty", "off", "unordered", "nan", "infinite"] {
|
||||
for pre in [false, true] {
|
||||
for static_mute in [false, true] {
|
||||
let (mut s, t, bus) = fixture(ChannelFormat::Mono);
|
||||
let tr = s.track_mut(t).unwrap();
|
||||
tr.mixer.volume_db = -6.0;
|
||||
let send = tr.mixer.sends[0].as_mut().unwrap();
|
||||
send.pan = -0.625;
|
||||
send.mute = static_mute;
|
||||
send.pre_fader = pre;
|
||||
send.level_db = -3.0;
|
||||
if state == "off" {
|
||||
lane(&mut s, t, AutoParam::SendPan(0), &PAN);
|
||||
lane(&mut s, t, AutoParam::SendMute(0), &MUTE);
|
||||
s.track_mut(t).unwrap().mixer.automation_mode = AutomationMode::Off;
|
||||
} else if state != "absent" {
|
||||
for param in [AutoParam::SendPan(0), AutoParam::SendMute(0)] {
|
||||
let mut control = AutomationLane::new(param);
|
||||
control.points = match state {
|
||||
"empty" => vec![],
|
||||
"unordered" => vec![AutomationPoint { at: 173, value: 1.0 }, AutomationPoint { at: 37, value: 0.0 }],
|
||||
"nan" => vec![AutomationPoint { at: 0, value: f32::NAN }],
|
||||
"infinite" => vec![AutomationPoint { at: 0, value: f32::INFINITY }],
|
||||
_ => unreachable!(),
|
||||
};
|
||||
s.track_mut(t).unwrap().automation.push(control);
|
||||
}
|
||||
}
|
||||
let before: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
|
||||
let scale = 10.0f64.powf((-3.0 + if pre { 0.0 } else { -6.0 }) / 20.0);
|
||||
let factors = pan_factors(-0.625, PanLaw::Minus3);
|
||||
for block in [1, 37, 100] {
|
||||
let out = render_bus(&s, bus, Range::new(0, LEN as i64), block);
|
||||
assert_shape(&out, 2, LEN);
|
||||
for (ch, channel) in out.iter().enumerate() {
|
||||
for (n, &actual) in channel.iter().enumerate() {
|
||||
let expected = if static_mute { 0.0 } else { f64::from(signal(0, n)) * scale * factors[ch] };
|
||||
assert!(
|
||||
(f64::from(actual) - expected).abs() < 2e-7,
|
||||
"{state} pre={pre} muted={static_mute} ch={ch} at={n}: {actual} != {expected}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let after: Vec<_> = s.track(t).unwrap().automation.iter().flat_map(|l| l.points.iter().map(|p| (p.at, p.value.to_bits()))).collect();
|
||||
assert_eq!(before, after);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
//! Send automation follows the delayed audio at its tap, without changing existing PDC routing.
|
||||
|
||||
use craft_audio::AudioBuffer;
|
||||
use soundcraft_dsp::pan::PanLaw;
|
||||
use soundcraft_mix::{MixEngine, render_bus};
|
||||
use soundcraft_model::{
|
||||
AutoParam, AutomationLane, BusId, ChannelFormat, Clip, Insert, Route, SendSlot, Session, SourceAudio, SourceId, TrackId, TrackKind,
|
||||
};
|
||||
use soundcraft_time::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
// The built-in Maximizer uses 1.5 ms of lookahead: 72 samples at 48 kHz, with a declared
|
||||
// and physical delay of 72 - 1 = 71. Its untouched threshold 0 dB gives unity drive;
|
||||
// every synthetic level stays below the default -0.3 dB ceiling, so there is no limiting.
|
||||
// Expected timelines use these declared values, not mixer latency fields or the clock helper.
|
||||
const LOOKAHEAD: usize = 71;
|
||||
const SOURCE_FRAMES: usize = 2048;
|
||||
const MUTE_AT: i64 = 300;
|
||||
const AMPLITUDE: f32 = 0.25;
|
||||
|
||||
struct Graph {
|
||||
session: Session,
|
||||
capture: BusId,
|
||||
receiver: TrackId,
|
||||
clip_start: i64,
|
||||
pan_start: i64,
|
||||
pan_end: i64,
|
||||
}
|
||||
|
||||
fn maximizers(session: &mut Session, track: TrackId, count: usize) {
|
||||
for slot in session.track_mut(track).unwrap().mixer.inserts.iter_mut().take(count) {
|
||||
*slot = Some(Insert::new("maximizer"));
|
||||
}
|
||||
}
|
||||
|
||||
fn source(session: &mut Session, insert_count: usize, clip_start: i64) -> TrackId {
|
||||
let track = session.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Declared DC"));
|
||||
let id = SourceId(901);
|
||||
session.pool.insert(id, Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![vec![AMPLITUDE; SOURCE_FRAMES]] })));
|
||||
let clip = session.new_clip_id();
|
||||
let t = session.track_mut(track).unwrap();
|
||||
t.playlist_mut().unwrap().clips.push(Clip::audio(clip, "Declared DC", id, 0, clip_start, SOURCE_FRAMES as i64));
|
||||
t.mixer.pan = vec![0.0];
|
||||
t.mixer.output = Route::None;
|
||||
maximizers(session, track, insert_count);
|
||||
track
|
||||
}
|
||||
|
||||
fn silent_audio(session: &mut Session, insert_count: usize) {
|
||||
let track = session.add_track(TrackKind::Audio, ChannelFormat::Mono, Some("Unrelated silent lookahead"));
|
||||
session.track_mut(track).unwrap().mixer.output = Route::None;
|
||||
maximizers(session, track, insert_count);
|
||||
}
|
||||
|
||||
fn aux(session: &mut Session, input: BusId, format: ChannelFormat, insert_count: usize) -> TrackId {
|
||||
let track = session.add_track(TrackKind::Aux, format, None);
|
||||
let t = session.track_mut(track).unwrap();
|
||||
t.mixer.input = Route::Bus(input);
|
||||
t.mixer.output = Route::None;
|
||||
t.mixer.pan = if format == ChannelFormat::Mono { vec![0.0] } else { vec![-1.0, 1.0] };
|
||||
maximizers(session, track, insert_count);
|
||||
track
|
||||
}
|
||||
|
||||
fn silent_aux(session: &mut Session, insert_count: usize) {
|
||||
let input = session.add_bus("Unrelated empty input", ChannelFormat::Mono);
|
||||
aux(session, input, ChannelFormat::Mono, insert_count);
|
||||
}
|
||||
|
||||
fn return_to_main(session: &mut Session, input: BusId) -> TrackId {
|
||||
let track = aux(session, input, ChannelFormat::Stereo, 0);
|
||||
session.track_mut(track).unwrap().mixer.output = Route::Main;
|
||||
track
|
||||
}
|
||||
|
||||
fn automation(session: &mut Session, track: TrackId, param: AutoParam, points: &[(i64, f32)]) {
|
||||
let mut lane = AutomationLane::new(param);
|
||||
for &(at, value) in points {
|
||||
lane.set_point(at, value);
|
||||
}
|
||||
session.track_mut(track).unwrap().automation.push(lane);
|
||||
}
|
||||
|
||||
fn send(session: &mut Session, sender: TrackId, capture: BusId, pre: bool, pan_start: i64, pan_end: i64, automated_pan: bool) {
|
||||
let mut send = SendSlot::new(Route::Bus(capture));
|
||||
send.level_db = 0.0;
|
||||
send.pre_fader = pre;
|
||||
send.pan = -1.0;
|
||||
session.track_mut(sender).unwrap().mixer.sends[0] = Some(send);
|
||||
automation(session, sender, AutoParam::SendMute(0), &[(-512, 0.0), (MUTE_AT, 1.0)]);
|
||||
if automated_pan {
|
||||
automation(session, sender, AutoParam::SendPan(0), &[(pan_start, -1.0), (pan_end, 1.0)]);
|
||||
}
|
||||
}
|
||||
|
||||
fn ordinary(pre: bool, own_inserts: usize, silent_inserts: usize, pdc: bool, clip_start: i64, pan_start: i64, pan_end: i64) -> Graph {
|
||||
let mut session = Session::default();
|
||||
session.edit.delay_compensation = pdc;
|
||||
let sender = source(&mut session, own_inserts, clip_start);
|
||||
if silent_inserts > 0 {
|
||||
silent_audio(&mut session, silent_inserts);
|
||||
}
|
||||
let capture = session.add_bus("Automation capture", ChannelFormat::Stereo);
|
||||
send(&mut session, sender, capture, pre, pan_start, pan_end, true);
|
||||
let receiver = return_to_main(&mut session, capture);
|
||||
Graph { session, capture, receiver, clip_start, pan_start, pan_end }
|
||||
}
|
||||
|
||||
fn make_mix() -> MixEngine {
|
||||
let mut mix = MixEngine::new(48_000.0, 1024);
|
||||
mix.pan_law = PanLaw::Zero;
|
||||
mix
|
||||
}
|
||||
|
||||
fn capture_pcm(mix: &mut MixEngine, graph: &Graph, start: i64, length: usize, sizes: &[usize]) -> Vec<Vec<f32>> {
|
||||
let mut main = vec![Vec::new(), Vec::new()];
|
||||
let mut offset = 0;
|
||||
let mut block = 0;
|
||||
while offset < length {
|
||||
let n = sizes[block % sizes.len()].min(length - offset);
|
||||
let mut main_block = vec![vec![0.0; n]; 2];
|
||||
mix.render(&graph.session, start + offset as i64, n, &mut main_block);
|
||||
for (output, samples) in main.iter_mut().zip(main_block) {
|
||||
assert_eq!(samples.len(), n);
|
||||
output.extend(samples);
|
||||
}
|
||||
offset += n;
|
||||
block += 1;
|
||||
}
|
||||
main
|
||||
}
|
||||
|
||||
fn numeric_pan(at: i64, first: i64, last: i64) -> [f32; 2] {
|
||||
let pan = if at <= first {
|
||||
-1.0
|
||||
} else if at >= last {
|
||||
1.0
|
||||
} else {
|
||||
(-1.0 + 2.0 * (at - first) as f64 / (last - first) as f64) as f32
|
||||
};
|
||||
// Independent declared zero-depth pan law; no routing or automation helper is called.
|
||||
[(1.0 - pan).min(1.0), (1.0 + pan).min(1.0)]
|
||||
}
|
||||
|
||||
fn check_known(output: &[Vec<f32>], graph: &Graph, start: i64, delay: usize, length: usize) {
|
||||
assert_eq!(output.len(), 2);
|
||||
for (channel, samples) in output.iter().enumerate() {
|
||||
assert_eq!(samples.len(), length);
|
||||
for (offset, &sample) in samples.iter().enumerate() {
|
||||
let source_time = start + offset as i64 - delay as i64;
|
||||
let audible =
|
||||
offset >= delay && source_time >= graph.clip_start && source_time < graph.clip_start + SOURCE_FRAMES as i64 && source_time < MUTE_AT;
|
||||
let expected = if audible { AMPLITUDE * numeric_pan(source_time, graph.pan_start, graph.pan_end)[channel] } else { 0.0 };
|
||||
assert!(sample.is_finite());
|
||||
assert!(
|
||||
(sample - expected).abs() < 2e-7,
|
||||
"channel {channel}, emit {}, source {source_time}, delay {delay}: {sample} != {expected}",
|
||||
start + offset as i64
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(output.iter().flatten().any(|sample| sample.abs() > 0.02), "declared capture must be audible");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_silent_lookahead_keeps_audio_pre_post_pan_and_last_source_sample_299() {
|
||||
for pre in [false, true] {
|
||||
let graph = ordinary(pre, 0, 1, true, 0, 0, 600);
|
||||
let mut mix = make_mix();
|
||||
let output = capture_pcm(&mut mix, &graph, 0, 800, &[1, 7, 37, 100, 3, 64]);
|
||||
assert_eq!(mix.latency, LOOKAHEAD, "the unrelated real Maximizer actually contributes latency");
|
||||
check_known(&output, &graph, 0, LOOKAHEAD, 800);
|
||||
let last = output[0].iter().rposition(|sample| sample.abs() > 1e-6).unwrap();
|
||||
assert_eq!(last, MUTE_AT as usize - 1 + LOOKAHEAD);
|
||||
// Public render_bus uses its default -3 dB law. This separate mute-only fixture
|
||||
// holds the static send at its left endpoint, whose factors are exactly1/0.
|
||||
let mut offline_session = graph.session.clone();
|
||||
offline_session.tracks[0].automation.retain(|lane| lane.param != AutoParam::SendPan(0));
|
||||
let offline = render_bus(&offline_session, graph.capture, Range::new(0, 640), 37);
|
||||
assert_eq!(offline[0].len(), 640);
|
||||
assert_eq!(offline[0].iter().rposition(|sample| sample.abs() > 1e-6), Some(299));
|
||||
for (channel, samples) in offline.iter().enumerate() {
|
||||
for (at, &sample) in samples.iter().enumerate() {
|
||||
let expected = if at < MUTE_AT as usize && channel == 0 { AMPLITUDE } else { 0.0 };
|
||||
assert!((sample - expected).abs() < 2e-7);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aux_pre_tap_omits_post_alignment_while_both_taps_include_upstream_and_own_delay() {
|
||||
for pdc in [false, true] {
|
||||
for pre in [false, true] {
|
||||
let mut session = Session::default();
|
||||
session.edit.delay_compensation = pdc;
|
||||
let source = source(&mut session, 1, 0);
|
||||
let input = session.add_bus("Own upstream", ChannelFormat::Mono);
|
||||
session.track_mut(source).unwrap().mixer.output = Route::Bus(input);
|
||||
let sender = aux(&mut session, input, ChannelFormat::Mono, 1);
|
||||
silent_aux(&mut session, 2);
|
||||
let capture = session.add_bus("Aux capture", ChannelFormat::Stereo);
|
||||
send(&mut session, sender, capture, pre, 0, 600, true);
|
||||
let receiver = return_to_main(&mut session, capture);
|
||||
let graph = Graph { session, capture, receiver, clip_start: 0, pan_start: 0, pan_end: 600 };
|
||||
let tap_delay = if pdc && !pre { 3 * LOOKAHEAD } else { 2 * LOOKAHEAD };
|
||||
let observation_delay = if pdc { 2 * LOOKAHEAD } else { 0 };
|
||||
let mut mix = make_mix();
|
||||
let output = capture_pcm(&mut mix, &graph, 0, 900, &[100, 17, 1, 37, 64]);
|
||||
assert_eq!(mix.latency, if pdc { 3 * LOOKAHEAD } else { 0 });
|
||||
check_known(&output, &graph, 0, tap_delay + observation_delay, 900);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_aux_taps_accumulate_the_actual_upstream_path_instead_of_global_latency() {
|
||||
for pre in [false, true] {
|
||||
let mut session = Session::default();
|
||||
session.edit.delay_compensation = true;
|
||||
let source = source(&mut session, 1, 0);
|
||||
silent_audio(&mut session, 2);
|
||||
let first_bus = session.add_bus("Nested first", ChannelFormat::Mono);
|
||||
session.track_mut(source).unwrap().mixer.output = Route::Bus(first_bus);
|
||||
let first_aux = aux(&mut session, first_bus, ChannelFormat::Mono, 1);
|
||||
let second_bus = session.add_bus("Nested second", ChannelFormat::Mono);
|
||||
session.track_mut(first_aux).unwrap().mixer.output = Route::Bus(second_bus);
|
||||
let sender = aux(&mut session, second_bus, ChannelFormat::Mono, 1);
|
||||
silent_aux(&mut session, 2);
|
||||
let capture = session.add_bus("Nested capture", ChannelFormat::Stereo);
|
||||
send(&mut session, sender, capture, pre, 0, 600, true);
|
||||
let receiver = return_to_main(&mut session, capture);
|
||||
let graph = Graph { session, capture, receiver, clip_start: 0, pan_start: 0, pan_end: 600 };
|
||||
// Upstream audio2*71; first Aux own+alignment2*71; target pre adds1*71,
|
||||
// target post adds2*71. The scalar global mix delay is only4*71.
|
||||
let tap_delay = if pre { 5 * LOOKAHEAD } else { 6 * LOOKAHEAD };
|
||||
let observation_delay = 2 * LOOKAHEAD;
|
||||
let mut mix = make_mix();
|
||||
let output = capture_pcm(&mut mix, &graph, 0, 1100, &[37, 3, 100, 64, 1]);
|
||||
assert_eq!(mix.latency, 4 * LOOKAHEAD);
|
||||
check_known(&output, &graph, 0, tap_delay + observation_delay, 1100);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_extra_downstream_aux_and_master_delay_do_not_shift_the_send_clock() {
|
||||
for pre in [false, true] {
|
||||
let mut graph = ordinary(pre, 0, 1, true, 0, 0, 600);
|
||||
let source = graph.session.tracks[0].id;
|
||||
graph.session.track_mut(source).unwrap().mixer.output = Route::Main;
|
||||
maximizers(&mut graph.session, graph.receiver, 1);
|
||||
silent_aux(&mut graph.session, 2);
|
||||
let master = graph.session.add_track(TrackKind::Master, ChannelFormat::Stereo, None);
|
||||
maximizers(&mut graph.session, master, 1);
|
||||
let mut mix = make_mix();
|
||||
let main = capture_pcm(&mut mix, &graph, 0, 900, &[100, 37, 1, 64]);
|
||||
assert_eq!(mix.latency, 4 * LOOKAHEAD);
|
||||
assert!(main.iter().all(|channel| channel[..4 * LOOKAHEAD].iter().all(|sample| *sample == 0.0)));
|
||||
assert!(main[0][4 * LOOKAHEAD] > 0.4, "main really traverses the excluded output/Aux/Master delays");
|
||||
for (channel, samples) in main.iter().enumerate() {
|
||||
for (at, &sample) in samples.iter().enumerate() {
|
||||
let source_time = at as i64 - (4 * LOOKAHEAD) as i64;
|
||||
let expected = if source_time < 0 {
|
||||
0.0
|
||||
} else {
|
||||
let sent = if source_time < MUTE_AT { AMPLITUDE * numeric_pan(source_time, 0, 600)[channel] } else { 0.0 };
|
||||
AMPLITUDE + sent
|
||||
};
|
||||
assert!((sample - expected).abs() < 2e-7, "exclusion channel {channel}, emit {at}: {sample} != {expected}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unequal_aux_pre_and_direct_bus_ages_keep_the_documented_raw_clock_fallback() {
|
||||
for target_pre in [false, true] {
|
||||
let mut session = Session::default();
|
||||
session.edit.delay_compensation = true;
|
||||
let source = source(&mut session, 1, 0);
|
||||
let input = session.add_bus("Mixed upstream", ChannelFormat::Mono);
|
||||
session.track_mut(source).unwrap().mixer.output = Route::Bus(input);
|
||||
let contributor = aux(&mut session, input, ChannelFormat::Mono, 1);
|
||||
silent_aux(&mut session, 2);
|
||||
let mixed_bus = session.add_bus("Unequal actual ages", ChannelFormat::Mono);
|
||||
session.track_mut(contributor).unwrap().mixer.output = Route::Bus(mixed_bus);
|
||||
let mut pre_send = SendSlot::new(Route::Bus(mixed_bus));
|
||||
pre_send.level_db = 0.0;
|
||||
pre_send.pre_fader = true;
|
||||
session.track_mut(contributor).unwrap().mixer.sends[0] = Some(pre_send);
|
||||
let sender = aux(&mut session, mixed_bus, ChannelFormat::Mono, 0);
|
||||
let capture = session.add_bus("Mixed capture", ChannelFormat::Stereo);
|
||||
send(&mut session, sender, capture, target_pre, 0, 600, false);
|
||||
let receiver = return_to_main(&mut session, capture);
|
||||
let graph = Graph { session, capture, receiver, clip_start: 0, pan_start: 0, pan_end: 600 };
|
||||
let mut mix = make_mix();
|
||||
let output = capture_pcm(&mut mix, &graph, 0, 900, &[37, 100, 1, 3, 64]);
|
||||
let extra = if target_pre { 0 } else { 2 * LOOKAHEAD };
|
||||
let observation_delay = 2 * LOOKAHEAD;
|
||||
let delays = [2 * LOOKAHEAD + extra + observation_delay, 3 * LOOKAHEAD + extra + observation_delay];
|
||||
for (at, (&left, &right)) in output[0].iter().zip(&output[1]).enumerate() {
|
||||
let contributions = delays.iter().filter(|&&delay| at >= delay).count();
|
||||
let expected = if at < MUTE_AT as usize + observation_delay { AMPLITUDE * contributions as f32 } else { 0.0 };
|
||||
assert!((left - expected).abs() < 2e-7, "mixed tap pre={target_pre} emit{at}: {left} != {expected}");
|
||||
assert_eq!(right, 0.0);
|
||||
}
|
||||
assert!(output[0].iter().any(|sample| *sample > 0.02));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_positions_and_reset_seek_use_the_delayed_source_clock_with_pdc_off() {
|
||||
let graph = ordinary(false, 1, 0, false, -512, -300, 300);
|
||||
let mut mix = make_mix();
|
||||
let negative = capture_pcm(&mut mix, &graph, -128, 256, &[1, 37, 3, 64, 17]);
|
||||
assert_eq!(mix.latency, 0, "PDC is off while the insert still physically delays its source");
|
||||
check_known(&negative, &graph, -128, LOOKAHEAD, 256);
|
||||
mix.reset();
|
||||
let seek = capture_pcm(&mut mix, &graph, 240, 400, &[100, 1, 37, 3]);
|
||||
check_known(&seek, &graph, 240, LOOKAHEAD, 400);
|
||||
assert_eq!(seek[1].iter().rposition(|sample| sample.abs() > 1e-6), Some(130));
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
# Send pan and mute automation
|
||||
|
||||
Last reviewed: 2026-10-14. Last updated: 2026-10-14.
|
||||
|
||||
Bus sends read supported `SendPan` and `SendMute` automation during mixing. Pan automation
|
||||
covers mono sources sent to ordinary stereo buses. Mute automation gates ordinary bus routes
|
||||
using the existing channel-routing matrix.
|
||||
|
||||
## Reading and fallback
|
||||
|
||||
A valid nonempty lane in an automation mode that reads overrides the corresponding static send
|
||||
control. A pan lane interpolates between knots and clamps finite values to -1 through 1. A mute
|
||||
lane holds each knot's value, clamps to 0 through 1 and gates the send at values of at least 0.5.
|
||||
Before the first knot, the reader holds its first value; at duplicate timestamps it uses the last
|
||||
knot at that position.
|
||||
|
||||
Off mode, an absent or empty lane, nonfinite point values or decreasing timestamps use the
|
||||
static control for the entire callback. This reader follows the existing mixer convention:
|
||||
`lane.enabled` does not independently gate reading. Global lane-enable and suspension semantics
|
||||
remain the existing mixer policy.
|
||||
|
||||
Each callback builds local forward cursors at the source-sample time represented by its send
|
||||
buffer. Seeking, looping or rendering irregular chunks does not reuse a cursor from an earlier
|
||||
callback. Reader initialization and per-frame lookup share that clock. Position, frame offset
|
||||
and sample age are combined in widened arithmetic before clamping once to the supported bounds.
|
||||
|
||||
## Delay accounting
|
||||
|
||||
Audio send clocks account for processor-declared active insert latency and alignment already
|
||||
applied to the selected buffer. Insert ages accumulate separately from the bounded delay-
|
||||
compensation field; its safety cap does not shorten a send's clock. This assumes processors
|
||||
report their delay accurately. Aux and folder sends also carry the upstream input bus's sample age, including
|
||||
known ages propagated through nested Aux paths. Post-fader Aux buffers include their applied
|
||||
alignment; the existing pre-fader Aux copy does not receive that alignment and uses its own age.
|
||||
Pre-fader audio-track buffers do receive their existing pre-fader alignment.
|
||||
|
||||
Direct bus outputs contribute the age after any additional output delay. A send tap excludes
|
||||
that later output delay, receiving processors and Master processing. Audio processing, routing,
|
||||
delay-line placement and offline latency removal retain their existing behavior.
|
||||
|
||||
Bus age metadata is rebuilt with each block and introduces no new dynamic collection. Equal
|
||||
known contribution ages retain a shared source clock. A sum of differently delayed contributors
|
||||
has no single source age; mixed or overflowing age metadata retains the earlier render-position
|
||||
clock for these send readers. This preserves the existing mixed-routing policy and does not
|
||||
claim complete graph delay compensation. Empty bus inputs use zero upstream age. When delay
|
||||
compensation is off, a known path still accounts for its actual processor delay.
|
||||
|
||||
## Routing compatibility
|
||||
|
||||
Without a qualifying pan lane, routing uses the current static matrix. Mono sends retain their
|
||||
static send pan; stereo sends retain their left/right routing even when a stored static send pan
|
||||
is nonzero. Automated stereo-send pan is outside this contribution.
|
||||
|
||||
A supported mute lane can override the static send mute, including unmuting it. Track mute and
|
||||
the existing solo/VCA suppression still take precedence. Pre-fader sends use the existing
|
||||
pre-fader buffer, post-fader sends use the existing processed buffer, and send level keeps its
|
||||
current reader and timing policy.
|
||||
|
||||
Mute gating preserves the ordinary matrix for mono folds, stereo and supported surround widths.
|
||||
Ambisonic routes and non-bus sends keep their existing handling. Main outputs, master processing,
|
||||
audio delay compensation, hosted-plugin parameter delivery and routing-error policies are unchanged.
|
||||
|
||||
## Callback work and verification
|
||||
|
||||
Pan gains are computed per sample only for supported automated mono-to-stereo sends. Mute uses
|
||||
a stepped gate at each sample. Static routing matrices and gated-path sparse taps are prepared outside the
|
||||
sample loop; automated mono-pan routing needs no matrix. The new helpers use local cursors and fixed
|
||||
stack storage without introducing heap allocation.
|
||||
|
||||
Lane validity is scanned once per callback over its stored points. Worst-case callback CPU and
|
||||
the allocation behavior of the complete mixer remain unmeasured.
|
||||
|
||||
Synthetic regressions exercise independent PCM expectations, all pan laws, mute knots, static
|
||||
fallback, pre/post-fader routing, send level, irregular chunks, seek/loop behavior, hostile
|
||||
timestamps and short buffers. Engine cases cover command history and native save/reopen.
|
||||
Static stereo compatibility checks use nonzero stored send-pan values and unchanged routing
|
||||
references.
|
||||
|
||||
Latency regressions cover the unrelated silent Maximizer case, pan and mute source clocks,
|
||||
Aux pre/post taps, nested upstream paths, subsequent output/processor delay, mixed-age fallback,
|
||||
negative positions and reset/seek behavior with synthetic audio.
|
||||
Unit regressions also check insert-age accounting beyond the delay-compensation cap and age overflow.
|
||||
|
||||
This contribution is limited to these send readers and bus-routing branches.
|
||||
|
||||
## Revision history
|
||||
|
||||
- 2026-10-14: Document supported bus-send automation, fallback, stereo compatibility and callback-work limits.
|
||||
- 2026-10-14: Account for the actual delayed send tap and known upstream bus ages; retain mixed-age timing limits.
|
||||
Reference in new issue
Block a user