Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions crates/os-app/src/project_plugins_ui.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,74 @@ mod tests {
assert_eq!(a.state.session.project.mixer[2].slots[1], saved.mixer[2].slots[1]);
}

/// A saved project reopened: its third-party plugins (VST 3, CLAP, VST 2) and native plugins get their sample rate,
/// block size and activation before the state the file holds, as a plugin that works its state out at that rate
/// needs (issue #458: one divided by a rate it had not been given yet). The probe refuses a state before a rate.
#[test]
fn reopened_projects_activate_plugins_before_their_state() {
use os_session::order_probe::{self, Log};
use os_host::Kind;
let path = std::env::temp_dir().join(format!("openstudio-state-order-{}.flp", std::process::id()));
let log = Log::default();
let probes = |pl: &mut Plugins| {
pl.available = vec![order_probe::available("Probe Synth", Format::Vst3, Kind::Instrument, &log), order_probe::available("Probe Keys", Format::Vst2, Kind::Instrument, &log)];
pl.effects = vec![order_probe::available("Probe Fx", Format::Clap, Kind::Effect, &log)];
};
let mut a = App::new(None);
a.state.session.project = crate::locked::Locked::new(crate::projects::test_project());
a.state.session.file = None;
a.state.session.path = None;
probes(&mut a.state.session.plugins);
a.state.session.plugins.set_rate(48000);
let synth = crate::projects::add_plugin_channel(a.state.session.project.get_mut(), "Probe Synth");
let keys = crate::projects::add_plugin_channel(a.state.session.project.get_mut(), "Probe Keys");
for (row, index, st) in [(synth, 0, [4u8, 5]), (keys, 1, [6, 7])] {
a.state.session.plugins.create(row, index).unwrap();
a.state.session.hosted_rows.push(row);
assert!(a.state.session.plugins.set_state(row, &st));
}
a.state.session.project.get_mut().mixer[3].slots[2] = Some(crate::plugins::new_slot("Probe Fx"));
a.state.session.plugins.create_effect(3, 2, 0, None).unwrap();
assert!(a.state.session.plugins.set_state(fx_key(3, 2), &[8, 9]));
a.save_to(path.clone());
assert!(a.state.message.as_deref().is_some_and(|m| m.starts_with("Saved")), "{:?}", a.state.message);
drop(a);
log.lock().unwrap().clear();

let mut b = App::new(None);
probes(&mut b.state.session.plugins);
b.state.session.plugins.set_rate(48000);
b.open(path.clone());
b.sync_wrapped();
let _ = std::fs::remove_file(&path);
assert!(b.state.session.hosted_rows.contains(&synth) && b.state.session.hosted_rows.contains(&keys), "{:?}", b.state.message);
let rate = 48000;
let calls = log.lock().unwrap().clone();
let one = [format!("activate {rate}"), "state".to_string()];
assert_eq!(calls, [&one[..], &one[..], &one[..]].concat(), "each instance: activated, then its state");
assert_eq!(b.state.session.plugins.state(synth), Some(vec![4, 5]));
assert_eq!(b.state.session.plugins.state(keys), Some(vec![6, 7]));
assert_eq!(b.state.session.plugins.state(fx_key(3, 2)), Some(vec![8, 9]));

// Native plugins named by an opened project: the same order.
log.lock().unwrap().clear();
let mut c = App::new(None);
c.state.session.project = crate::locked::Locked::new(crate::projects::test_project());
c.state.session.plugins.available = vec![order_probe::available("Harmor", Format::Native, Kind::Instrument, &log)];
c.state.session.plugins.effects = vec![order_probe::available("Fruity Balance", Format::Native, Kind::Effect, &log)];
c.state.session.plugins.set_rate(48000);
let harmor = crate::projects::add_plugin_channel(c.state.session.project.get_mut(), "Harmor");
c.state.session.project.get_mut().channels[harmor].plugin_state = Some(vec![1, 2, 3]);
c.state.session.project.get_mut().mixer[2].slots[1] = Some(SlotPlugin { id: os_model::Id::NONE, name: "Fruity Balance".into(), state: vec![5, 6] });
c.host_native();
assert!(c.state.session.hosted_rows.contains(&harmor));
let rate = 48000;
let one = [format!("activate {rate}"), "state".to_string()];
assert_eq!(*log.lock().unwrap(), [&one[..], &one[..]].concat());
assert_eq!(c.state.session.plugins.state(harmor), Some(vec![1, 2, 3]));
assert_eq!(c.state.session.plugins.state(fx_key(2, 1)), Some(vec![5, 6]));
}

