Skip to main content

truce_utils/
state.rs

1//! Canonical plugin-state wire format.
2//!
3//! Lives in `truce-utils` (rather than `truce-core`) so build-time
4//! tools - `cargo-truce` emits factory-preset files containing this
5//! envelope at install time - can produce byte-identical blobs
6//! without inheriting `truce-core`'s runtime dependency chain.
7//! `truce-core::state` re-exports everything here and layers the
8//! plugin-coupled helpers (`apply_state`, `snapshot_plugin`, ...)
9//! on top.
10
11/// Magic bytes for state identification.
12const STATE_MAGIC: &[u8; 4] = b"OAST";
13const STATE_VERSION: u32 = 1;
14
15/// Serialize plugin state: parameter values + extra state. Empty
16/// `extra` slice serializes as the same `0u64` length-prefix that an
17/// absent extra block would, so callers don't need an `Option`
18/// wrapper to express "no extra state".
19#[must_use]
20pub fn serialize_state(
21    plugin_id_hash: u64,
22    param_ids: &[u32],
23    param_values: &[f64],
24    extra: &[u8],
25) -> Vec<u8> {
26    let mut data = Vec::new();
27
28    // Header
29    data.extend_from_slice(STATE_MAGIC);
30    data.extend_from_slice(&STATE_VERSION.to_le_bytes());
31    data.extend_from_slice(&plugin_id_hash.to_le_bytes());
32
33    // Parameter block
34    let count = crate::cast::len_u32(param_ids.len());
35    data.extend_from_slice(&count.to_le_bytes());
36    for (id, value) in param_ids.iter().zip(param_values.iter()) {
37        data.extend_from_slice(&id.to_le_bytes());
38        data.extend_from_slice(&value.to_le_bytes());
39    }
40
41    // Extra state block: length-prefixed, may be zero-length.
42    let len = extra.len() as u64;
43    data.extend_from_slice(&len.to_le_bytes());
44    data.extend_from_slice(extra);
45
46    data
47}
48
49/// Deserialized state.
50pub struct DeserializedState {
51    pub params: Vec<(u32, f64)>,
52    pub extra: Option<Vec<u8>>,
53}
54
55/// Outcome of [`parse_state`]: what the bytes turned out to be.
56/// Splits the causes [`deserialize_state`] collapses into one `None`
57/// so callers can route each one differently (fail the load, offer
58/// the bytes to the plugin's `migrate_state` hook, ...).
59pub enum StateParse {
60    Ok(DeserializedState),
61    /// Wrong magic / too short to carry the header: not a truce
62    /// envelope at all. Candidate for legacy-state migration.
63    NotAnEnvelope,
64    /// Valid magic, `version` field newer than this build understands.
65    /// Reserved for truce-side envelope evolution: never handed to
66    /// the plugin, the load fails with a distinct log line.
67    UnknownVersion(u32),
68    /// Structurally valid envelope whose `plugin_id_hash` isn't the
69    /// expected one - a renamed / re-identified plugin. Params and
70    /// extra are already decoded; the caller decides whether to
71    /// offer them to the plugin.
72    WrongPlugin {
73        found: u64,
74        state: DeserializedState,
75    },
76    /// Magic + version matched but the param / extra blocks are
77    /// truncated or inconsistent. Never migrated, the load fails.
78    Corrupt,
79}
80
81/// Deserialize plugin state. Thin wrapper over [`parse_state`] for
82/// callers that only care about the strict-success case (preset
83/// codecs, tests).
84#[must_use]
85pub fn deserialize_state(data: &[u8], expected_plugin_id: u64) -> Option<DeserializedState> {
86    match parse_state(data, expected_plugin_id) {
87        StateParse::Ok(state) => Some(state),
88        _ => None,
89    }
90}
91
92/// Parse a state blob, distinguishing every failure cause. See
93/// [`StateParse`] for the routing each variant is meant for.
94#[must_use]
95pub fn parse_state(data: &[u8], expected_plugin_id: u64) -> StateParse {
96    if data.len() < 8 || &data[0..4] != STATE_MAGIC {
97        return StateParse::NotAnEnvelope;
98    }
99
100    let Ok(version_bytes) = data[4..8].try_into() else {
101        return StateParse::NotAnEnvelope;
102    };
103    let version = u32::from_le_bytes(version_bytes);
104    if version != STATE_VERSION {
105        return StateParse::UnknownVersion(version);
106    }
107
108    // From here on the bytes claim to be a current-version envelope:
109    // any structural violation is corruption, not foreign data.
110    let Some(id_bytes) = data.get(8..16) else {
111        return StateParse::Corrupt;
112    };
113    let Ok(id_bytes) = id_bytes.try_into() else {
114        return StateParse::Corrupt;
115    };
116    let plugin_id = u64::from_le_bytes(id_bytes);
117
118    let mut offset = 16;
119
120    // Parameter block
121    if offset + 4 > data.len() {
122        return StateParse::Corrupt;
123    }
124    let Ok(count_bytes) = data[offset..offset + 4].try_into() else {
125        return StateParse::Corrupt;
126    };
127    let count = u32::from_le_bytes(count_bytes) as usize;
128    offset += 4;
129
130    // Cap the pre-allocation by what the remaining buffer could
131    // possibly hold. Each entry is 12 bytes (`u32 id` + `f64 value`),
132    // so a hostile or corrupted blob with `count = u32::MAX` (≈64 GB
133    // request) is clamped to at most the remaining byte budget. The
134    // per-iteration bounds check below still rejects entries that
135    // overrun the buffer; this just keeps the up-front allocation
136    // honest.
137    let max_count = data.len().saturating_sub(offset) / 12;
138    let mut params = Vec::with_capacity(count.min(max_count));
139    for _ in 0..count {
140        if offset + 12 > data.len() {
141            return StateParse::Corrupt;
142        }
143        let Ok(id_bytes) = data[offset..offset + 4].try_into() else {
144            return StateParse::Corrupt;
145        };
146        let id = u32::from_le_bytes(id_bytes);
147        offset += 4;
148        let Ok(value_bytes) = data[offset..offset + 8].try_into() else {
149            return StateParse::Corrupt;
150        };
151        let value = f64::from_le_bytes(value_bytes);
152        offset += 8;
153        params.push((id, value));
154    }
155
156    // Extra state block
157    if offset + 8 > data.len() {
158        return StateParse::Corrupt;
159    }
160    let Ok(len_bytes) = data[offset..offset + 8].try_into() else {
161        return StateParse::Corrupt;
162    };
163    // The wire format encodes `extra_len` as `u64`; on 32-bit
164    // targets the cast may truncate, but the next branch validates
165    // `offset.checked_add(extra_len)` against the buffer length.
166    #[allow(clippy::cast_possible_truncation)]
167    let extra_len = u64::from_le_bytes(len_bytes) as usize;
168    offset += 8;
169
170    let extra = if extra_len > 0 {
171        // `offset + extra_len` can wrap to a small value when
172        // `extra_len` is huge (host-supplied), making the comparison
173        // pass even though the slice would overrun. Use `checked_add`
174        // and reject overflow as malformed.
175        match offset.checked_add(extra_len) {
176            Some(end) if end <= data.len() => Some(data[offset..end].to_vec()),
177            _ => return StateParse::Corrupt,
178        }
179    } else {
180        None
181    };
182
183    let state = DeserializedState { params, extra };
184    if plugin_id == expected_plugin_id {
185        StateParse::Ok(state)
186    } else {
187        StateParse::WrongPlugin {
188            found: plugin_id,
189            state,
190        }
191    }
192}
193
194/// Compute a simple hash of the plugin ID string for state identification.
195///
196/// Uses FNV-1a-64. **Do not change this without bumping the envelope's
197/// `STATE_VERSION` and writing a migration:** the returned hash is
198/// stored verbatim in every `.pluginstate` blob the host has saved,
199/// and a different algorithm here would invalidate every shipped
200/// session. If a stronger hash is ever needed, it must be selected via
201/// the version byte in the envelope, not by replacing this function in
202/// place.
203#[must_use]
204pub fn hash_plugin_id(id: &str) -> u64 {
205    let mut hash: u64 = 0xcbf2_9ce4_8422_2325; // FNV-1a offset basis
206    for byte in id.bytes() {
207        hash ^= u64::from(byte);
208        hash = hash.wrapping_mul(0x0100_0000_01b3); // FNV prime
209    }
210    hash
211}
212
213/// The 16-byte VST3 class ID for a plugin ID string.
214///
215/// FNV-1a-128, per <http://www.isthe.com/chongo/tech/comp/fnv/>.
216/// Standard constants - DAWs persist this CID as the plugin's identity
217/// in saved sessions and `.vstpreset` files, so the algorithm and
218/// constants must stay stable across releases. `truce-vst3` reports
219/// this as the component's TUID; `cargo-truce` stamps the same bytes
220/// (hex-encoded) into emitted `.vstpreset` headers.
221#[must_use]
222pub fn vst3_cid(id: &str) -> [u8; 16] {
223    const FNV_OFFSET_BASIS: u128 = 0x6C62_272E_07BB_0142_62B8_2175_6295_C58D;
224    const FNV_PRIME: u128 = 0x0000_0000_0100_0000_0000_0000_0000_013B;
225    let mut hash = FNV_OFFSET_BASIS;
226    for byte in id.bytes() {
227        hash ^= u128::from(byte);
228        hash = hash.wrapping_mul(FNV_PRIME);
229    }
230    hash.to_le_bytes()
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236
237    #[test]
238    fn round_trip_state() {
239        let plugin_id = hash_plugin_id("com.test.plugin");
240        let ids = [0u32, 1, 2];
241        let values = [0.5f64, 1.0, -12.0];
242        let extra = b"hello extra state";
243
244        let data = serialize_state(plugin_id, &ids, &values, extra);
245        let state = deserialize_state(&data, plugin_id).unwrap();
246
247        assert_eq!(state.params.len(), 3);
248        assert_eq!(state.params[0], (0, 0.5));
249        assert_eq!(state.params[1], (1, 1.0));
250        assert_eq!(state.params[2], (2, -12.0));
251        assert_eq!(state.extra.unwrap(), b"hello extra state");
252    }
253
254    #[test]
255    fn wrong_plugin_id_fails() {
256        let plugin_id = hash_plugin_id("com.test.plugin");
257        let data = serialize_state(plugin_id, &[], &[], &[]);
258        assert!(deserialize_state(&data, 12345).is_none());
259    }
260
261    #[test]
262    fn parse_distinguishes_foreign_bytes() {
263        assert!(matches!(
264            parse_state(b"{\"legacy\":true}", 1),
265            StateParse::NotAnEnvelope
266        ));
267        assert!(matches!(parse_state(b"", 1), StateParse::NotAnEnvelope));
268        assert!(matches!(parse_state(b"OAS", 1), StateParse::NotAnEnvelope));
269    }
270
271    #[test]
272    fn parse_distinguishes_future_version() {
273        let mut data = serialize_state(1, &[], &[], &[]);
274        data[4..8].copy_from_slice(&2u32.to_le_bytes());
275        assert!(matches!(
276            parse_state(&data, 1),
277            StateParse::UnknownVersion(2)
278        ));
279    }
280
281    #[test]
282    fn parse_decodes_wrong_plugin_envelope() {
283        let data = serialize_state(99, &[7], &[0.25], b"extra");
284        match parse_state(&data, 1) {
285            StateParse::WrongPlugin { found, state } => {
286                assert_eq!(found, 99);
287                assert_eq!(state.params, vec![(7, 0.25)]);
288                assert_eq!(state.extra.as_deref(), Some(&b"extra"[..]));
289            }
290            _ => panic!("expected WrongPlugin"),
291        }
292    }
293
294    #[test]
295    fn parse_flags_truncated_envelope_as_corrupt() {
296        let data = serialize_state(1, &[7, 8], &[0.25, 0.5], b"extra");
297        // Cut inside the param block: valid header, broken body.
298        assert!(matches!(parse_state(&data[..22], 1), StateParse::Corrupt));
299    }
300}