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 persist: Vec::new(),
68 }
69 }
70}
71
72/// Reason a [`crate::PluginRuntime::load_state`] /
73/// `truce_plugin::PluginLogic::load_state` implementation failed to
74/// interpret the host-supplied extra-state blob. Format wrappers
75/// receive this on the audio-thread apply path and log it; hosts
76/// that surface a non-success code to the DAW (e.g. CLAP
77/// `state_load` returning `false`) read the variant via that path.
78///
79/// `Malformed` is the typical case: the blob's framing or content
80/// doesn't match what `save_state` would emit (version skew between
81/// older session files and newer plugin builds is the canonical
82/// example). `Other` carries a free-form message for plugin-specific
83/// failures that don't fit the malformed-bytes shape.
84#[derive(Debug)]
85#[non_exhaustive]
86pub enum StateLoadError {
87 /// State blob is too short, mis-framed, or otherwise unparseable.
88 Malformed(&'static str),
89 /// Plugin-specific failure with a free-form message.
90 Other(String),
91}
92
93impl std::fmt::Display for StateLoadError {
94 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95 match self {
96 Self::Malformed(s) => write!(f, "malformed state: {s}"),
97 Self::Other(s) => f.write_str(s),
98 }
99 }
100}
101
102impl std::error::Error for StateLoadError {}
103
104/// Apply a deserialized state to a plugin: write parameter values,
105/// snap smoothers, then hand the optional extra blob to
106/// [`crate::plugin::PluginRuntime::load_state`].
107///
108/// Format wrappers call this from the audio thread after popping a
109/// pending load off their per-instance handoff queue. The reason it
110/// must run on the audio thread (and not on the host's main thread,
111/// where state-load callbacks are typically invoked): `load_state`
112/// takes `&mut P`, which would alias the audio thread's `&mut P`
113/// inside `process()` and produce a data race. The audio thread is
114/// the single thread that already owns `&mut P` between blocks, so
115/// running the load there sidesteps the race entirely.
116///
117/// `restore_values` and `snap_smoothers` go through the param
118/// struct's interior atomics, so they don't strictly need to run on
119/// the audio thread - but applying the whole state in one place keeps
120/// the param values and the user's extra-state blob coherent for any
121/// observer reading after this returns.
122pub fn apply_state<P: crate::export::PluginExport>(plugin: &mut P, state: &DeserializedState) {
123 use truce_params::Params;
124 plugin.params().restore_values(&state.params);
125 plugin.params().load_persist(&state.persist);
126 plugin.params().snap_smoothers();
127 if let Some(extra) = &state.extra
128 && let Err(e) = plugin.load_state(extra)
129 {
130 // Debug-only breadcrumb: this can run on the audio thread (the
131 // deferred load pops off the handoff queue at the top of
132 // `process()`), and `eprintln!` locks stderr and allocates - so
133 // it must never fire in a release / shipped build. By the time
134 // this runs the host already got a success return from the
135 // wrapper's setChunk, so there's no user-facing report left,
136 // only a dev diagnostic. Envelope-level failures the host can
137 // act on are logged synchronously in `parse_or_migrate` before
138 // the queue handoff.
139 #[cfg(debug_assertions)]
140 eprintln!("truce: load_state failed: {e}");
141 #[cfg(not(debug_assertions))]
142 let _ = e;
143 }
144}
145
146/// Parse a host-supplied state blob and, when it isn't this plugin's
147/// envelope, offer it to the plugin's
148/// [`crate::plugin::PluginRuntime::migrate_state`] hook. One routing
149/// point for every format wrapper's state callback:
150///
151/// - a matching envelope loads as always;
152/// - foreign bytes ([`StateParse::NotAnEnvelope`]) and renamed-plugin
153/// envelopes ([`StateParse::WrongPlugin`]) go to `migrate_state`;
154/// - a future envelope version and a corrupt envelope fail the load
155/// (never handed to the plugin), each with its own log line.
156///
157/// `None` means the load failed and the wrapper must report failure
158/// to the host in its own idiom. Runs on the host thread - that's
159/// where `migrate_state` is allowed to do allocator-heavy parsing.
160pub fn parse_or_migrate<P: PluginExport>(
161 data: &[u8],
162 expected_plugin_id: u64,
163 format: PluginFormat,
164 source_key: Option<&str>,
165) -> Option<DeserializedState> {
166 match truce_utils::state::parse_state(data, expected_plugin_id) {
167 StateParse::Ok(state) => Some(state),
168 StateParse::NotAnEnvelope => P::migrate_state(&ForeignState::Raw {
169 format,
170 source_key,
171 bytes: data,
172 })
173 .map(Into::into),
174 StateParse::WrongPlugin { found, state } => {
175 P::migrate_state(&ForeignState::MismatchedEnvelope {
176 plugin_id_hash: found,
177 params: &state.params,
178 extra: state.extra.as_deref(),
179 })
180 .map(Into::into)
181 }
182 StateParse::UnknownVersion(version) => {
183 // Same logging rationale as `apply_state`: one-shot event,
184 // no `log` dep in the audio-runtime crate.
185 eprintln!(
186 "truce: state blob carries envelope version {version}; this build \
187 reads version 1 - load failed"
188 );
189 None
190 }
191 StateParse::Corrupt => {
192 eprintln!("truce: state blob is a corrupt truce envelope - load failed");
193 None
194 }
195 }
196}
197
198/// Apply just the parameter values from a deserialized state - the
199/// host-thread-safe subset of [`apply_state`]. Format wrappers call
200/// this from their state-load callback (host main thread) before
201/// pushing the full state onto the audio-thread handoff queue, so
202/// host-thread reads of `getParameter`/equivalents see the restored
203/// values immediately. Validators (auval, pluginval, the VST2 binary
204/// smoke) read parameters synchronously after `setChunk`/equivalents
205/// without first running a render block, and would otherwise see the
206/// pre-restore values until the audio thread caught up.
207///
208/// The extra blob still has to round-trip through the audio thread
209/// because [`crate::plugin::PluginRuntime::load_state`] takes `&mut P`, which
210/// would alias `process()`'s `&mut P` if called from the host thread.
211/// `restore_values` and `snap_smoothers` go through atomic interior
212/// mutability and are safe to call concurrently with `process()`.
213pub fn apply_params<P: truce_params::Params>(params: &P, state: &DeserializedState) {
214 params.restore_values(&state.params);
215 params.snap_smoothers();
216}
217
218// ---------------------------------------------------------------------------
219// `snapshot_plugin` / `restore_plugin` - high-level helpers wrapping
220// `serialize_state` + `deserialize_state` with the params-collect /
221// restore + custom-state plumbing every host needs to do anyway.
222// ---------------------------------------------------------------------------
223
224use crate::export::PluginExport;
225use truce_params::Params;
226
227/// Errors `restore_plugin` can return.
228///
229/// `Invalid` covers envelope-level failures (missing / wrong magic,
230/// version mismatch, plugin-ID mismatch, truncated body); `LoadState`
231/// covers a successfully-parsed envelope whose extra-state blob the
232/// plugin's [`crate::PluginRuntime::load_state`] rejected. The caller
233/// typically prints a diagnostic and proceeds with default params.
234#[derive(Debug)]
235pub enum RestoreError {
236 /// The bytes don't parse as a state envelope for this plugin.
237 Invalid,
238 /// Envelope parsed but the plugin couldn't interpret its extra
239 /// bytes.
240 LoadState(StateLoadError),
241}
242
243impl std::fmt::Display for RestoreError {
244 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
245 match self {
246 Self::Invalid => f.write_str("state envelope is invalid"),
247 Self::LoadState(e) => write!(f, "plugin load_state failed: {e}"),
248 }
249 }
250}
251
252impl std::error::Error for RestoreError {}
253
254/// Serialize a plugin instance into the canonical state envelope -
255/// parameter values + optional `Plugin::save_state()` payload, with
256/// the magic / version / plugin-ID header `serialize_state` writes.
257///
258/// Same shape every format wrapper produces, so a `.state` file
259/// written by one host loads in any other (subject to the
260/// plugin-ID match `deserialize_state` enforces).
261pub fn snapshot_plugin<P: PluginExport>(plugin: &P) -> Vec<u8> {
262 use truce_params::Params;
263 let (ids, values) = plugin.params().collect_values();
264 let extra = plugin.save_state();
265 let persist = plugin.params().serialize_persist();
266 serialize_state(
267 hash_plugin_id(P::info().clap_id),
268 &ids,
269 &values,
270 &extra,
271 &persist,
272 )
273}
274
275/// Inverse of [`snapshot_plugin`]. Validates the envelope's magic,
276/// version, and plugin-ID hash; on success restores parameter
277/// values via `Params::restore_values` and forwards the optional
278/// extra payload to `Plugin::load_state`.
279///
280/// # Errors
281///
282/// Returns [`RestoreError::Invalid`] if the magic / version /
283/// plugin-ID hash check fails or the envelope is truncated. A
284/// successful return guarantees the params and (optional) extra
285/// payload were forwarded to the plugin.
286pub fn restore_plugin<P: PluginExport>(plugin: &mut P, bytes: &[u8]) -> Result<(), RestoreError> {
287 let id = hash_plugin_id(P::info().clap_id);
288 let s = deserialize_state(bytes, id).ok_or(RestoreError::Invalid)?;
289 plugin.params().restore_values(&s.params);
290 plugin.params().load_persist(&s.persist);
291 if let Some(extra) = s.extra {
292 plugin.load_state(&extra).map_err(RestoreError::LoadState)?;
293 }
294 Ok(())
295}
296
297/// Resolve the state-envelope hash every format wrapper stamps into
298/// the saved blob. Today this is just `hash_plugin_id(info.clap_id)`,
299/// which means the same plugin built as CLAP / VST3 / AU / AAX / VST2
300/// / LV2 produces a single state space - saving in one host and
301/// loading in another will round-trip parameter values (provided the
302/// `Plugin::save_state` / `load_state` extra payload is also
303/// format-agnostic).
304///
305/// **Trade-off:** because the input is the CLAP ID, renaming
306/// `info.clap_id` invalidates **every** saved session across **every**
307/// format. Callers that want format-pinned state (e.g. an AU build
308/// that shouldn't share state with the same plugin's CLAP build)
309/// should add a per-format ID field to [`crate::PluginInfo`] and
310/// route through it instead.
311#[must_use]
312pub fn shared_plugin_state_hash(info: &crate::PluginInfo) -> u64 {
313 hash_plugin_id(info.clap_id)
314}