/// An opened project's plugin channels and mixer slots that name installed native plugins are hosted by them,
/// started from the file's state; a plugin that is not installed is reported and kept; the states of hosted
/// instances are saved, except for one that did not give the file's state back, whose file bytes are kept
Expand Down
2 changes: 2 additions & 0 deletions crates/os-session/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ pub mod mixer_state;
pub mod monitor;
pub mod note_names;
pub mod one_click;
#[cfg(any(test, feature = "test-util"))]
pub mod order_probe;
pub mod osc3;
pub mod panic_log;
pub mod params;
Expand Down
117 changes: 117 additions & 0 deletions crates/os-session/src/order_probe.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// Copyright (C) 2026 ItsAlphaNeon
// SPDX-License-Identifier: GPL-3.0-or-later
// This file is part of Lemon Studio: https://github.com/ItsAlphaNeon/Lemon-Studio

//! A test plugin that writes down the host's calls in order (tests only): which of activation and the saved state an
//! instance got first. A plugin that works its state out at the sample rate it was given (issue #458: one divided by
//! it) needs the rate first; this one refuses a state that comes before any rate, as such a plugin would fail.

use std::sync::{Arc, Mutex};

use os_host::{Descriptor, Format, Kind};

/// The calls every instance of one probe library got, in order: `activate <rate>`, `state` (taken after a rate),
/// `state before rate` (refused).
pub type Log = Arc<Mutex<Vec<String>>>;

/// A library of one probe plugin named `name`, of `format` and `kind`, logging to `log`.
pub fn available(name: &str, format: Format, kind: Kind, log: &Log) -> crate::plugins::Available {
let ext = match format {
Format::Clap => "clap",
Format::Vst3 => "vst3",
Format::Vst2 | Format::Native => "dll",
};
let desc = Descriptor {
format,
// `os_native` lists a native plugin by its folder name.
id: if format == Format::Native { name.into() } else { format!("probe.{}", name.to_lowercase().replace(' ', "-")) },
name: name.into(),
vendor: "Probe".into(),
version: "1".into(),
features: vec![],
kind,
path: match (format, kind) {
(Format::Native, Kind::Effect) => format!("C:/FL/Plugins/Fruity/Effects/{name}/{name}_x64.dll"),
(Format::Native, _) => format!("C:/FL/Plugins/Fruity/Generators/{name}/{name}_x64.dll"),
_ => format!("C:/Plugins/{name}.{ext}"),
}
.into(),
};
crate::plugins::Available { lib: Arc::new(ProbeLib(desc.clone(), log.clone())), desc }
}

struct ProbeLib(Descriptor, Log);

impl os_host::Library for ProbeLib {
fn path(&self) -> &std::path::Path {
&self.0.path
}
fn plugins(&self) -> &[Descriptor] {
std::slice::from_ref(&self.0)
}
fn create(self: Arc<Self>, _: &str) -> Result<os_host::SharedPlugin, String> {
Ok(Arc::new(Mutex::new(Probe { desc: self.0.clone(), log: self.1.clone(), rate: 0, state: vec![1, 2, 3] })))
}
}

struct Probe {
desc: Descriptor,
log: Log,
rate: u32,
state: Vec<u8>,
}

impl Probe {
fn note(&self, what: String) {
self.log.lock().unwrap().push(what);
}
}

impl os_engine::Instrument for Probe {
fn note_on(&mut self, _: u32, _: u8, _: f32) {}
fn note_off(&mut self, _: u32, _: u8) {}
fn process(&mut self, _: u32, _: &mut [f32], _: &mut [f32]) {}
}

impl os_engine::HostedEffect for Probe {
fn process_fx(&mut self, _: u32, _: &mut [f32], _: &mut [f32]) {}
}

