diff --git a/contributors/people.toml b/contributors/people.toml index d5401ce70..1b81e4eb1 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -70,6 +70,10 @@ sync_github_name = true real_name = "Kushagra Kumar" sync_github_name = true +[people.JonRC] +real_name = "Jonathan Cardoso" +display_name = "Jonathan Cardoso" + # Display name explicitly chosen by the contributor on 2026-10-19. [people.vhhr7] display_name = "Vic Herrera (@vhhr)" diff --git a/crates/clap-host/src/plugin.rs b/crates/clap-host/src/plugin.rs index 1bd0d9ead..b454dbf85 100644 --- a/crates/clap-host/src/plugin.rs +++ b/crates/clap-host/src/plugin.rs @@ -8,6 +8,8 @@ use std::sync::atomic::Ordering; /// Largest block we activate a plugin for. const MAX_BLOCK: usize = 1 << 16; +/// Most `on_main_thread` calls one `idle` runs for a plugin that keeps asking for more. +const MAX_CALLBACKS_PER_IDLE: usize = 8; /// Most channels a host strip may ask for. const MAX_CHANNELS: usize = 64; /// Queue slots that only releases from `note_off` may take: one per key, so a queue that @@ -43,6 +45,8 @@ pub struct ClapPlugin { channels: usize, max_block: usize, latency: usize, + /// What the last `prepare` was asked for, to restart the plugin the same way. + prepared: Option<(f32, usize, usize)>, steady: i64, transport: Option, } @@ -67,6 +71,7 @@ impl ClapPlugin { channels: 2, max_block: 0, latency: 0, + prepared: None, steady: 0, transport: None, } @@ -231,6 +236,7 @@ impl Plugin for ClapPlugin { } fn prepare(&mut self, sample_rate: f32, max_block: usize, channels: usize) { + self.prepared = Some((sample_rate, max_block, channels)); let sr = if sample_rate.is_finite() && sample_rate > 0.0 { f64::from(sample_rate) } else { 48_000.0 }; let mb = max_block.clamp(1, MAX_BLOCK); self.channels = channels.clamp(1, MAX_CHANNELS); @@ -358,6 +364,25 @@ impl Plugin for ClapPlugin { self.latency } + fn idle(&mut self) { + // A plugin that finds a new latency while processing asks for `on_main_thread`, and from + // there for a restart (maybe after more callbacks): the new value only counts once it is + // activated again. Run every callback it asks for here, a bounded number of them. + for _ in 0..MAX_CALLBACKS_PER_IDLE { + if !self.inst.state().callback.load(Ordering::Relaxed) { + break; + } + self.inst.service_callback(); + } + if self.inst.state().restart.swap(false, Ordering::Relaxed) { + if let Some((sr, mb, ch)) = self.prepared { + self.prepare(sr, mb, ch); + } + } else if self.inst.is_active() && self.inst.state().latency_changed.swap(false, Ordering::Relaxed) { + self.latency = self.inst.latency() as usize; + } + } + fn set_transport(&mut self, transport: &Transport) { self.transport = Some(*transport); } diff --git a/crates/clap-host/tests/fixture/src/lib.rs b/crates/clap-host/tests/fixture/src/lib.rs index 31700b666..e73c6b1c8 100644 --- a/crates/clap-host/tests/fixture/src/lib.rs +++ b/crates/clap-host/tests/fixture/src/lib.rs @@ -1,7 +1,9 @@ //! Test-only CLAP plugins for soundcraft-clap-host: a gain effect and a "DC synth". //! //! - `org.soundcraft.test.gain`: stereo in/out, param 7 "Gain" (0..2, default 1), param 3 "Mode" -//! (stepped enum A/B/C), hidden param 9, latency 3 samples. +//! (stepped enum A/B/C), hidden param 9, latency 3 samples. Mode C needs 16: like LSP, the +//! plugin finds that out in `process`, asks for `on_main_thread`, from there for a second +//! `on_main_thread`, and from that one for a restart; it reports 16 once activated again. //! - `org.soundcraft.test.synth`: instrument, stereo out, CLAP note port; outputs a constant equal //! to the velocity of the held note (0 when none), switching at the event's sample offset. A //! MIDI CC 7 (volume) sets the constant to its value / 127. `reset` leaves the note sounding. @@ -99,6 +101,11 @@ struct Fx { gain: f64, mode: f64, level: f64, + /// The latency the plugin was activated with, and whether it asked for a restart to change it. + latency: u32, + restart_wanted: bool, + /// The first `on_main_thread` after a latency change only asks for another one. + second_callback_asked: bool, active: bool, processing: bool, gui_created: bool, @@ -146,9 +153,14 @@ unsafe extern "C" fn activate(p: *const clap_plugin, sr: f64, min: u32, max: u32 return false; } f.active = true; + f.latency = latency_for(f.mode); true } +fn latency_for(mode: f64) -> u32 { + if mode >= 2.0 { 16 } else { 3 } +} + unsafe extern "C" fn deactivate(p: *const clap_plugin) { let f = unsafe { fx(p) }; assert!(!f.processing, "deactivate while processing"); @@ -310,6 +322,11 @@ unsafe extern "C" fn process(p: *const clap_plugin, pr: *const clap_process) -> unsafe { *o.add(i) = v }; } } + if latency_for(f.mode) != f.latency && !f.restart_wanted { + f.restart_wanted = true; + let host = unsafe { &*f.host }; + unsafe { (host.request_callback.unwrap())(f.host) }; + } CLAP_PROCESS_CONTINUE } @@ -422,8 +439,8 @@ unsafe extern "C" fn ports_get(p: *const clap_plugin, index: u32, is_input: bool static PORTS: clap_plugin_audio_ports = clap_plugin_audio_ports { count: Some(ports_count), get: Some(ports_get) }; -unsafe extern "C" fn latency_get(_p: *const clap_plugin) -> u32 { - 3 +unsafe extern "C" fn latency_get(p: *const clap_plugin) -> u32 { + unsafe { fx(p) }.latency } static LATENCY: clap_plugin_latency = clap_plugin_latency { get: Some(latency_get) }; @@ -586,7 +603,20 @@ unsafe extern "C" fn get_extension(p: *const clap_plugin, id: *const c_char) -> } } -unsafe extern "C" fn on_main_thread(_p: *const clap_plugin) {} +unsafe extern "C" fn on_main_thread(p: *const clap_plugin) { + let f = unsafe { fx(p) }; + if !f.restart_wanted { + return; + } + let host = unsafe { &*f.host }; + if std::mem::replace(&mut f.second_callback_asked, true) { + f.restart_wanted = false; + f.second_callback_asked = false; + unsafe { (host.request_restart.unwrap())(f.host) }; + } else { + unsafe { (host.request_callback.unwrap())(f.host) }; + } +} // ---- factory + entry ---- @@ -641,6 +671,9 @@ unsafe extern "C" fn factory_create(_f: *const clap_plugin_factory, host: *const gain: 1.0, mode: 0.0, level: 0.0, + latency: 3, + restart_wanted: false, + second_callback_asked: false, active: false, processing: false, gui_created: false, diff --git a/crates/clap-host/tests/it/fixture_e2e.rs b/crates/clap-host/tests/it/fixture_e2e.rs index b748fc267..fe110e58d 100644 --- a/crates/clap-host/tests/it/fixture_e2e.rs +++ b/crates/clap-host/tests/it/fixture_e2e.rs @@ -80,6 +80,27 @@ fn gain_processes_audio_and_follows_params() { p.process(&mut io, 8); } +#[test] +fn a_new_latency_counts_after_the_restart_the_plugin_asks_for() { + fixture_dir(); + let mut p = soundcraft_clap_host::create(GAIN).unwrap(); + p.prepare(48_000.0, 64, 2); + assert_eq!(p.latency(), 3); + assert!(p.set_param("3", 2.0), "mode C takes 16 samples"); + let mut io = vec![vec![0.5f32; 64]; 2]; + p.process(&mut io, 64); + assert_eq!(p.latency(), 3, "so far the plugin only asked for on_main_thread"); + // One idle runs both callbacks the plugin asks for (the second one asks for the restart). + p.idle(); + assert_eq!(p.latency(), 16, "restarted with its new latency"); + assert_eq!(p.param("3"), Some(2.0)); + let mut io = vec![vec![0.5f32; 64]; 2]; + p.process(&mut io, 64); + assert!(io[0].iter().all(|&x| (x - 0.5).abs() < 1e-6), "still processing after the restart: {:?}", &io[0][..4]); + p.idle(); + assert_eq!(p.latency(), 16); +} + #[test] fn synth_plays_notes_at_their_offsets() { fixture_dir(); diff --git a/crates/dsp/src/lib.rs b/crates/dsp/src/lib.rs index 3c073ec0f..ae065d182 100644 --- a/crates/dsp/src/lib.rs +++ b/crates/dsp/src/lib.rs @@ -210,6 +210,15 @@ pub trait Plugin: Send { fn latency(&self) -> usize { 0 } + /// Main-thread time between blocks, for hosted plugins: runs the callbacks the plugin asked + /// for, restarts it when it asked to, and reads its latency again (some plugins only know it + /// once they have processed). Offline renders call it after every block; the realtime audio + /// thread never does. + /// + /// For implementors: it runs between two `process` calls, on the thread that owns the instance, + /// so it may allocate, block and re-activate the plugin, and it may change what `latency()` + /// reports; callers read `latency()` again afterwards. + fn idle(&mut self) {} /// How long the output keeps ringing after the input stops, in samples. fn tail_samples(&self) -> usize { 0 diff --git a/crates/mix/src/lib.rs b/crates/mix/src/lib.rs index 8c13e8754..5eb030ef0 100644 --- a/crates/mix/src/lib.rs +++ b/crates/mix/src/lib.rs @@ -293,6 +293,36 @@ impl MixEngine { self.main_meter.reset_levels(); } + /// [`MixEngine::reset`], then prepares the hosted plugins again: their own `reset` may keep + /// audio (a VST3 processor's only flushes notes), and activating them again clears it. + /// Offline only: plugins allocate when they activate. + pub(crate) fn reset_and_reprepare(&mut self) { + self.reset(); + let (sr, mb) = (self.sample_rate, self.max_block); + for s in self.strips.values_mut() { + for p in s.plugins.iter_mut().flatten().chain(s.instrument.as_mut()) { + if is_third_party(&p.id) { + p.plugin.prepare(sr, mb, p.ch); + } + } + } + } + + /// Main-thread time for every plugin ([`Plugin::idle`]): offline renders give it between + /// blocks, the audio thread never does. True when an insert's or an instrument's latency + /// changed (both are delay-compensated). + pub(crate) fn idle_plugins(&mut self) -> bool { + let mut changed = false; + for s in self.strips.values_mut() { + for p in s.plugins.iter_mut().flatten().chain(s.instrument.as_mut()) { + let before = p.plugin.latency(); + p.plugin.idle(); + changed |= p.plugin.latency() != before; + } + } + changed + } + /// Bring plugin instances in line with the session (creates/destroys as needed). Allocates; /// call outside the realtime thread when the document changes, or let `render` do it. pub fn sync(&mut self, s: &Session) { diff --git a/crates/mix/src/offline.rs b/crates/mix/src/offline.rs index 85add656b..3d9dbddee 100644 --- a/crates/mix/src/offline.rs +++ b/crates/mix/src/offline.rs @@ -42,6 +42,9 @@ pub fn source_channels(s: &Session, bus: Option) -> usize { } } +/// How many times [`RangeRender`] renders its first block again while a plugin's latency changes. +const FIRST_BLOCK_TRIES: usize = 4; + /// [`render_range`] or [`render_bus`] of any length, a block at a time. pub struct RangeRender { eng: MixEngine, @@ -64,6 +67,12 @@ impl RangeRender { RangeRender { eng, bus, tmp, start: range.start, done: 0, total: len, latency: 0 } } + /// The engine, for tests that hand it fake hosted plugins. + #[cfg(test)] + pub(crate) fn engine(&mut self) -> &mut MixEngine { + &mut self.eng + } + fn render(&mut self, s: &Session, pos: Samples, n: usize) { match self.bus { Some(id) => { @@ -83,6 +92,27 @@ impl RangeRender { } let n = (self.total - self.done).min(self.eng.max_block()); self.render(s, self.start + self.done as i64, n); + // Hosted plugins may only find their latency once they process, and apply it when they + // are restarted. If one did on the first block, start over from a clean state, so that + // block and the latency trimmed off it line up too. The head trim is the first block's: + // a later change (an automated lookahead) moves the alignment from that block on, as in + // playback, since the audio before it has already gone out. + if self.eng.idle_plugins() && self.done == 0 { + // A plugin may settle in more than one step: start over until none changes, a few + // times at most. + let mut settled = false; + for _ in 0..FIRST_BLOCK_TRIES { + self.eng.reset_and_reprepare(); + self.render(s, self.start, n); + if !self.eng.idle_plugins() { + settled = true; + break; + } + } + if !settled { + log::warn!("a plugin's latency kept changing on the first block; the render may not line up with the timeline"); + } + } if self.done == 0 { // The first block tells the mix's latency: render that much more and drop the head. self.latency = match self.bus { diff --git a/crates/mix/src/tests.rs b/crates/mix/src/tests.rs index 47db99cb5..965a12f9b 100644 --- a/crates/mix/src/tests.rs +++ b/crates/mix/src/tests.rs @@ -1492,6 +1492,268 @@ fn volume_automation_follows_its_breakpoints_in_any_block_size() { } } +/// Delays its input by `n` samples from its first block, like a lookahead limiter, but reports +/// that latency only after its first block and an `idle`, the way a CLAP plugin applies a new +/// latency through a restart (LSP Limiter: 0 at `activate`, a restart request once it processed). +struct LateLatency { + inner: Box, + n: usize, + lines: Vec>, + processed: bool, + reported: usize, + /// What it reports at each `idle` once it has processed (the last one stays). + steps: std::collections::VecDeque, + /// How many times it was prepared. + prepares: Arc, +} + +impl LateLatency { + /// Prepared, as the host hands it over. + fn new(n: usize) -> Self { + Self::stepping(n, &[n]) + } + + /// Delays by `n` from the start, but reports `steps` one `idle` at a time. + fn stepping(n: usize, steps: &[usize]) -> Self { + let mut p = LateLatency { + inner: soundcraft_dsp::create("gain").unwrap(), + n, + lines: Vec::new(), + processed: false, + reported: 0, + steps: steps.iter().copied().collect(), + prepares: Arc::default(), + }; + p.prepare(48_000.0, 512, 2); + p + } +} + +impl Plugin for LateLatency { + fn info(&self) -> &'static soundcraft_dsp::PluginInfo { + self.inner.info() + } + fn prepare(&mut self, sr: f32, mb: usize, ch: usize) { + self.inner.prepare(sr, mb, ch); + self.lines = vec![std::iter::repeat_n(0.0, self.n).collect(); ch]; + self.prepares.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + fn reset(&mut self) { + self.lines.iter_mut().for_each(|l| l.iter_mut().for_each(|x| *x = 0.0)); + } + fn set_param(&mut self, id: &str, v: f32) -> bool { + self.inner.set_param(id, v) + } + fn param(&self, id: &str) -> Option { + self.inner.param(id) + } + fn process(&mut self, io: &mut [Vec], frames: usize) { + for (c, line) in io.iter_mut().zip(&mut self.lines) { + for x in c.iter_mut().take(frames) { + line.push_back(*x); + *x = line.pop_front().unwrap(); + } + } + self.processed = true; + } + fn latency(&self) -> usize { + self.reported + } + fn idle(&mut self) { + if self.processed + && let Some(r) = self.steps.pop_front() + { + self.reported = r; + } + } +} + +/// A hosted insert that reports its latency only after the first block (on a track, or on the +/// master, whose latency is read before it processes) still lines up from the first sample. +#[test] +fn offline_renders_follow_a_latency_reported_after_the_first_block() { + for kind in [TrackKind::Audio, TrackKind::Master] { + let mut s = Session::default(); + s.edit.delay_compensation = true; + let n = 4096; + let mut clicks = vec![0.0f32; n]; + for at in [100, 3000] { + clicks[at] = 0.25; + } + s.pool.insert(SourceId(902), Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![clicks.clone(), clicks] }))); + let mut tracks = Vec::new(); + for _ in 0..2 { + let t = s.add_track(TrackKind::Audio, ChannelFormat::Stereo, None); + let cid = s.new_clip_id(); + s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "clicks", SourceId(902), 0, 0, n as i64)); + tracks.push(t); + } + let target = if kind == TrackKind::Audio { tracks[0] } else { s.add_track(TrackKind::Master, ChannelFormat::Stereo, None) }; + s.track_mut(target).unwrap().mixer.inserts[0] = Some(Insert::new("clap:test.late")); + let render = |s: &Session| { + let mut r = RangeRender::new(s, None, Range::new(0, n as i64), 512); + r.engine().set_external_instances(true); + r.engine().adopt(vec![PreparedInstance { + track: target, + slot: 0, + id: "clap:test.late".into(), + ch: 2, + plugin: Box::new(LateLatency::new(240)), + }]); + let mut out = vec![Vec::new(); 2]; + while let Some((chunk, k)) = r.next_block(s) { + for (o, c) in out.iter_mut().zip(chunk) { + o.extend_from_slice(&c[..k]); + } + } + out + }; + // Both tracks play the clicks: they land where they are on the timeline. + let out = render(&s); + assert_eq!(out[0].len(), n); + assert_eq!(impulse_at(&out[0]), vec![100, 3000], "{kind:?}: the plugin's 240 samples are compensated from the start"); + // The second track flipped: with the two lined up, nothing is left. + s.track_mut(tracks[1]).unwrap().mixer.phase_invert = true; + let out = render(&s); + assert!(out.iter().flatten().all(|x| x.abs() < 1e-6), "{kind:?}: the tracks line up"); + } +} + +/// An echo 1000 samples later whose memory survives `reset` and is cleared only by `prepare`, +/// like a VST3 processor: its reset only flushes notes, and activating it again clears its audio. +struct KeepsTail { + inner: Box, + ring: Vec>, + pos: usize, +} + +impl KeepsTail { + /// Prepared, as the host hands it over. + fn new() -> Self { + let mut p = KeepsTail { inner: soundcraft_dsp::create("gain").unwrap(), ring: Vec::new(), pos: 0 }; + p.prepare(48_000.0, 512, 2); + p + } +} + +impl Plugin for KeepsTail { + fn info(&self) -> &'static soundcraft_dsp::PluginInfo { + self.inner.info() + } + fn prepare(&mut self, sr: f32, mb: usize, ch: usize) { + self.inner.prepare(sr, mb, ch); + self.ring = vec![vec![0.0; 1000]; ch]; + self.pos = 0; + } + fn reset(&mut self) {} + fn set_param(&mut self, id: &str, v: f32) -> bool { + self.inner.set_param(id, v) + } + fn param(&self, id: &str) -> Option { + self.inner.param(id) + } + fn process(&mut self, io: &mut [Vec], frames: usize) { + for i in 0..frames { + for (c, ring) in io.iter_mut().zip(&mut self.ring) { + let old = std::mem::replace(&mut ring[self.pos], c[i]); + c[i] += 0.5 * old; + } + self.pos = (self.pos + 1) % 1000; + } + } +} + +/// Starting the first block over must not keep what the discarded pass left in an insert whose +/// own reset keeps its audio (a VST3 tail), on any track. +#[test] +fn a_first_block_rendered_again_carries_nothing_from_the_discarded_pass() { + let mut s = Session::default(); + s.edit.delay_compensation = true; + let n = 4096; + let mut clicks = vec![0.0f32; n]; + for at in [100, 3000] { + clicks[at] = 0.25; + } + s.pool.insert(SourceId(903), Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![clicks.clone(), clicks] }))); + let mut tracks = Vec::new(); + for slot in ["clap:test.late", "clap:test.tail"] { + let t = s.add_track(TrackKind::Audio, ChannelFormat::Stereo, None); + let cid = s.new_clip_id(); + s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "clicks", SourceId(903), 0, 0, n as i64)); + s.track_mut(t).unwrap().mixer.inserts[0] = Some(Insert::new(slot)); + tracks.push(t); + } + let mut r = RangeRender::new(&s, None, Range::new(0, n as i64), 512); + r.engine().set_external_instances(true); + r.engine().adopt(vec![ + PreparedInstance { track: tracks[0], slot: 0, id: "clap:test.late".into(), ch: 2, plugin: Box::new(LateLatency::new(240)) }, + PreparedInstance { track: tracks[1], slot: 0, id: "clap:test.tail".into(), ch: 2, plugin: Box::new(KeepsTail::new()) }, + ]); + let mut out = vec![Vec::new(); 2]; + while let Some((chunk, k)) = r.next_block(&s) { + for (o, c) in out.iter_mut().zip(chunk) { + o.extend_from_slice(&c[..k]); + } + } + assert_eq!(impulse_at(&out[0]), vec![100, 1100, 3000, 4000], "the clicks and their echoes, and no echo of the first pass"); +} + +/// Clicks at 100 and 3000 on a stereo track with `plugin` as its insert, rendered in 512-sample +/// blocks: where the clicks land. +fn clicks_through(plugin: LateLatency) -> Vec { + let mut s = Session::default(); + s.edit.delay_compensation = true; + let n = 4096; + let mut clicks = vec![0.0f32; n]; + for at in [100, 3000] { + clicks[at] = 0.25; + } + s.pool.insert(SourceId(904), Arc::new(SourceAudio::new(AudioBuffer { sample_rate: 48_000, channels: vec![clicks.clone(), clicks] }))); + let t = s.add_track(TrackKind::Audio, ChannelFormat::Stereo, None); + let cid = s.new_clip_id(); + s.track_mut(t).unwrap().playlist_mut().unwrap().clips.push(Clip::audio(cid, "clicks", SourceId(904), 0, 0, n as i64)); + s.track_mut(t).unwrap().mixer.inserts[0] = Some(Insert::new("clap:test.late")); + let mut r = RangeRender::new(&s, None, Range::new(0, n as i64), 512); + r.engine().set_external_instances(true); + r.engine().adopt(vec![PreparedInstance { track: t, slot: 0, id: "clap:test.late".into(), ch: 2, plugin: Box::new(plugin) }]); + let mut out = Vec::new(); + while let Some((chunk, k)) = r.next_block(&s) { + out.extend_from_slice(&chunk[0][..k]); + } + impulse_at(&out) +} + +/// A plugin whose latency settles in two steps (it changes again on the first block rendered a +/// second time) still lines up: the render starts over until no latency changes. +#[test] +fn a_latency_that_settles_in_two_steps_still_lines_up() { + assert_eq!(clicks_through(LateLatency::stepping(240, &[120, 240])), vec![100, 3000]); + assert_eq!(clicks_through(LateLatency::new(240)), vec![100, 3000], "one step"); +} + +/// An instrument's latency is compensated like an insert's (#1476), so either one reported late +/// renders the first block again (every hosted instance is prepared a second time). +#[test] +fn an_insert_or_instrument_latency_reported_late_renders_the_first_block_again() { + for insert_too in [false, true] { + let (mut s, a) = session_with_dc(0.5, 4096); + let inst = s.add_track(TrackKind::Instrument, ChannelFormat::Stereo, None); + s.track_mut(inst).unwrap().instrument = Some(Insert::new("clap:test.inst")); + let synth = LateLatency::new(64); + let prepares = Arc::clone(&synth.prepares); + let mut adopt = vec![PreparedInstance { track: inst, slot: INSTRUMENT_SLOT, id: "clap:test.inst".into(), ch: 2, plugin: Box::new(synth) }]; + if insert_too { + s.track_mut(a).unwrap().mixer.inserts[0] = Some(Insert::new("clap:test.late")); + adopt.push(PreparedInstance { track: a, slot: 0, id: "clap:test.late".into(), ch: 1, plugin: Box::new(LateLatency::new(240)) }); + } + let mut r = RangeRender::new(&s, None, Range::new(0, 4096), 512); + r.engine().set_external_instances(true); + r.engine().adopt(adopt); + while r.next_block(&s).is_some() {} + assert_eq!(prepares.load(std::sync::atomic::Ordering::Relaxed), 2, "with an insert reporting late too: {insert_too}"); + } +} + /// A master fader's breakpoint acts on its own sample too. #[test] fn master_volume_automation_follows_its_breakpoints_in_any_block_size() { diff --git a/crates/vst3-host/src/plugin.rs b/crates/vst3-host/src/plugin.rs index 2999c1ab7..6f21717ee 100644 --- a/crates/vst3-host/src/plugin.rs +++ b/crates/vst3-host/src/plugin.rs @@ -359,6 +359,15 @@ impl Plugin for Vst3Plugin { self.latency } + fn idle(&mut self) { + // A new latency is announced with `restartComponent(kLatencyChanged)`, which some plugins + // send from a timer of their own, long after they started using it (LSP): ask instead. + if self.inst.is_active() { + self.inst.host().latency_changed.store(false, Ordering::Relaxed); + self.latency = self.inst.latency() as usize; + } + } + fn set_transport(&mut self, transport: &Transport) { self.transport = Some(*transport); } diff --git a/crates/vst3-host/tests/fixture/src/lib.rs b/crates/vst3-host/tests/fixture/src/lib.rs index 9d9323cb3..988990fc9 100644 --- a/crates/vst3-host/tests/fixture/src/lib.rs +++ b/crates/vst3-host/tests/fixture/src/lib.rs @@ -4,7 +4,8 @@ //! (connected through IConnectionPoint, synced through the component state). Params: 7 "Gain" //! (plain 0..2, linear, units dB), 3 "Mode" (3 steps: A/B/C), 12 "Freq" (20..20000 Hz, log), //! 9 hidden, 11 bypass. Starts at gain 0.5 (its state) although the declared default is 1.0. -//! Reports 3 samples of latency. State: the component stores the gain (one LE f64), the +//! Reports 3 samples of latency, 16 in mode C (at once, but never announced with +//! `restartComponent`, like a plugin that announces it later from a timer). State: the component stores the gain (one LE f64), the //! controller the Freq value (one LE f64). Its controller has an editor view (`IPlugView`, //! 320×240, no real drawing) supporting NSView/HWND/X11. //! - "Fixture Synth" (`Instrument|Synth`): a single-component instrument (the component is also @@ -77,6 +78,8 @@ unsafe fn channels<'a>(bus: &AudioBusBuffers, frames: usize) -> Vec<&'a mut [f32 struct GainProcessor { /// Normalized gain (plain = 2 × normalized). gain: AtomicU64, + /// Normalized mode (C = 1.0). + mode: AtomicU64, arrangement: AtomicU64, _live: Live, } @@ -179,7 +182,7 @@ impl IAudioProcessorTrait for GainProcessor { if size == SymbolicSampleSizes_::kSample32 as i32 { kResultOk } else { kNotImplemented } } unsafe fn getLatencySamples(&self) -> u32 { - 3 + if f64::from_bits(self.mode.load(Ordering::Relaxed)) > 0.75 { 16 } else { 3 } } unsafe fn setupProcessing(&self, setup: *mut ProcessSetup) -> tresult { let s = unsafe { &*setup }; @@ -198,8 +201,13 @@ impl IAudioProcessorTrait for GainProcessor { let Some(q) = (unsafe { ComRef::from_raw(changes.getParameterData(i)) }) else { continue }; let (mut off, mut v) = (0, 0.0); let n = unsafe { q.getPointCount() }; - if unsafe { q.getParameterId() } == 7 && n > 0 && unsafe { q.getPoint(n - 1, &mut off, &mut v) } == kResultOk { - self.gain.store(v.to_bits(), Ordering::Relaxed); + if n == 0 || unsafe { q.getPoint(n - 1, &mut off, &mut v) } != kResultOk { + continue; + } + match unsafe { q.getParameterId() } { + 7 => self.gain.store(v.to_bits(), Ordering::Relaxed), + 3 => self.mode.store(v.to_bits(), Ordering::Relaxed), + _ => {} } } } @@ -779,6 +787,7 @@ impl IPluginFactoryTrait for Factory { let unknown = if cid == GAIN_CID { ComWrapper::new(GainProcessor { gain: AtomicU64::new(0.25f64.to_bits()), + mode: AtomicU64::new(0f64.to_bits()), arrangement: AtomicU64::new(SpeakerArr::kStereo), _live: Live::new(&OBJECTS), }) diff --git a/crates/vst3-host/tests/it/fixture_e2e.rs b/crates/vst3-host/tests/it/fixture_e2e.rs index 075f02b12..3e195d789 100644 --- a/crates/vst3-host/tests/it/fixture_e2e.rs +++ b/crates/vst3-host/tests/it/fixture_e2e.rs @@ -71,6 +71,19 @@ fn identity_mapped_param_text_is_read_on_the_main_thread_only() { } } +#[test] +fn idle_reads_a_latency_the_plugin_has_not_announced_yet() { + let mut p = soundcraft_vst3_host::create(&id_of("Fixture Gain")).unwrap(); + p.prepare(48_000.0, 64, 2); + assert_eq!(p.latency(), 3); + assert!(p.set_param("3", 2.0), "mode C takes 16 samples"); + let mut io = vec![vec![0.5f32; 64]; 2]; + p.process(&mut io, 64); + assert_eq!(p.latency(), 3, "no restartComponent came"); + p.idle(); + assert_eq!(p.latency(), 16); +} + #[test] fn gain_processes_audio_and_follows_params() { let mut p = soundcraft_vst3_host::create(&id_of("Fixture Gain")).unwrap(); diff --git a/docs/plugin-parity.md b/docs/plugin-parity.md index daf39e474..298dff5b9 100644 --- a/docs/plugin-parity.md +++ b/docs/plugin-parity.md @@ -52,13 +52,14 @@ User report #152: a saved instrument level does not reach the bounce. | Sidechain / key input | ✅ | ❌ | All three hosts | | ARA 2 (pitch/time editors in the timeline) | ✅ | ❌ | Menu leaves Track/Clip/Window ▸ ARA still missing | | Crash isolation | in-process (DSP on HDX) | in-process | Out-of-process hosting would beat Pro Tools | -| Plugin delay reporting changes on the fly | ✅ | 🟡 | Aux insert latency bug #103 (PR #133) | +| Plugin delay reporting changes on the fly | ✅ | 🟡 | Aux insert latency bug #103 (PR #133). Offline renders follow a latency a hosted plugin finds once it runs (CLAP restart, VST3 asked between blocks, #1287); realtime playback doesn't follow it yet | ## Revision history | Date | Change | Summary | |---|---|---| | 2026-11-09 | trivial | Modulation: Frequency Shifter (`freq_shifter`); 28 processors + 3 instruments | +| 2026-11-02 | minor | Offline renders give hosted plugins main-thread time between blocks: CLAP callbacks and restarts, VST3 latency read again; a latency found on the first block restarts the render (#1287) | | 2026-10-27 | minor | Editors: VST3 and embedded CLAP editors on Linux/X11, with the host run loop (VST3 `IRunLoop`, CLAP timer and fd support) (#527) | | 2026-10-25 | trivial | Auto Pan: constant-power balance of the left and right channels; stereo passes unchanged at the center | | 2026-10-24 | minor | AudioSuite speed ramps (`speed_ramp`): down to a stop and up from one, Fit To or Extend, fades on or off |