Skip to main content

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 them here keeps the param values and
120/// the user's extra-state blob coherent for any observer reading after
121/// this returns.
122///
123/// `#[persist]` fields are **not** applied here - `load_persist` takes a
124/// lock per field that a GUI reader can hold, so it would risk blocking
125/// the audio thread. [`apply_params`] applies persist on the host thread;
126/// the deferred wrappers call it before queueing, and a host-thread full
127/// load (the standalone host, an inactive-plugin load) calls it alongside
128/// this.
129pub fn apply_state<P: crate::export::PluginExport>(plugin: &mut P, state: &DeserializedState) {
130    use truce_params::Params;
131    plugin.params().restore_values(&state.params);
132    plugin.params().snap_smoothers();
133    if let Some(extra) = &state.extra
134        && let Err(e) = plugin.load_state(extra)
135    {
136        // Debug-only breadcrumb: this can run on the audio thread (the
137        // deferred load pops off the handoff queue at the top of
138        // `process()`), and `eprintln!` locks stderr and allocates - so
139        // it must never fire in a release / shipped build. By the time
140        // this runs the host already got a success return from the
141        // wrapper's setChunk, so there's no user-facing report left,
142        // only a dev diagnostic. Envelope-level failures the host can
143        // act on are logged synchronously in `parse_or_migrate` before
144        // the queue handoff.
145        #[cfg(debug_assertions)]
146        eprintln!("truce: load_state failed: {e}");
147        #[cfg(not(debug_assertions))]
148        let _ = e;
149    }
150}
151
152/// Parse a host-supplied state blob and, when it isn't this plugin's
153/// envelope, offer it to the plugin's
154/// [`crate::plugin::PluginRuntime::migrate_state`] hook. One routing
155/// point for every format wrapper's state callback:
156///
157/// - a matching envelope loads as always;
158/// - foreign bytes ([`StateParse::NotAnEnvelope`]) and renamed-plugin
159///   envelopes ([`StateParse::WrongPlugin`]) go to `migrate_state`;
160/// - a future envelope version and a corrupt envelope fail the load
161///   (never handed to the plugin), each with its own log line.
162///
163/// `None` means the load failed and the wrapper must report failure
164/// to the host in its own idiom. Runs on the host thread - that's
165/// where `migrate_state` is allowed to do allocator-heavy parsing.
166pub fn parse_or_migrate<P: PluginExport>(
167    data: &[u8],
168    expected_plugin_id: u64,
169    format: PluginFormat,
170    source_key: Option<&str>,
171) -> Option<DeserializedState> {
172    match truce_utils::state::parse_state(data, expected_plugin_id) {
173        StateParse::Ok(state) => Some(state),
174        StateParse::NotAnEnvelope => P::migrate_state(&ForeignState::Raw {
175            format,
176            source_key,
177            bytes: data,
178        })
179        .map(Into::into),
180        StateParse::WrongPlugin { found, state } => {
181            P::migrate_state(&ForeignState::MismatchedEnvelope {
182                plugin_id_hash: found,
183                params: &state.params,
184                extra: state.extra.as_deref(),
185            })
186            .map(Into::into)
187        }
188        StateParse::UnknownVersion(version) => {
189            // Same logging rationale as `apply_state`: one-shot event,
190            // no `log` dep in the audio-runtime crate.
191            eprintln!(
192                "truce: state blob carries envelope version {version}; this build \
193                 reads version 1 - load failed"
194            );
195            None
196        }
197        StateParse::Corrupt => {
198            eprintln!("truce: state blob is a corrupt truce envelope - load failed");
199            None
200        }
201    }
202}
203
204/// Apply just the parameter values from a deserialized state - the
205/// host-thread-safe subset of [`apply_state`]. Format wrappers call
206/// this from their state-load callback (host main thread) before
207/// pushing the full state onto the audio-thread handoff queue, so
208/// host-thread reads of `getParameter`/equivalents see the restored
209/// values immediately. Validators (auval, pluginval, the VST2 binary
210/// smoke) read parameters synchronously after `setChunk`/equivalents
211/// without first running a render block, and would otherwise see the
212/// pre-restore values until the audio thread caught up.
213///
214/// The extra blob still has to round-trip through the audio thread
215/// because [`crate::plugin::PluginRuntime::load_state`] takes `&mut P`, which
216/// would alias `process()`'s `&mut P` if called from the host thread.
217/// `restore_values` and `snap_smoothers` go through atomic interior
218/// mutability and are safe to call concurrently with `process()`.
219///
220/// `#[persist]` fields are applied here too, and deliberately *not* on the
221/// audio thread: `load_persist` takes a `RwLock::write` / `Mutex::lock`
222/// per persisted field - fields a GUI thread reads at frame rate - so
223/// applying it inside `process()` would let the editor block the audio
224/// thread (priority inversion). It also allocates (deserializing
225/// `String` / `Vec`). Running it on the host thread keeps both off the
226/// real-time path.
227pub fn apply_params<P: truce_params::Params>(params: &P, state: &DeserializedState) {
228    params.restore_values(&state.params);
229    params.load_persist(&state.persist);
230    params.snap_smoothers();
231}
232
233// ---------------------------------------------------------------------------
234// `snapshot_plugin` / `restore_plugin` - high-level helpers wrapping
235// `serialize_state` + `deserialize_state` with the params-collect /
236// restore + custom-state plumbing every host needs to do anyway.
237// ---------------------------------------------------------------------------
238
239use crate::export::{PluginExport, read_custom_state_offthread};
240use truce_params::Params;
241
242/// Errors `restore_plugin` can return.
243///
244/// `Invalid` covers envelope-level failures (missing / wrong magic,
245/// version mismatch, plugin-ID mismatch, truncated body); `LoadState`
246/// covers a successfully-parsed envelope whose extra-state blob the
247/// plugin's [`crate::PluginRuntime::load_state`] rejected. The caller
248/// typically prints a diagnostic and proceeds with default params.
249#[derive(Debug)]
250pub enum RestoreError {
251    /// The bytes don't parse as a state envelope for this plugin.
252    Invalid,
253    /// Envelope parsed but the plugin couldn't interpret its extra
254    /// bytes.
255    LoadState(StateLoadError),
256}
257
258impl std::fmt::Display for RestoreError {
259    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
260        match self {
261            Self::Invalid => f.write_str("state envelope is invalid"),
262            Self::LoadState(e) => write!(f, "plugin load_state failed: {e}"),
263        }
264    }
265}
266
267impl std::error::Error for RestoreError {}
268
269/// Serialize a plugin instance into the canonical state envelope -
270/// parameter values + optional custom-state payload, with the magic /
271/// version / plugin-ID header `serialize_state` writes.
272///
273/// Same shape every format wrapper produces, so a `.state` file
274/// written by one host loads in any other (subject to the
275/// plugin-ID match `deserialize_state` enforces).
276pub fn snapshot_plugin<P: PluginExport>(plugin: &P) -> Vec<u8> {
277    use truce_params::Params;
278    let (ids, values) = plugin.params().collect_values();
279    let extra = read_custom_state_offthread(plugin);
280    let persist = plugin.params().serialize_persist();
281    serialize_state(
282        hash_plugin_id(P::info().clap_id),
283        &ids,
284        &values,
285        &extra,
286        &persist,
287    )
288}
289
290/// Inverse of [`snapshot_plugin`]. Validates the envelope's magic,
291/// version, and plugin-ID hash; on success restores parameter
292/// values via `Params::restore_values` and forwards the optional
293/// extra payload to `Plugin::load_state`.
294///
295/// # Errors
296///
297/// Returns [`RestoreError::Invalid`] if the magic / version /
298/// plugin-ID hash check fails or the envelope is truncated. A
299/// successful return guarantees the params and (optional) extra
300/// payload were forwarded to the plugin.
301pub fn restore_plugin<P: PluginExport>(plugin: &mut P, bytes: &[u8]) -> Result<(), RestoreError> {
302    let id = hash_plugin_id(P::info().clap_id);
303    let s = deserialize_state(bytes, id).ok_or(RestoreError::Invalid)?;
304    plugin.params().restore_values(&s.params);
305    plugin.params().load_persist(&s.persist);
306    if let Some(extra) = s.extra {
307        plugin.load_state(&extra).map_err(RestoreError::LoadState)?;
308    }
309    Ok(())
310}
311
312/// Resolve the state-envelope hash every format wrapper stamps into
313/// the saved blob. Today this is just `hash_plugin_id(info.clap_id)`,
314/// which means the same plugin built as CLAP / VST3 / AU / AAX / VST2
315/// / LV2 produces a single state space - saving in one host and
316/// loading in another will round-trip parameter values (provided the
317/// `Plugin::save_state` / `load_state` extra payload is also
318/// format-agnostic).
319///
320/// **Trade-off:** because the input is the CLAP ID, renaming
321/// `info.clap_id` invalidates **every** saved session across **every**
322/// format. Callers that want format-pinned state (e.g. an AU build
323/// that shouldn't share state with the same plugin's CLAP build)
324/// should add a per-format ID field to [`crate::PluginInfo`] and
325/// route through it instead.
326#[must_use]
327pub fn shared_plugin_state_hash(info: &crate::PluginInfo) -> u64 {
328    hash_plugin_id(info.clap_id)
329}