impl os_host::Plugin for Probe {
fn desc(&self) -> &Descriptor {
&self.desc
}
fn activate(&mut self, rate: u32) -> bool {
if rate != self.rate {
self.note(format!("activate {rate}"));
self.rate = rate;
}
true
}
fn idle(&mut self) {}
fn has_editor(&self) -> bool {
false
}
fn editor_open(&self) -> bool {
false
}
fn open_editor(&mut self, _: *mut std::ffi::c_void, _: f32) -> Result<(u32, u32), String> {
Err("no editor".into())
}
fn editor_size(&self) -> Option<(u32, u32)> {
None
}
fn close_editor(&mut self) {}
fn save_state(&self) -> Option<Vec<u8>> {
Some(self.state.clone())
}
fn load_state(&mut self, data: &[u8]) -> bool {
if self.rate == 0 {
self.note("state before rate".into());
return false;
}
self.note("state".into());
self.state = data.to_vec();
true
}
}
86 changes: 66 additions & 20 deletions crates/os-session/src/plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -640,20 +640,7 @@ impl Plugins {
self.native_check(&a.desc)?;
let plugin = a.lib.clone().create(&a.desc.id)?;
let mut p = plugin.lock().map_err(|_| "plugin busy")?;
if let Some(st) = state {
if !p.load_state(st) {
eprintln!("[plugins] {} did not take its starting state", a.desc.name);
}
}
if self.rate == 0 {
self.rate = crate::transport::Transport::device_rate().unwrap_or(48000);
}
if std::env::var_os("OS_DEBUG").is_some() {
eprintln!("[plugins] {} activated at {} Hz", a.desc.name, self.rate);
}
if !p.activate(self.rate) {
return Err(format!("{} could not start", a.desc.name));
}
self.start(&mut *p, &a.desc.name, state)?;
// Trimmed audio clips start their note further into the sample (spec: plugins/lemon-sampler.md §7).
p.use_start_param(SAMPLE_START);
// A note's own pan and mod X / Y reach the built-in Lemon instruments only (spec: audio/voice-levels.md); audio
Expand Down Expand Up @@ -707,17 +694,31 @@ impl Plugins {
self.native_check(&a.desc)?;
let plugin = a.lib.clone().create(&a.desc.id)?;
let mut p = plugin.lock().map_err(|_| "plugin busy")?;
if let Some(st) = state {
p.load_state(st);
}
self.start(&mut *p, &a.desc.name, state)?;
drop(p);
Ok((plugin, a.desc.name))
}

/// Starts a new instance: activated at the device rate, then given its starting `state` (issue #458). Activation
/// gives the plugin its sample rate and block size and turns it on (VST 2 `effSetSampleRate`, `effSetBlockSize`,
/// `effMainsChanged`; VST 3 `setupProcessing`, `setActive`; CLAP `activate`), and every format takes a state while
/// active: a plugin that works its state out at the rate it was given (one divided by it) needs that rate first.
fn start(&mut self, p: &mut dyn os_host::Plugin, name: &str, state: Option<&[u8]>) -> Result<(), String> {
if self.rate == 0 {
self.rate = crate::transport::Transport::device_rate().unwrap_or(48000);
}
if std::env::var_os("OS_DEBUG").is_some() {
eprintln!("[plugins] {name} activated at {} Hz", self.rate);
}
if !p.activate(self.rate) {
return Err(format!("{} could not start", a.desc.name));
return Err(format!("{name} could not start"));
}
drop(p);
Ok((plugin, a.desc.name))
if let Some(st) = state {
if !p.load_state(st) {
eprintln!("[plugins] {name} did not take its starting state");
}
}
Ok(())
}

/// The user just added the instance under `key` (a new channel's plugin, a new effect in a slot): its window opens
Expand Down Expand Up @@ -2043,3 +2044,48 @@ mod slot_tests {
assert_eq!(between, 0);
}
}

