Skip to main content

rodecaster_protocol/
valuetree.rs

1//! JUCE `ValueTree` data structures and parser.
2//!
3//! When a RØDECaster connects, it transmits its entire device state as a
4//! binary `juce::ValueTreeSynchroniser` full-sync payload. This module parses
5//! that binary representation into a hierarchy of [`Node`] and [`Property`]
6//! structures.
7
8use std::fmt;
9
10use crate::juce_var::{write_compressed_int, Reader, Value};
11
12// Property and Node
13
14/// A property (name-value pair) in the ValueTree.
15#[derive(Debug, Clone, PartialEq)]
16pub struct Property {
17    pub name: String,
18    pub value: Value,
19}
20
21/// A node in the ValueTree (has a name, properties, and child nodes).
22#[derive(Debug, Clone, PartialEq)]
23pub struct Node {
24    pub name: String,
25    pub properties: Vec<Property>,
26    pub children: Vec<Node>,
27}
28
29impl Node {
30    /// Encode this node using JUCE's `ValueTree::writeToStream` format.
31    ///
32    /// This writes the tree body only. Use
33    /// [`crate::change_frame::encode_full_sync`] to prepend the full-sync
34    /// change type, then wrap that payload in a transport packet if needed.
35    pub fn write_to_stream(&self, out: &mut Vec<u8>) {
36        out.extend_from_slice(self.name.as_bytes());
37        out.push(0);
38        write_compressed_int(out, self.properties.len() as i64);
39        for property in &self.properties {
40            out.extend_from_slice(property.name.as_bytes());
41            out.push(0);
42            property.value.write_to_stream(out);
43        }
44        write_compressed_int(out, self.children.len() as i64);
45        for child in &self.children {
46            child.write_to_stream(out);
47        }
48    }
49}
50
51impl fmt::Display for Node {
52    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
53        write!(
54            f,
55            "Node({}, {} props, {} children)",
56            self.name,
57            self.properties.len(),
58            self.children.len()
59        )
60    }
61}
62
63// Tree walk: ValueTree::writeToStream framing over juce_var values.
64
65/// Parse a property: `writeString(name)` then a `juce::var` value.
66fn parse_property(reader: &mut Reader) -> Option<Property> {
67    let name = reader.read_cstring()?.to_string();
68    let value = reader.read_value()?;
69    Some(Property { name, value })
70}
71
72/// Parse one `juce::ValueTree::writeToStream` node from the cursor: name,
73/// property count, properties, child count, children (recursive).
74///
75/// Exposed at crate scope so [`crate::change_frame`] can decode the embedded
76/// ValueTree streams in `FullSync` (after the change-type byte) and
77/// `ChildAdded` (after the path + insertion index) without re-implementing the
78/// tree walk.
79pub(crate) fn parse_node(reader: &mut Reader) -> Option<Node> {
80    // Node name (writeString: UTF-8 + NUL).
81    let name = reader.read_cstring()?.to_string();
82
83    // Property count (writeCompressedInt).
84    let prop_count = usize::try_from(reader.read_compressed_int()?).ok()?;
85    let mut properties = Vec::with_capacity(prop_count.min(reader.remaining()));
86    for _ in 0..prop_count {
87        properties.push(parse_property(reader)?);
88    }
89
90    // Child count (writeCompressedInt), then children recursively. A declared
91    // count is a hard contract: returning a partial tree on truncation would
92    // let a corrupted full sync look valid and build a subtly incomplete
93    // Layout.
94    let child_count = usize::try_from(reader.read_compressed_int()?).ok()?;
95    let mut children = Vec::with_capacity(child_count.min(reader.remaining()));
96    for _ in 0..child_count {
97        children.push(parse_node(reader)?);
98    }
99
100    Some(Node {
101        name,
102        properties,
103        children,
104    })
105}
106
107/// Parse a ValueTree from binary data.
108///
109/// The data is the payload after the RODE transport frame, i.e. the
110/// `juce::ValueTreeSynchroniser` message: a one-byte `ChangeType` header
111/// (`fullSync = 2`) followed by `ValueTree::writeToStream` of the root node.
112pub fn parse_valuetree(data: &[u8]) -> Option<Node> {
113    if data.is_empty() {
114        return None;
115    }
116
117    let mut reader = Reader::new(data);
118
119    // ChangeType::fullSync header byte (juce::ValueTreeSynchroniser).
120    let change_type = reader.read_u8()?;
121    if change_type != 0x02 {
122        return None;
123    }
124
125    // Parse exactly one root node. Trailing bytes are malformed at this layer;
126    // transport framing is responsible for separating adjacent messages.
127    let root = parse_node(&mut reader)?;
128    (reader.remaining() == 0).then_some(root)
129}
130
131// Tests
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    #[test]
138    fn test_parse_simple_property() {
139        // faderLevel = 75: "faderLevel\0" + frame [01][05][01][4b 00 00 00].
140        let data = [
141            0x66, 0x61, 0x64, 0x65, 0x72, 0x4c, 0x65, 0x76, 0x65, 0x6c,
142            0x00, // "faderLevel\0"
143            0x01, // data_len_len
144            0x05, // data_len
145            0x01, // type (int)
146            0x4b, 0x00, 0x00, 0x00, // value = 75
147        ];
148
149        let mut reader = Reader::new(&data);
150        let prop = parse_property(&mut reader).expect("Should parse property");
151        assert_eq!(prop.name, "faderLevel");
152        assert_eq!(prop.value, Value::Int(75));
153    }
154
155    #[test]
156    fn test_parse_boolean_true() {
157        let data = [
158            0x6d, 0x65, 0x74, 0x65, 0x72, 0x53, 0x74, 0x65, 0x72, 0x65, 0x6f,
159            0x00, // "meterStereo\0"
160            0x01, 0x01, 0x02, // var bool true
161        ];
162
163        let mut reader = Reader::new(&data);
164        let prop = parse_property(&mut reader).expect("Should parse property");
165        assert_eq!(prop.name, "meterStereo");
166        assert_eq!(prop.value, Value::Bool(true));
167    }
168
169    #[test]
170    fn test_parse_double() {
171        // meterPeakL = 1.0 (0x3FF0000000000000 LE).
172        let data = [
173            0x6d, 0x65, 0x74, 0x65, 0x72, 0x50, 0x65, 0x61, 0x6b, 0x4c,
174            0x00, // "meterPeakL\0"
175            0x01, 0x09, 0x04, // var double frame
176            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f, // 1.0
177        ];
178
179        let mut reader = Reader::new(&data);
180        let prop = parse_property(&mut reader).expect("Should parse property");
181        assert_eq!(prop.name, "meterPeakL");
182        if let Value::Double(d) = prop.value {
183            assert!((d - 1.0).abs() < 0.0001);
184        } else {
185            panic!("Expected Double value");
186        }
187    }
188
189    #[test]
190    fn test_parse_binary_property() {
191        // mixUnlinkRequest: the real 6-byte binary blob protocol::mix emits.
192        let mut data = b"mixUnlinkRequest\0".to_vec();
193        data.extend_from_slice(&[0x01, 0x07, 0x08, 0x01, 0x01, 0x02, 0x01, 0x01, 0x02]);
194
195        let mut reader = Reader::new(&data);
196        let prop = parse_property(&mut reader).expect("Should parse property");
197        assert_eq!(prop.name, "mixUnlinkRequest");
198        assert_eq!(
199            prop.value,
200            Value::Binary(vec![0x01, 0x01, 0x02, 0x01, 0x01, 0x02])
201        );
202    }
203
204    #[test]
205    fn node_stream_round_trips() {
206        let node = Node {
207            name: "ROOT".to_string(),
208            properties: vec![Property {
209                name: "name".to_string(),
210                value: Value::String("fixture".to_string()),
211            }],
212            children: vec![Node {
213                name: "CHILD".to_string(),
214                properties: vec![Property {
215                    name: "enabled".to_string(),
216                    value: Value::Bool(true),
217                }],
218                children: vec![],
219            }],
220        };
221        let mut bytes = Vec::new();
222        node.write_to_stream(&mut bytes);
223        let mut reader = Reader::new(&bytes);
224        assert_eq!(parse_node(&mut reader), Some(node));
225        assert_eq!(reader.remaining(), 0);
226    }
227
228    #[test]
229    fn test_node_display() {
230        let node = Node {
231            name: "FADER".to_string(),
232            properties: vec![
233                Property {
234                    name: "faderLevel".to_string(),
235                    value: Value::Int(75),
236                },
237                Property {
238                    name: "channelOutputMute".to_string(),
239                    value: Value::Bool(false),
240                },
241            ],
242            children: vec![],
243        };
244        assert_eq!(node.to_string(), "Node(FADER, 2 props, 0 children)");
245    }
246}