truce_core/state.rs
1//! Plugin-state save / restore helpers layered on the canonical wire
2//! format in [`truce_utils::state`]. The wire functions are
3//! re-exported here so format wrappers and plugin code keep a single
4//! import path; the envelope itself lives in `truce-utils` so
5//! `cargo-truce` can emit byte-identical blobs (factory preset files)
6//! without inheriting `truce-core`'s runtime dependency chain.
7
8pub use truce_utils::state::{
9 DeserializedState, StateParse, deserialize_state, hash_plugin_id, parse_state, serialize_state,
10 vst3_cid,
11};
12
13/// The plugin format whose wrapper found a foreign state blob.
14/// Carried in [`ForeignState::Raw`] so a `migrate_state`
15/// implementation can branch per format when the old builds
16/// serialized differently per format.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18#[non_exhaustive]
19pub enum PluginFormat {
20 Clap,
21 Vst3,
22 Vst2,
23 Au,
24 Lv2,
25 Aax,
26}
27
28/// What a format wrapper found where truce state should have been.
29/// Handed to [`crate::plugin::PluginRuntime::migrate_state`] on the
30/// host thread; the plugin decides whether it recognizes the bytes.
31pub enum ForeignState<'a> {
32 /// Bytes that aren't a truce envelope: a previous framework's
33 /// state, exactly as the old build saved it.
34 Raw {
35 format: PluginFormat,
36 /// The container key the bytes were found under, for keyed
37 /// formats (AU dict key, LV2 property URI, AAX chunk id).
38 /// `None` for stream formats (CLAP / VST3 / VST2).
39 source_key: Option<&'a str>,
40 bytes: &'a [u8],
41 },
42 /// A valid truce envelope whose `plugin_id_hash` doesn't match:
43 /// the plugin was renamed / re-identified. Params are already
44 /// decoded; the plugin only decides whether to accept them.
45 MismatchedEnvelope {
46 plugin_id_hash: u64,
47 params: &'a [(u32, f64)],
48 extra: Option<&'a [u8]>,
49 },
50}
51
52/// Truce-shaped state produced by a successful
53/// [`crate::plugin::PluginRuntime::migrate_state`]. Rides the normal
54/// restore pipeline as a synthetic [`DeserializedState`]; the next
55/// save writes a regular envelope, so migration is a one-shot door,
56/// not a permanent dual-format reader.
57pub struct MigratedState {
58 pub params: Vec<(u32, f64)>,
59 pub extra: Option<Vec<u8>>,
60}
61
62impl From<MigratedState> for DeserializedState {
63 fn from(migrated: MigratedState) -> Self {
64 Self {
65 params: migrated.params,
66 extra: migrated.extra,
67 }
68 }
69}
70
71/// Reason a [`crate::PluginRuntime::load_state`] /
72/// `truce_plugin::PluginLogic::load_state` implementation failed to
73/// interpret the host-supplied extra-state blob. Format wrappers
74/// receive this on the audio-thread apply path and log it; hosts
75/// that surface a non-success code to the DAW (e.g. CLAP
76/// `state_load` returning `false`) read the variant via that path.
77///
78/// `Malformed` is the typical case: the blob's framing or content
79/// doesn't match what `save_state` would emit (version skew between
80/// older session files and newer plugin builds is the canonical
81/// example). `Other` carries a free-form message for plugin-specific
82/// failures that don't fit the malformed-bytes shape.
83#[derive(Debug)]
84#[non_exhaustive]
85pub enum StateLoadError {
86 /// State blob is too short, mis-framed, or otherwise unparseable.
87 Malformed(&'static str),
88 /// Plugin-specific failure with a free-form message.
89 Other(String),
90}
91
92impl std::fmt::Display for StateLoadError {
93 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94 match self {
95 Self::Malformed(s) => write!(f, "malformed state: {s}"),
96 Self::Other(s) => f.write_str(s),
97 }
98 }
99}
100
101impl std::error::Error for StateLoadError {}
102
103/// Apply a deserialized state to a plugin: write parameter values,
104/// snap smoothers, then hand the optional extra blob to
105/// [`crate::plugin::PluginRuntime::load_state`].
106///
107/// Format wrappers call this from the audio thread after popping a
108/// pending load off their per-instance handoff queue. The reason it
109/// must run on the audio thread (and not on the host's main thread,
110/// where state-load callbacks are typically invoked): `load_state`
111/// takes `&mut P`, which would alias the audio thread's `&mut P`
112/// inside `process()` and produce a data race. The audio thread is
113/// the single thread that already owns `&mut P` between blocks, so
114/// running the load there sidesteps the race entirely.
115///
116/// `restore_values` and `snap_smoothers` go through the param
117/// struct's interior atomics, so they don't strictly need to run on
118/// the audio thread - but applying the whole state in one place keeps
119/// the param values and the user's extra-state blob coherent for any
120/// observer reading after this returns.
121pub fn apply_state<P: crate::export::PluginExport>(plugin: &mut P, state: &DeserializedState) {
122 use truce_params::Params;
123 plugin.params().restore_values(&state.params);
124 plugin.params().snap_smoothers();
125 if let Some(extra) = &state.extra
126 && let Err(e) = plugin.load_state(extra)
127 {
128 // Audio-thread error path: host already received a "yes I
129 // accepted the state" return from the format wrapper's setChunk
130 // by the time we run, so the only thing left is logging.
131 // `eprintln!` is deliberate - `truce-core` is the audio-runtime
132 // crate, no `log` dep, and a state-load failure is a one-shot
133 // event not a per-block hot path. Format wrappers that surface
134 // this to the host (e.g. CLAP's `state_load` returning `false`)
135 // do so synchronously *before* the queue handoff.
136 eprintln!("truce: load_state failed: {e}");
137 }
138}
139
140/// Parse a host-supplied state blob and, when it isn't this plugin's
141/// envelope, offer it to the plugin's
142/// [`crate::plugin::PluginRuntime::migrate_state`] hook. One routing
143/// point for every format wrapper's state callback:
144///
145/// - a matching envelope loads as always;
146/// - foreign bytes ([`StateParse::NotAnEnvelope`]) and renamed-plugin
147/// envelopes ([`StateParse::WrongPlugin`]) go to `migrate_state`;
148/// - a future envelope version and a corrupt envelope fail the load
149/// (never handed to the plugin), each with its own log line.
150///
151/// `None` means the load failed and the wrapper must report failure
152/// to the host in its own idiom. Runs on the host thread - that's
153/// where `migrate_state` is allowed to do allocator-heavy parsing.
154pub fn parse_or_migrate<P: PluginExport>(
155 data: &[u8],
156 expected_plugin_id: u64,
157 format: PluginFormat,
158 source_key: Option<&str>,
159) -> Option<DeserializedState> {
160 match truce_utils::state::parse_state(data, expected_plugin_id) {
161 StateParse::Ok(state) => Some(state),
162 StateParse::NotAnEnvelope => P::migrate_state(&ForeignState::Raw {
163 format,
164 source_key,
165 bytes: data,
166 })
167 .map(Into::into),
168 StateParse::WrongPlugin { found, state } => {
169 P::migrate_state(&ForeignState::MismatchedEnvelope {
170 plugin_id_hash: found,
171 params: &state.params,
172 extra: state.extra.as_deref(),
173 })
174 .map(Into::into)
175 }
176 StateParse::UnknownVersion(version) => {
177 // Same logging rationale as `apply_state`: one-shot event,
178 // no `log` dep in the audio-runtime crate.
179 eprintln!(
180 "truce: state blob carries envelope version {version}; this build \
181 reads version 1 - load failed"
182 );
183 None
184 }
185 StateParse::Corrupt => {
186 eprintln!("truce: state blob is a corrupt truce envelope - load failed");
187 None
188 }
189 }
190}
191
192/// Apply just the parameter values from a deserialized state - the
193/// host-thread-safe subset of [`apply_state`]. Format wrappers call
194/// this from their state-load callback (host main thread) before
195/// pushing the full state onto the audio-thread handoff queue, so
196/// host-thread reads of `getParameter`/equivalents see the restored
197/// values immediately. Validators (auval, pluginval, the VST2 binary
198/// smoke) read parameters synchronously after `setChunk`/equivalents
199/// without first running a render block, and would otherwise see the
200/// pre-restore values until the audio thread caught up.
201///
202/// The extra blob still has to round-trip through the audio thread
203/// because [`crate::plugin::PluginRuntime::load_state`] takes `&mut P`, which
204/// would alias `process()`'s `&mut P` if called from the host thread.
205/// `restore_values` and `snap_smoothers` go through atomic interior
206/// mutability and are safe to call concurrently with `process()`.
207pub fn apply_params<P: truce_params::Params>(params: &P, state: &DeserializedState) {
208 params.restore_values(&state.params);
209 params.snap_smoothers();
210}
211
212// ---------------------------------------------------------------------------
213// `snapshot_plugin` / `restore_plugin` - high-level helpers wrapping
214// `serialize_state` + `deserialize_state` with the params-collect /
215// restore + custom-state plumbing every host needs to do anyway.
216// ---------------------------------------------------------------------------
217
218use crate::export::PluginExport;
219use truce_params::Params;
220
221/// Errors `restore_plugin` can return.
222///
223/// `Invalid` covers envelope-level failures (missing / wrong magic,
224/// version mismatch, plugin-ID mismatch, truncated body); `LoadState`
225/// covers a successfully-parsed envelope whose extra-state blob the
226/// plugin's [`crate::PluginRuntime::load_state`] rejected. The caller
227/// typically prints a diagnostic and proceeds with default params.
228#[derive(Debug)]
229pub enum RestoreError {
230 /// The bytes don't parse as a state envelope for this plugin.
231 Invalid,
232 /// Envelope parsed but the plugin couldn't interpret its extra
233 /// bytes.
234 LoadState(StateLoadError),
235}
236
237impl std::fmt::Display for RestoreError {
238 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239 match self {
240 Self::Invalid => f.write_str("state envelope is invalid"),
241 Self::LoadState(e) => write!(f, "plugin load_state failed: {e}"),
242 }
243 }
244}
245
246impl std::error::Error for RestoreError {}
247
248/// Serialize a plugin instance into the canonical state envelope -
249/// parameter values + optional `Plugin::save_state()` payload, with
250/// the magic / version / plugin-ID header `serialize_state` writes.
251///
252/// Same shape every format wrapper produces, so a `.state` file
253/// written by one host loads in any other (subject to the
254/// plugin-ID match `deserialize_state` enforces).
255pub fn snapshot_plugin<P: PluginExport>(plugin: &P) -> Vec<u8> {
256 let (ids, values) = plugin.params().collect_values();
257 let extra = plugin.save_state();
258 serialize_state(hash_plugin_id(P::info().clap_id), &ids, &values, &extra)
259}
260
261/// Inverse of [`snapshot_plugin`]. Validates the envelope's magic,
262/// version, and plugin-ID hash; on success restores parameter
263/// values via `Params::restore_values` and forwards the optional
264/// extra payload to `Plugin::load_state`.
265///
266/// # Errors
267///
268/// Returns [`RestoreError::Invalid`] if the magic / version /
269/// plugin-ID hash check fails or the envelope is truncated. A
270/// successful return guarantees the params and (optional) extra
271/// payload were forwarded to the plugin.
272pub fn restore_plugin<P: PluginExport>(plugin: &mut P, bytes: &[u8]) -> Result<(), RestoreError> {
273 let id = hash_plugin_id(P::info().clap_id);
274 let s = deserialize_state(bytes, id).ok_or(RestoreError::Invalid)?;
275 plugin.params().restore_values(&s.params);
276 if let Some(extra) = s.extra {
277 plugin.load_state(&extra).map_err(RestoreError::LoadState)?;
278 }
279 Ok(())
280}
281
282/// Resolve the state-envelope hash every format wrapper stamps into
283/// the saved blob. Today this is just `hash_plugin_id(info.clap_id)`,
284/// which means the same plugin built as CLAP / VST3 / AU / AAX / VST2
285/// / LV2 produces a single state space - saving in one host and
286/// loading in another will round-trip parameter values (provided the
287/// `Plugin::save_state` / `load_state` extra payload is also
288/// format-agnostic).
289///
290/// **Trade-off:** because the input is the CLAP ID, renaming
291/// `info.clap_id` invalidates **every** saved session across **every**
292/// format. Callers that want format-pinned state (e.g. an AU build
293/// that shouldn't share state with the same plugin's CLAP build)
294/// should add a per-format ID field to [`crate::PluginInfo`] and
295/// route through it instead.
296#[must_use]
297pub fn shared_plugin_state_hash(info: &crate::PluginInfo) -> u64 {
298 hash_plugin_id(info.clap_id)
299}