#[cfg(test)]
mod state_order_tests {
use super::*;
use crate::order_probe::{self, Log};
use os_host::{Format, Kind};

fn probes(format: Format, log: &Log) -> Plugins {
let mut pl = Plugins::default();
pl.available = vec![order_probe::available("Probe Synth", format, Kind::Instrument, log)];
pl.effects = vec![order_probe::available("Probe Fx", format, Kind::Effect, log)];
pl.rate = 48000;
pl
}

fn take(log: &Log) -> Vec<String> {
std::mem::take(&mut *log.lock().unwrap())
}

/// Every way an instance is started from a saved state (a channel's plugin, a mixer slot's, a container's members;
/// project open, FLP import, undo and presets all come through these) gives the plugin its sample rate, block size
/// and activation before the state, in every format: a plugin that works its state out at the rate it was given
/// must not get the state first (issue #458).
#[test]
fn saved_states_reach_plugins_after_activation() {
for format in [Format::Clap, Format::Vst3, Format::Vst2] {
let log = Log::default();
let mut pl = probes(format, &log);
let st = [9u8, 9, 9];
pl.create_with(0, 0, Some(&st)).unwrap();
assert_eq!(take(&log), ["activate 48000", "state"], "{format:?} channel");
assert_eq!(pl.state(0), Some(st.to_vec()), "{format:?}: the channel's instance holds its state");
pl.create_effect(2, 1, 0, Some(&st)).unwrap();
assert_eq!(take(&log), ["activate 48000", "state"], "{format:?} mixer slot");
assert_eq!(pl.state(fx_key(2, 1)), Some(st.to_vec()));
pl.instantiate(0, Some(&st)).unwrap();
assert_eq!(take(&log), ["activate 48000", "state"], "{format:?} container instrument");
pl.instantiate_effect(0, Some(&st)).unwrap();
assert_eq!(take(&log), ["activate 48000", "state"], "{format:?} container effect");
// Without a state: activation only.
pl.create_with(1, 0, None).unwrap();
assert_eq!(take(&log), ["activate 48000"]);
}
}
}
11 changes: 11 additions & 0 deletions crates/os-vst2/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -965,6 +965,17 @@ impl Plugin {

/// Restores a `save_state` blob, one FL Studio saved, or one Lemon Studio's first saves wrote ([`state`]).
pub fn load_state(&mut self, data: &[u8]) -> bool {
let ok = self.restore(data);
// A state reaches an active plugin (it is activated first: issue #458). Its latency and channels were read at
// activation; a plugin whose state changed them without saying so (`IO_CHANGED`) is set up again on the next
// idle, as one that says so is.
if ok && self.rate != 0 && (self.inst.delay() != self.latency || self.inst.channels() != (self.ins, self.outs)) {
self.inst.shared.io_changed.store(true, Ordering::Release);
}
ok
}

fn restore(&mut self, data: &[u8]) -> bool {
match Saved::parse(data, self.inst.flags() & flags::CHUNKS != 0) {
Some(Saved::Chunk(mut c)) => {
let len = c.len() as isize;
Expand Down
27 changes: 27 additions & 0 deletions crates/os-vst2/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,33 @@ fn states_round_trip_as_chunks_or_parameter_lists() {
assert!(!t.load_state(&p.save_state().unwrap()));
}

/// A state reaches a plugin that is already set up and resumed (issue #458): the chunk comes after the rate, block
/// size and resume; a latency the state changed without the plugin saying so is taken on the next idle.
#[test]
fn a_state_reaches_a_resumed_plugin_and_its_new_latency_is_taken() {
let (m, mut p) = gain();
p.set_param(0, 0.75);
let saved = p.save_state().expect("state");
let mut q = Plugin::new(&m, &id_text(GAIN_ID)).expect("create");
clear();
assert!(q.activate(48000));
assert!(q.load_state(&saved));
let order: Vec<String> = probe(|p| p.log.clone()).into_iter().filter(|l| !l.starts_with("automate")).collect();
assert_eq!(order, ["rate 48000", "block 4096", "resume 1", "set chunk 12"]);
assert_eq!(q.param_value(0), Some(0.75));
// Unchanged latency: nothing to set up again.
clear();
q.idle();
assert!(logged("resume").is_empty());
// The state moved the latency quietly.
unsafe { (*q.inst.effect).delay = 96 };
assert!(q.load_state(&saved));
clear();
q.idle();
assert_eq!(logged("resume"), ["resume 0", "resume 1"]);
assert_eq!(os_host::Plugin::latency(&q), 96);
}

#[test]
fn parameters_describe_themselves() {
let (_m, p) = gain();
Expand Down
5 changes: 5 additions & 0 deletions crates/os-vst3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1152,6 +1152,11 @@ impl Plugin {
c.set_state(s.shared());
}
}
// A state reaches an active plug-in (it is activated first: issue #458). Its latency was read at
// activation; one the state changed without a `restartComponent` is taken on the next idle all the same.
if self.rate != 0 && self.processor.get_latency_samples() != self.latency {
self.shared.restart.fetch_or(LATENCY_CHANGED, Ordering::AcqRel);
}
}
true
}
Expand Down
Loading
Loading