Skip to main content

rodecaster_protocol/
layout.rs

1//! Dynamic device topology discovery and address translation.
2//!
3//! RØDECaster devices do not use fixed, static wire addresses across models
4//! and firmware versions. Instead, the console sends a full state tree
5//! (`fullSync`) when connected.
6//!
7//! [`Layout`] inspects this tree to discover where physical faders, channels,
8//! audio inputs, and mix routing nodes reside. High-level commands and events
9//! use [`Layout`] to translate between human-readable domain names (such as
10//! [`crate::Fader::Physical1`]) and the exact numeric node indices on the wire.
11//!
12//! Most applications do not need to construct or query [`Layout`] directly:
13//! [`crate::ProtocolSession`] manages the active layout automatically.
14
15use crate::juce_var::Value;
16use crate::names::DeviceModel;
17use crate::valuetree::Node;
18
19/// Mix destinations per source in the RODECaster Pro II / Duo mix matrix
20/// (firmware 1.7.3 observation).
21///
22/// This is a **device characteristic**, not a JUCE protocol fact. The total
23/// `MIX` node count factors as `source_count * mix_count_per_source`; one
24/// dimension cannot be uniquely recovered from the fullSync alone, so this
25/// constant pins it. If newer firmware changes the matrix width, expose an
26/// override here.
27pub const MIX_COUNT_PER_SOURCE: u8 = 13;
28
29/// One addressable singleton node (no index): its tree position, or absent.
30///
31/// `MASTERCHANNEL`, `OUTPUT`, `DUCKER`, `RECORDER`, `PLAYER`, `GUI` and `SYSTEM`
32/// are all one-of-a-kind nodes addressed purely by position. `None` means the
33/// fullSync did not carry the node (synthetic or partial trees).
34#[derive(Debug, Clone, PartialEq)]
35struct Singleton {
36    idx: Option<u32>,
37}
38
39impl Singleton {
40    /// Root-down single-element path to the node, if present.
41    fn path(&self) -> Option<Vec<u32>> {
42        self.idx.map(|p| vec![p])
43    }
44
45    /// True if this single-level path points at the node.
46    fn is_path(&self, path: &[u32]) -> bool {
47        matches!((self.idx, path), (Some(i), [p]) if *p == i)
48    }
49}
50
51/// A contiguous run of same-named nodes under root, addressed by a single-level
52/// path `[first + n]`. `first` is `None` when the run is absent (which, since a
53/// found node always has at least one consecutive entry, is the same as
54/// `count == 0`).
55///
56/// `CHANNEL`, `INPUTSOURCE`, `HEADPHONE` and the root `EFFECTS_PARAMETERS` run
57/// share this shape: the ordinal within the run is the logical index.
58#[derive(Debug, Clone, PartialEq)]
59struct Indexed {
60    first: Option<u32>,
61    count: u8,
62}
63
64impl Indexed {
65    /// Root-down path to the `n`th node in the run, or `None` if `n` is past the
66    /// run or the run is absent.
67    fn path(&self, n: u8) -> Option<Vec<u32>> {
68        let first = self.first?;
69        if n >= self.count {
70            return None;
71        }
72        Some(vec![first + n as u32])
73    }
74
75    /// Inverse of [`Indexed::path`]: the ordinal this single-level path
76    /// identifies, if it falls inside the run.
77    fn index_from_path(&self, path: &[u32]) -> Option<u8> {
78        let first = self.first?;
79        if path.len() != 1 {
80            return None;
81        }
82        let p = path[0];
83        if p < first {
84            return None;
85        }
86        let n = p - first;
87        if n >= self.count as u32 {
88            return None;
89        }
90        Some(n as u8)
91    }
92}
93
94/// A contiguous run of same-named child nodes under a parent container,
95/// addressed by a two-level path `[parent, first + n]`. `parent` is `None` when
96/// the container is absent; `count` can be 0 even when the container exists
97/// (e.g. a `SOUNDPADS` node with no `PAD` children), so parent presence is
98/// tracked independently of the run length.
99///
100/// `FADER` (under `PHYSICALINTERFACE`) and `PAD` (under `SOUNDPADS`) share this
101/// shape.
102#[derive(Debug, Clone, PartialEq)]
103struct TwoLevel {
104    parent: Option<u32>,
105    first: u32,
106    count: u8,
107}
108
109impl TwoLevel {
110    /// Root-down two-level path to the `n`th child, or `None` if `n` is past the
111    /// run or the container is absent.
112    fn path(&self, n: u8) -> Option<Vec<u32>> {
113        let parent = self.parent?;
114        if n >= self.count {
115            return None;
116        }
117        Some(vec![parent, self.first + n as u32])
118    }
119
120    /// Inverse of [`TwoLevel::path`]: the ordinal this two-level path identifies,
121    /// if its parent matches and it falls inside the run.
122    fn index_from_path(&self, path: &[u32]) -> Option<u8> {
123        let parent = self.parent?;
124        if path.len() != 2 || path[0] != parent {
125            return None;
126        }
127        let p = path[1];
128        if p < self.first {
129            return None;
130        }
131        let n = p - self.first;
132        if n >= self.count as u32 {
133            return None;
134        }
135        Some(n as u8)
136    }
137}
138
139/// Tree positions of the addressable node families. All fields are
140/// discovered, not hardcoded.
141#[derive(Debug, Clone, PartialEq)]
142pub struct Layout {
143    model: DeviceModel,
144    // CHANNEL: a required single-level run at root (so `first` is always `Some`).
145    channel: Indexed,
146    // MIX: a 2D source-major matrix at root. Bespoke stride arithmetic, so it is
147    // not one of the generic addressing shapes. `source_count` is the first
148    // matrix dimension; the second is MIX_COUNT_PER_SOURCE.
149    first_mix: u32,
150    source_count: u8,
151    // FADER under PHYSICALINTERFACE: a required two-level run.
152    fader: TwoLevel,
153    // INPUTSOURCE / HEADPHONE / root EFFECTS_PARAMETERS: optional single-level
154    // runs at root. Absent (synthetic or partial trees) -> `first` is `None` and
155    // addressing simply returns `None` (no panic, no misroute).
156    input_source: Indexed,
157    headphone: Indexed,
158    effects: Indexed,
159    // MASTERCHANNEL / OUTPUT / DUCKER / RECORDER / PLAYER / GUI / SYSTEM: root
160    // singletons, each addressed by position with no index. Optional for the
161    // same reason.
162    master_channel: Singleton,
163    output: Singleton,
164    ducker: Singleton,
165    recorder: Singleton,
166    player: Singleton,
167    gui: Singleton,
168    system: Singleton,
169    // PAD under SOUNDPADS: an optional two-level run (mirrors FADER). The
170    // container can exist with zero pads, so its presence is tracked separately
171    // from the run length.
172    pad: TwoLevel,
173    // SIP subsystem. SIPCALLING and SIPADVANCED are singletons at root; the
174    // SIPCALLSLOTS run holds one node per configured call slot (three on the
175    // Duo); SIPREGISTRATION nodes are children of SIPCALLING (two on the Duo).
176    sip_calling: Singleton,
177    sip_advanced: Singleton,
178    sip_call_slots: Indexed,
179    sip_registration: TwoLevel,
180    // TEST: factory-diagnostic singleton at root.
181    test: Singleton,
182    // PADRECORDER: a run at root (one node per pad recorder instance).
183    pad_recorder: Indexed,
184    // FXPRESET: two-level under the FXPRESETS container at root.
185    fx_preset: TwoLevel,
186    // Singletons at root.
187    network: Singleton,
188    audio: Singleton,
189    build: Singleton,
190    app: Singleton,
191    theme: Singleton,
192    current_show: Singleton,
193    show_control: Singleton,
194    recordings: Singleton,
195    radio: Singleton,
196    // Container-level and indexed runs.
197    show: TwoLevel,
198    recording: TwoLevel,
199    storage_volume: Indexed,
200    radio_tx: Indexed,
201    radio_rx: Indexed,
202    wifi_scan_result: Indexed,
203    streamerx_mix_preset: Indexed,
204    streamerx_stream_mix: Indexed,
205    rcsync_mix: Indexed,
206    mix_minuses: Indexed,
207}
208
209macro_rules! impl_singleton {
210    ($field:ident, $path_fn:ident, $is_path_fn:ident) => {
211        pub fn $path_fn(&self) -> Option<Vec<u32>> {
212            self.$field.path()
213        }
214        pub fn $is_path_fn(&self, path: &[u32]) -> bool {
215            self.$field.is_path(path)
216        }
217    };
218}
219
220macro_rules! impl_run {
221    ($field:ident, $path_fn:ident, $index_fn:ident, $count_fn:ident) => {
222        pub fn $path_fn(&self, n: u8) -> Option<Vec<u32>> {
223            self.$field.path(n)
224        }
225        pub fn $index_fn(&self, path: &[u32]) -> Option<u8> {
226            self.$field.index_from_path(path)
227        }
228        pub fn $count_fn(&self) -> u8 {
229            self.$field.count
230        }
231    };
232}
233
234impl Layout {
235    /// Walk a parsed fullSync root and discover the layout.
236    ///
237    /// Fails loudly on missing required nodes so a future firmware layout
238    /// change surfaces immediately rather than silently misrouting.
239    pub fn from_full_sync(root: &Node) -> Result<Layout, BuildError> {
240        // Device model from the SYSTEM node (boardType primary, systemName
241        // fallback). Absent on synthetic trees and old firmware -> Pro II.
242        let model = detect_model(root);
243
244        // PHYSICALINTERFACE under root, with FADER children inside it (required,
245        // two-level).
246        let physical_interface_idx = position_of_named_child(root, "PHYSICALINTERFACE")
247            .ok_or(BuildError::MissingNode("PHYSICALINTERFACE under root"))?;
248        let phys = &root.children[physical_interface_idx as usize];
249        let first_fader_in_phys = position_of_named_child(phys, "FADER")
250            .ok_or(BuildError::MissingNode("FADER under PHYSICALINTERFACE"))?;
251        let fader = TwoLevel {
252            parent: Some(physical_interface_idx),
253            first: first_fader_in_phys,
254            count: count_consecutive_named(phys, first_fader_in_phys, "FADER"),
255        };
256
257        // CHANNEL nodes under root (required, single-level).
258        let first_channel = position_of_named_child(root, "CHANNEL")
259            .ok_or(BuildError::MissingNode("CHANNEL under root"))?;
260        let channel = Indexed {
261            first: Some(first_channel),
262            count: count_consecutive_named(root, first_channel, "CHANNEL"),
263        };
264
265        // MIX nodes under root. Count, then factor by MIX_COUNT_PER_SOURCE.
266        let first_mix = position_of_named_child(root, "MIX")
267            .ok_or(BuildError::MissingNode("MIX under root"))?;
268        let mix_total = count_consecutive_named_u32(root, first_mix, "MIX");
269        if mix_total == 0 || !mix_total.is_multiple_of(MIX_COUNT_PER_SOURCE as u32) {
270            return Err(BuildError::ShapeMismatch {
271                what: "MIX",
272                detail: format!(
273                    "expected mix_total divisible by MIX_COUNT_PER_SOURCE={}, got {}",
274                    MIX_COUNT_PER_SOURCE, mix_total
275                ),
276            });
277        }
278        let source_count = u8::try_from(mix_total / MIX_COUNT_PER_SOURCE as u32).map_err(|_| {
279            BuildError::ShapeMismatch {
280                what: "MIX",
281                detail: format!("source_count overflows u8 (mix_total={mix_total})"),
282            }
283        })?;
284
285        // INPUTSOURCE nodes under root (optional, single-level). The first
286        // contiguous run holds the addressable sources; its ordinal == the
287        // device's `inputId` == `Source::to_protocol`. A second run (rcSync /
288        // streamer-x placeholders) follows on some devices and is deliberately
289        // not counted (discover_run takes only the first run).
290        let input_source = discover_run(root, "INPUTSOURCE");
291
292        // HEADPHONE nodes under root (optional, single-level, multi-instance).
293        // One node per physical headphone jack; the ordinal in the run is the
294        // headphone index.
295        let headphone = discover_run(root, "HEADPHONE");
296
297        // EFFECTS_PARAMETERS nodes under root (optional, single-level). The first
298        // contiguous run at root is the per-channel-strip effects slots; the
299        // ordinal in the run is the slot index (== the node's `effectsIdx`). The
300        // PADEFFECTS node nests its own EFFECTS_PARAMETERS set elsewhere in the
301        // tree; only the root run is counted here.
302        let effects = discover_run(root, "EFFECTS_PARAMETERS");
303
304        // MASTERCHANNEL, OUTPUT, DUCKER, RECORDER, PLAYER, GUI and SYSTEM are
305        // singletons under root; record each position if present (None on
306        // synthetic/partial trees).
307        let master_channel = Singleton {
308            idx: position_of_named_child(root, "MASTERCHANNEL"),
309        };
310        let output = Singleton {
311            idx: position_of_named_child(root, "OUTPUT"),
312        };
313        let ducker = Singleton {
314            idx: position_of_named_child(root, "DUCKER"),
315        };
316        let recorder = Singleton {
317            idx: position_of_named_child(root, "RECORDER"),
318        };
319        let player = Singleton {
320            idx: position_of_named_child(root, "PLAYER"),
321        };
322        let gui = Singleton {
323            idx: position_of_named_child(root, "GUI"),
324        };
325        // SYSTEM is the device-wide state singleton. `detect_model` reads the
326        // same node by name independently; this records its position so SYSTEM
327        // properties are addressable like any other singleton family.
328        let system = Singleton {
329            idx: position_of_named_child(root, "SYSTEM"),
330        };
331
332        // TEST diagnostic singleton at root.
333        let test = Singleton {
334            idx: position_of_named_child(root, "TEST"),
335        };
336
337        // PADRECORDER: a run at root (one per pad recorder instance).
338        let pad_recorder = discover_run(root, "PADRECORDER");
339
340        // FXPRESET: two-level under FXPRESETS container at root.
341        let fx_preset = discover_two_level(root, "FXPRESETS", "FXPRESET");
342
343        // SIP subsystem discovery.
344        let sip_calling = Singleton {
345            idx: position_of_named_child(root, "SIPCALLING"),
346        };
347        let sip_advanced = Singleton {
348            idx: position_of_named_child(root, "SIPADVANCED"),
349        };
350        let sip_call_slots = discover_run(root, "SIPCALLSLOTS");
351        let sip_registration = discover_two_level(root, "SIPCALLING", "SIPREGISTRATION");
352
353        // SOUNDPADS container under root.
354        let pad = discover_two_level(root, "SOUNDPADS", "PAD");
355
356        // Root singletons.
357        let network = Singleton {
358            idx: position_of_named_child(root, "NETWORK"),
359        };
360        let audio = Singleton {
361            idx: position_of_named_child(root, "AUDIO"),
362        };
363        let build = Singleton {
364            idx: position_of_named_child(root, "BUILD"),
365        };
366        let app = Singleton {
367            idx: position_of_named_child(root, "APP"),
368        };
369        let theme = Singleton {
370            idx: position_of_named_child(root, "THEME"),
371        };
372        let current_show = Singleton {
373            idx: position_of_named_child(root, "CURRENTSHOW"),
374        };
375        let show_control = Singleton {
376            idx: position_of_named_child(root, "SHOWCONTROL"),
377        };
378        let recordings = Singleton {
379            idx: position_of_named_child(root, "RECORDINGS"),
380        };
381        let radio = Singleton {
382            idx: position_of_named_child(root, "RADIO"),
383        };
384
385        // Container-nested runs.
386        let show = discover_two_level(root, "SHOWS", "SHOW");
387        let recording = discover_two_level(root, "RECORDINGS", "RECORDING");
388
389        // Single-level runs at root.
390        let storage_volume = discover_run(root, "STORAGEVOLUME");
391        let radio_tx = discover_run(root, "RADIOTX");
392        let radio_rx = discover_run(root, "RADIORX");
393        let wifi_scan_result = discover_run(root, "WIFISCANRESULT");
394        let streamerx_mix_preset = discover_run(root, "STREAMERXMIXPRESET");
395        let streamerx_stream_mix = discover_run(root, "STREAMERXSTREAMMIX");
396        let rcsync_mix = discover_run(root, "RCSYNCMIX");
397        let mix_minuses = discover_run(root, "MIXMINUSES");
398
399        Ok(Layout {
400            model,
401            channel,
402            first_mix,
403            source_count,
404            fader,
405            input_source,
406            headphone,
407            effects,
408            master_channel,
409            output,
410            ducker,
411            recorder,
412            player,
413            gui,
414            system,
415            pad,
416            sip_calling,
417            sip_advanced,
418            sip_call_slots,
419            sip_registration,
420            test,
421            pad_recorder,
422            fx_preset,
423            network,
424            audio,
425            build,
426            app,
427            theme,
428            current_show,
429            show_control,
430            recordings,
431            radio,
432            show,
433            recording,
434            storage_volume,
435            radio_tx,
436            radio_rx,
437            wifi_scan_result,
438            streamerx_mix_preset,
439            streamerx_stream_mix,
440            rcsync_mix,
441            mix_minuses,
442        })
443    }
444
445    /// Which RODECaster this layout was discovered from. Selects the per-model
446    /// [`crate::Fader`] mapping when resolving typed commands and events.
447    pub fn model(&self) -> DeviceModel {
448        self.model
449    }
450
451    pub fn physical_interface_idx(&self) -> u32 {
452        // FADER (and thus its PHYSICALINTERFACE parent) is required, so any built
453        // Layout has a parent here.
454        self.fader
455            .parent
456            .expect("PHYSICALINTERFACE present in every built Layout")
457    }
458    pub fn first_fader_in_phys(&self) -> u32 {
459        self.fader.first
460    }
461    pub fn fader_count(&self) -> u8 {
462        self.fader.count
463    }
464    pub fn first_channel(&self) -> u32 {
465        // CHANNEL is required, so any built Layout has a first index here.
466        self.channel
467            .first
468            .expect("CHANNEL present in every built Layout")
469    }
470    pub fn channel_count(&self) -> u8 {
471        self.channel.count
472    }
473    pub fn first_mix(&self) -> u32 {
474        self.first_mix
475    }
476    pub fn source_count(&self) -> u8 {
477        self.source_count
478    }
479    pub fn mix_count_per_source(&self) -> u8 {
480        MIX_COUNT_PER_SOURCE
481    }
482    /// Index of the first `INPUTSOURCE` node under root, if the fullSync had any.
483    pub fn first_input_source(&self) -> Option<u32> {
484        self.input_source.first
485    }
486    /// Number of addressable `INPUTSOURCE` nodes (the first contiguous run).
487    pub fn input_source_count(&self) -> u8 {
488        self.input_source.count
489    }
490    /// Index of the single `MASTERCHANNEL` node under root, if present.
491    pub fn master_channel(&self) -> Option<u32> {
492        self.master_channel.idx
493    }
494    /// Index of the single `OUTPUT` node under root, if present.
495    pub fn output(&self) -> Option<u32> {
496        self.output.idx
497    }
498    /// Index of the single `DUCKER` node under root, if present.
499    pub fn ducker(&self) -> Option<u32> {
500        self.ducker.idx
501    }
502    /// Index of the single `RECORDER` node under root, if present.
503    pub fn recorder(&self) -> Option<u32> {
504        self.recorder.idx
505    }
506    /// Index of the single `PLAYER` node under root, if present.
507    pub fn player(&self) -> Option<u32> {
508        self.player.idx
509    }
510    /// Index of the first `HEADPHONE` node under root, if the fullSync had any.
511    pub fn first_headphone(&self) -> Option<u32> {
512        self.headphone.first
513    }
514    /// Number of addressable `HEADPHONE` nodes (one per physical jack).
515    pub fn headphone_count(&self) -> u8 {
516        self.headphone.count
517    }
518    /// Index of the first root `EFFECTS_PARAMETERS` node, if the fullSync had any.
519    pub fn first_effects(&self) -> Option<u32> {
520        self.effects.first
521    }
522    /// Number of addressable `EFFECTS_PARAMETERS` slots (the first root run).
523    pub fn effects_count(&self) -> u8 {
524        self.effects.count
525    }
526    /// Index of the single `GUI` (front-panel UI state) node under root, if present.
527    pub fn gui(&self) -> Option<u32> {
528        self.gui.idx
529    }
530    /// Index of the single `SYSTEM` (device-wide state) node under root, if present.
531    pub fn system(&self) -> Option<u32> {
532        self.system.idx
533    }
534    /// Index of the `SOUNDPADS` container node under root, if present.
535    pub fn soundpads(&self) -> Option<u32> {
536        self.pad.parent
537    }
538    /// Offset of the first `PAD` node inside the `SOUNDPADS` container.
539    pub fn first_pad(&self) -> u32 {
540        self.pad.first
541    }
542    /// Number of `PAD` nodes in the contiguous run inside `SOUNDPADS`.
543    pub fn pad_count(&self) -> u8 {
544        self.pad.count
545    }
546
547    // Core hardware and routing paths
548
549    /// Root-down path to the `n`th `CHANNEL` node (single-level).
550    pub fn channel_path(&self, n: u8) -> Option<Vec<u32>> {
551        self.channel.path(n)
552    }
553
554    /// Inverse of `channel_path`: channel index from single-level path.
555    pub fn channel_index_from_path(&self, path: &[u32]) -> Option<u8> {
556        self.channel.index_from_path(path)
557    }
558
559    /// Root-down path to the `n`th `FADER` strip inside `PHYSICALINTERFACE` (two-level).
560    pub fn fader_path(&self, n: u8) -> Option<Vec<u32>> {
561        self.fader.path(n)
562    }
563
564    /// Inverse of `fader_path`: fader index from two-level path.
565    pub fn fader_index_from_path(&self, path: &[u32]) -> Option<u8> {
566        self.fader.index_from_path(path)
567    }
568
569    /// Root-down path to the `n`th `PAD` strip inside `SOUNDPADS` (two-level).
570    pub fn pad_path(&self, n: u8) -> Option<Vec<u32>> {
571        self.pad.path(n)
572    }
573
574    /// Inverse of `pad_path`: pad index from two-level path.
575    pub fn pad_index_from_path(&self, path: &[u32]) -> Option<u8> {
576        self.pad.index_from_path(path)
577    }
578
579    /// Root-down path to the `n`th `INPUTSOURCE` node (single-level).
580    pub fn input_source_path(&self, n: u8) -> Option<Vec<u32>> {
581        self.input_source.path(n)
582    }
583
584    /// Inverse of `input_source_path`: which input-source ordinal does this path identify?
585    pub fn input_source_index_from_path(&self, path: &[u32]) -> Option<u8> {
586        self.input_source.index_from_path(path)
587    }
588
589    /// Root-down path to the `n`th `HEADPHONE` node (single-level).
590    pub fn headphone_path(&self, n: u8) -> Option<Vec<u32>> {
591        self.headphone.path(n)
592    }
593
594    /// Inverse of `headphone_path`: headphone index from single-level path.
595    pub fn headphone_index_from_path(&self, path: &[u32]) -> Option<u8> {
596        self.headphone.index_from_path(path)
597    }
598
599    /// Root-down path to the `n`th root `EFFECTS_PARAMETERS` node (single-level).
600    pub fn effects_path(&self, n: u8) -> Option<Vec<u32>> {
601        self.effects.path(n)
602    }
603
604    /// Inverse of `effects_path`: effects-slot index from single-level path.
605    pub fn effects_index_from_path(&self, path: &[u32]) -> Option<u8> {
606        self.effects.index_from_path(path)
607    }
608
609    /// Root-down path to the `MIX` cell at (`source`, `mix`), source-major layout.
610    pub fn mix_cell_path(&self, source: u8, mix: u8) -> Option<Vec<u32>> {
611        if source >= self.source_count || mix >= MIX_COUNT_PER_SOURCE {
612            return None;
613        }
614        Some(vec![
615            self.first_mix + source as u32 * MIX_COUNT_PER_SOURCE as u32 + mix as u32,
616        ])
617    }
618
619    /// Inverse of `mix_cell_path`: which (source, mix) cell, if any?
620    pub fn mix_cell_from_path(&self, path: &[u32]) -> Option<(u8, u8)> {
621        if path.len() != 1 {
622            return None;
623        }
624        let p = path[0];
625        if p < self.first_mix {
626            return None;
627        }
628        let offset = p - self.first_mix;
629        let span = self.source_count as u32 * MIX_COUNT_PER_SOURCE as u32;
630        if offset >= span {
631            return None;
632        }
633        let source = (offset / MIX_COUNT_PER_SOURCE as u32) as u8;
634        let mix = (offset % MIX_COUNT_PER_SOURCE as u32) as u8;
635        Some((source, mix))
636    }
637
638    // Singleton node accessors
639    impl_singleton!(master_channel, master_channel_path, is_master_channel_path);
640    impl_singleton!(output, output_path, is_output_path);
641    impl_singleton!(ducker, ducker_path, is_ducker_path);
642    impl_singleton!(recorder, recorder_path, is_recorder_path);
643    impl_singleton!(player, player_path, is_player_path);
644    impl_singleton!(gui, gui_path, is_gui_path);
645    impl_singleton!(system, system_path, is_system_path);
646    impl_singleton!(sip_calling, sip_calling_path, is_sip_calling_path);
647    impl_singleton!(sip_advanced, sip_advanced_path, is_sip_advanced_path);
648    impl_singleton!(test, test_path, is_test_path);
649    impl_singleton!(network, network_path, is_network_path);
650    impl_singleton!(audio, audio_path, is_audio_path);
651    impl_singleton!(build, build_path, is_build_path);
652    impl_singleton!(app, app_path, is_app_path);
653    impl_singleton!(theme, theme_path, is_theme_path);
654    impl_singleton!(current_show, current_show_path, is_current_show_path);
655    impl_singleton!(show_control, show_control_path, is_show_control_path);
656    impl_singleton!(recordings, recordings_path, is_recordings_path);
657    impl_singleton!(radio, radio_path, is_radio_path);
658
659    // Indexed and container-nested run accessors
660    impl_run!(
661        sip_call_slots,
662        sip_call_slots_path,
663        sip_call_slots_index_from_path,
664        sip_call_slots_count
665    );
666    impl_run!(
667        sip_registration,
668        sip_registration_path,
669        sip_registration_index_from_path,
670        sip_registration_count
671    );
672    impl_run!(
673        pad_recorder,
674        pad_recorder_path,
675        pad_recorder_index_from_path,
676        pad_recorder_count
677    );
678    impl_run!(
679        fx_preset,
680        fx_preset_path,
681        fx_preset_index_from_path,
682        fx_preset_count
683    );
684    impl_run!(show, show_path, show_index_from_path, show_count);
685    impl_run!(
686        recording,
687        recording_path,
688        recording_index_from_path,
689        recording_count
690    );
691    impl_run!(
692        storage_volume,
693        storage_volume_path,
694        storage_volume_index_from_path,
695        storage_volume_count
696    );
697    impl_run!(
698        radio_tx,
699        radio_tx_path,
700        radio_tx_index_from_path,
701        radio_tx_count
702    );
703    impl_run!(
704        radio_rx,
705        radio_rx_path,
706        radio_rx_index_from_path,
707        radio_rx_count
708    );
709    impl_run!(
710        wifi_scan_result,
711        wifi_scan_result_path,
712        wifi_scan_result_index_from_path,
713        wifi_scan_result_count
714    );
715    impl_run!(
716        streamerx_mix_preset,
717        streamerx_mix_preset_path,
718        streamerx_mix_preset_index_from_path,
719        streamerx_mix_preset_count
720    );
721    impl_run!(
722        streamerx_stream_mix,
723        streamerx_stream_mix_path,
724        streamerx_stream_mix_index_from_path,
725        streamerx_stream_mix_count
726    );
727    impl_run!(
728        rcsync_mix,
729        rcsync_mix_path,
730        rcsync_mix_index_from_path,
731        rcsync_mix_count
732    );
733    impl_run!(
734        mix_minuses,
735        mix_minuses_path,
736        mix_minuses_index_from_path,
737        mix_minuses_count
738    );
739}
740
741/// Read the `SYSTEM` node's `boardType` / `systemName` and resolve the model.
742/// Missing `SYSTEM` (synthetic trees, partial captures) -> Pro II default.
743fn detect_model(root: &Node) -> DeviceModel {
744    let sys = root.children.iter().find(|c| c.name == "SYSTEM");
745    let board_type = sys.and_then(|s| {
746        s.properties
747            .iter()
748            .find(|p| p.name == "boardType")
749            .and_then(|p| p.value.as_int())
750    });
751    let system_name = sys.and_then(|s| {
752        s.properties
753            .iter()
754            .find(|p| p.name == "systemName")
755            .and_then(|p| match &p.value {
756                Value::String(name) => Some(name.as_str()),
757                _ => None,
758            })
759    });
760    DeviceModel::detect(board_type, system_name)
761}
762
763/// Discover the first contiguous run of `name` children under `parent` as an
764/// [`Indexed`] addressing shape. Absent -> `first: None, count: 0`.
765fn discover_run(parent: &Node, name: &str) -> Indexed {
766    match position_of_named_child(parent, name) {
767        Some(first) => Indexed {
768            first: Some(first),
769            count: count_consecutive_named(parent, first, name),
770        },
771        None => Indexed {
772            first: None,
773            count: 0,
774        },
775    }
776}
777
778/// Discover a two-level run of `child_name` nodes inside a `container_name` parent
779/// as a [`TwoLevel`] addressing shape. Absent -> `parent: None, first: 0, count: 0`.
780fn discover_two_level(root: &Node, container_name: &str, child_name: &str) -> TwoLevel {
781    match position_of_named_child(root, container_name) {
782        Some(parent) => {
783            let container = &root.children[parent as usize];
784            match position_of_named_child(container, child_name) {
785                Some(first) => TwoLevel {
786                    parent: Some(parent),
787                    first,
788                    count: count_consecutive_named(container, first, child_name),
789                },
790                None => TwoLevel {
791                    parent: Some(parent),
792                    first: 0,
793                    count: 0,
794                },
795            }
796        }
797        None => TwoLevel {
798            parent: None,
799            first: 0,
800            count: 0,
801        },
802    }
803}
804
805fn position_of_named_child(parent: &Node, name: &str) -> Option<u32> {
806    parent
807        .children
808        .iter()
809        .position(|c| c.name == name)
810        .map(|i| i as u32)
811}
812
813fn count_consecutive_named(parent: &Node, start: u32, name: &str) -> u8 {
814    let mut n: u8 = 0;
815    for child in parent.children.iter().skip(start as usize) {
816        if child.name != name {
817            break;
818        }
819        n = n.saturating_add(1);
820    }
821    n
822}
823
824fn count_consecutive_named_u32(parent: &Node, start: u32, name: &str) -> u32 {
825    let mut n: u32 = 0;
826    for child in parent.children.iter().skip(start as usize) {
827        if child.name != name {
828            break;
829        }
830        n = n.saturating_add(1);
831    }
832    n
833}
834
835/// Error from [`Layout::from_full_sync`].
836#[derive(Debug, Clone, PartialEq)]
837pub enum BuildError {
838    /// A required node name wasn't found where the Rodecaster layout expects it.
839    MissingNode(&'static str),
840    /// A required node family was found but its shape doesn't match expectations
841    /// (e.g., MIX count not divisible by the matrix width).
842    ShapeMismatch { what: &'static str, detail: String },
843}
844
845impl std::fmt::Display for BuildError {
846    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
847        match self {
848            BuildError::MissingNode(what) => {
849                write!(f, "fullSync missing required node: {what}")
850            }
851            BuildError::ShapeMismatch { what, detail } => {
852                write!(f, "fullSync shape mismatch for {what}: {detail}")
853            }
854        }
855    }
856}
857
858impl std::error::Error for BuildError {}
859
860#[cfg(test)]
861#[path = "layout_tests.rs"]
862mod tests;