rill-patchbay 0.5.0-beta.2

The world where Automata live - control system for Rill
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
#![allow(missing_docs)]
//! Serializable patchbay document types (de)serialised from JSON/CBOR.

use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use rill_core::NodeId;

use crate::automaton::envelope::{EnvelopeAutomaton, EnvelopeType};
use crate::automaton::lfo::LfoWaveform;
use crate::automaton::sequencer::{PlayMode, SequencerAutomaton, Step};
pub use crate::control::EventPattern;
use crate::control::{
    BoxedServo, Mapping, OscSurface, ParameterMapping, PatchbayControl, Servo, Target, Transform,
};
use crate::function_registry::FunctionRegistry;
use crate::strategy::{ConflictStrategy, ControlStrategy};

// ============================================================================
// AutomatonDef
// ============================================================================

/// Serializable description of a control automaton.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone)]
pub enum AutomatonDef {
    Lfo {
        id: String,
        frequency: f64,
        amplitude: f64,
        offset: f64,
        waveform: LfoWaveform,
    },
    Envelope {
        id: String,
        envelope_type: EnvelopeType,
        attack: f64,
        decay: f64,
        sustain: f64,
        release: f64,
        curve: f64,
    },
    Sequencer {
        id: String,
        steps: Vec<StepDef>,
        play_mode: PlayMode,
        tempo: f64,
    },
    NamedFunction {
        id: String,
        function_name: String,
        params: HashMap<String, f64>,
    },
}

impl AutomatonDef {
    pub fn id(&self) -> &str {
        match self {
            AutomatonDef::Lfo { id, .. } => id,
            AutomatonDef::Envelope { id, .. } => id,
            AutomatonDef::Sequencer { id, .. } => id,
            AutomatonDef::NamedFunction { id, .. } => id,
        }
    }
}

/// Serializable step for [`AutomatonDef::Sequencer`].
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone)]
pub struct StepDef {
    pub value: f64,
    pub duration: f64,
    /// Curve for transition to the next step. CBOR-roundtrip safe.
    #[cfg_attr(feature = "serde", serde(default))]
    pub curve: Option<f64>,
}

// ============================================================================
// ServoDef
// ============================================================================

/// Type of value mapping for a servo.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MappingType {
    Linear,
    Exponential,
    Logarithmic,
    Inverted,
}

impl MappingType {
    pub fn to_parameter_mapping(self) -> ParameterMapping {
        match self {
            MappingType::Linear => ParameterMapping::Linear,
            MappingType::Exponential => ParameterMapping::Exponential,
            MappingType::Logarithmic => ParameterMapping::Logarithmic,
            MappingType::Inverted => ParameterMapping::Inverted,
        }
    }
}

/// Describes a servo: which automaton drives which node parameter.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone)]
pub struct ServoDef {
    pub automaton_id: String,
    pub target_node: u32,
    pub target_param: String,
    pub mapping: MappingType,
    pub min: f64,
    pub max: f64,
    pub enabled: bool,

    /// Async mode: update interval in milliseconds.
    /// When `Some`, the automaton runs as a green thread (tokio task)
    /// with the given interval. When `None`, falls back to sync mode
    /// (requires manual `PatchbayControl::update()` calls).
    #[serde(default)]
    pub async_interval_ms: Option<f64>,

    /// Async mode: control strategy (defaults to `Absolute`).
    #[serde(default)]
    pub control_strategy: Option<ControlStrategy>,

    /// Async mode: conflict resolution (defaults to `LastWriteWins`).
    #[serde(default)]
    pub conflict_strategy: Option<ConflictStrategy>,
}

// ============================================================================
// MappingDef
// ============================================================================

/// Serializable transform (without closure variant).
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone)]
pub enum TransformDef {
    Linear,
    Exponential,
    Logarithmic,
    Inverted,
    NamedFunction {
        name: String,
        params: HashMap<String, f64>,
    },
}

impl TransformDef {
    pub fn to_transform(&self, registry: &FunctionRegistry) -> Transform {
        match self {
            TransformDef::Linear => Transform::Linear,
            TransformDef::Exponential => Transform::Exponential,
            TransformDef::Logarithmic => Transform::Logarithmic,
            TransformDef::Inverted => Transform::Inverted,
            TransformDef::NamedFunction { name, params } => {
                let name = name.clone();
                let params = params.clone();
                let reg = registry.clone();
                Transform::Custom(Arc::new(move |x| {
                    reg.apply(&name, x as f64, &params).unwrap_or(x as f64) as f32
                }))
            }
        }
    }
}

/// Describes a mapping from an external event to a node parameter.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone)]
pub struct MappingDef {
    pub event_pattern: EventPattern,
    pub target_node: u32,
    pub target_param: String,
    pub transform: TransformDef,
    pub min: f64,
    pub max: f64,
    pub enabled: bool,
}

// ============================================================================
// PatchbayDocument
// ============================================================================

/// Serializable patchbay configuration.
///
/// Analogous to `rill_graph::serialization::GraphDocument`, linked through
/// shared `node_id` values.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone)]
pub struct PatchbayDocument {
    pub automata: Vec<AutomatonDef>,
    pub servos: Vec<ServoDef>,
    pub mappings: Vec<MappingDef>,

    /// OSC → EventPattern bridge (see [`OscSurfaceEntry`]).
    /// Consumed by the host runtime to register user‑facing OSC handlers.
    #[serde(default)]
    pub osc_surface: OscSurface,

    /// Optional human-readable description (attribution, preset notes, …).
    /// Not interpreted by the engine; preserved through serialisation round-trips.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

impl PatchbayDocument {
    pub fn new() -> Self {
        Self {
            automata: Vec::new(),
            servos: Vec::new(),
            mappings: Vec::new(),
            osc_surface: Vec::new(),
            description: None,
        }
    }

    /// Apply the document to a [`PatchbayControl`].
    pub fn apply_to(
        &self,
        control: &mut PatchbayControl,
        registry: &FunctionRegistry,
    ) -> Result<(), String> {
        let auto_ids: std::collections::HashSet<&str> =
            self.automata.iter().map(|a| a.id()).collect();

        for s in &self.servos {
            if !auto_ids.contains(s.automaton_id.as_str()) {
                return Err(format!(
                    "servo references unknown automaton '{}'",
                    s.automaton_id
                ));
            }

            let def = self
                .automata
                .iter()
                .find(|a| a.id() == s.automaton_id)
                .unwrap();
            let nid = NodeId(s.target_node);
            let mapping = s.mapping.to_parameter_mapping();

            match def {
                AutomatonDef::Lfo {
                    id,
                    frequency,
                    amplitude,
                    offset,
                    waveform,
                } => {
                    control.add_lfo(
                        id,
                        *frequency,
                        *amplitude,
                        *offset,
                        *waveform,
                        nid,
                        &s.target_param,
                        s.min,
                        s.max,
                    );
                }
                AutomatonDef::Envelope {
                    id,
                    envelope_type,
                    attack,
                    decay,
                    sustain,
                    release,
                    curve,
                } => {
                    let automaton =
                        EnvelopeAutomaton::adsr(id, *attack, *decay, *sustain, *release)
                            .with_curve(*curve);
                    let servo: BoxedServo = Box::new(Servo::new(
                        id,
                        automaton,
                        nid,
                        &s.target_param,
                        mapping,
                        s.min,
                        s.max,
                    ));
                    control.add_boxed_servo(id.clone(), servo);
                }
                AutomatonDef::Sequencer {
                    id,
                    steps,
                    play_mode,
                    tempo,
                } => {
                    let seq_steps: Vec<Step> = steps
                        .iter()
                        .map(|sd| Step {
                            value: sd.value,
                            duration: sd.duration,
                            curve: sd.curve,
                        })
                        .collect();
                    let automaton = SequencerAutomaton::new(id, seq_steps)
                        .with_mode(*play_mode)
                        .with_tempo(*tempo);
                    let servo: BoxedServo = Box::new(Servo::new(
                        id,
                        automaton,
                        nid,
                        &s.target_param,
                        mapping,
                        s.min,
                        s.max,
                    ));
                    control.add_boxed_servo(id.clone(), servo);
                }
                AutomatonDef::NamedFunction { id, .. } => {
                    log::warn!("NamedFunction automaton '{}' requires manual setup", id);
                }
            }
        }

        for m in &self.mappings {
            let transform = m.transform.to_transform(registry);
            let name = format!("{:?} -> {}", m.event_pattern, m.target_param);
            control.add_mapping(Mapping {
                pattern: m.event_pattern.clone(),
                target: Target {
                    node_id: NodeId(m.target_node),
                    param_name: m.target_param.clone(),
                    min: m.min as f32,
                    max: m.max as f32,
                },
                transform,
                name,
                enabled: m.enabled,
            });
        }

        Ok(())
    }

    /// Apply the document to a [`PatchbayControl`] using async automaton tasks.
    ///
    /// For each servo with `async_interval_ms: Some(...)`, creates a green
    /// thread (tokio task) with the specified strategies. Falls back to sync
    /// mode for servos without async configuration.
    ///
    /// Requires an active tokio runtime.
    pub fn apply_to_async(
        &self,
        control: &mut PatchbayControl,
        registry: &FunctionRegistry,
    ) -> Result<(), String> {
        let auto_ids: std::collections::HashSet<&str> =
            self.automata.iter().map(|a| a.id()).collect();

        for s in &self.servos {
            if !auto_ids.contains(s.automaton_id.as_str()) {
                return Err(format!(
                    "servo references unknown automaton '{}'",
                    s.automaton_id
                ));
            }

            let def = self
                .automata
                .iter()
                .find(|a| a.id() == s.automaton_id)
                .unwrap();
            let nid = NodeId(s.target_node);
            let target = (nid, s.target_param.clone());
            let range = (s.min, s.max);

            match def {
                AutomatonDef::Lfo {
                    id,
                    frequency,
                    amplitude,
                    offset,
                    waveform,
                } => {
                    if let Some(interval_ms) = s.async_interval_ms {
                        let interval = Duration::from_secs_f64(interval_ms / 1000.0);
                        let control_strategy =
                            s.control_strategy.unwrap_or(ControlStrategy::Absolute);
                        let conflict_strategy = s
                            .conflict_strategy
                            .unwrap_or(ConflictStrategy::LastWriteWins);
                        control.add_lfo_task(
                            id,
                            *frequency,
                            *amplitude,
                            *offset,
                            *waveform,
                            interval,
                            target,
                            range,
                            control_strategy,
                            conflict_strategy,
                        );
                    } else {
                        control.add_lfo(
                            id,
                            *frequency,
                            *amplitude,
                            *offset,
                            *waveform,
                            nid,
                            &s.target_param,
                            s.min,
                            s.max,
                        );
                    }
                }
                AutomatonDef::Envelope {
                    id,
                    attack,
                    decay,
                    sustain,
                    release,
                    curve,
                    ..
                } => {
                    if let Some(interval_ms) = s.async_interval_ms {
                        let interval = Duration::from_secs_f64(interval_ms / 1000.0);
                        let control_strategy =
                            s.control_strategy.unwrap_or(ControlStrategy::Absolute);
                        let conflict_strategy = s
                            .conflict_strategy
                            .unwrap_or(ConflictStrategy::LastWriteWins);
                        control.add_envelope_task(
                            id,
                            *attack,
                            *decay,
                            *sustain,
                            *release,
                            interval,
                            target,
                            range,
                            control_strategy,
                            conflict_strategy,
                        );
                    } else {
                        let automaton =
                            EnvelopeAutomaton::adsr(id, *attack, *decay, *sustain, *release)
                                .with_curve(*curve);
                        let mapping = s.mapping.to_parameter_mapping();
                        let servo: BoxedServo = Box::new(Servo::new(
                            id,
                            automaton,
                            nid,
                            &s.target_param,
                            mapping,
                            s.min,
                            s.max,
                        ));
                        control.add_boxed_servo(id.clone(), servo);
                    }
                }
                AutomatonDef::Sequencer {
                    id,
                    steps,
                    play_mode,
                    tempo,
                } => {
                    log::warn!(
                        "Sequencer sync mode not fully wired in apply_to_async; use manual setup"
                    );
                    let _ = (id, steps, play_mode, tempo, nid, s);
                }
                AutomatonDef::NamedFunction { id, .. } => {
                    log::warn!("NamedFunction automaton '{}' requires manual setup", id);
                }
            }
        }

        for m in &self.mappings {
            let transform = m.transform.to_transform(registry);
            let name = format!("{:?} -> {}", m.event_pattern, m.target_param);
            control.add_mapping(Mapping {
                pattern: m.event_pattern.clone(),
                target: Target {
                    node_id: NodeId(m.target_node),
                    param_name: m.target_param.clone(),
                    min: m.min as f32,
                    max: m.max as f32,
                },
                transform,
                name,
                enabled: m.enabled,
            });
        }

        Ok(())
    }
}

impl Default for PatchbayDocument {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Serialisation helpers
// ============================================================================

#[cfg(feature = "json")]
pub fn to_json(doc: &PatchbayDocument) -> Result<String, String> {
    serde_json::to_string_pretty(doc).map_err(|e| e.to_string())
}

#[cfg(feature = "json")]
pub fn from_json(json: &str) -> Result<PatchbayDocument, String> {
    serde_json::from_str(json).map_err(|e| e.to_string())
}

#[cfg(feature = "cbor")]
pub fn to_cbor(doc: &PatchbayDocument) -> Result<Vec<u8>, String> {
    serde_cbor::to_vec(doc).map_err(|e| e.to_string())
}

#[cfg(feature = "cbor")]
pub fn from_cbor(bytes: &[u8]) -> Result<PatchbayDocument, String> {
    serde_cbor::from_slice(bytes).map_err(|e| e.to_string())
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use rill_core::queues::MpscQueue;

    fn sample_doc() -> PatchbayDocument {
        PatchbayDocument {
            automata: vec![AutomatonDef::Lfo {
                id: "lfo1".into(),
                frequency: 0.3,
                amplitude: 1.0,
                offset: 0.0,
                waveform: LfoWaveform::Sine,
            }],
            servos: vec![ServoDef {
                automaton_id: "lfo1".into(),
                target_node: 1,
                target_param: "delay_time".into(),
                mapping: MappingType::Linear,
                min: 0.01,
                max: 0.5,
                enabled: true,
                async_interval_ms: None,
                control_strategy: None,
                conflict_strategy: None,
            }],
            mappings: vec![],
            osc_surface: vec![],
            description: None,
        }
    }

    #[test]
    fn test_json_roundtrip() {
        let doc = sample_doc();
        let json = to_json(&doc).unwrap();
        let restored = from_json(&json).unwrap();
        assert_eq!(restored.automata.len(), 1);
        assert_eq!(restored.servos.len(), 1);
        assert_eq!(restored.servos[0].target_param, "delay_time");
    }

    #[test]
    fn test_cbor_roundtrip() {
        let doc = sample_doc();
        let cbor = to_cbor(&doc).unwrap();
        let restored = from_cbor(&cbor).unwrap();
        assert_eq!(restored.automata.len(), 1);
        assert_eq!(restored.automata[0].id(), "lfo1");
    }

    #[test]
    fn test_apply_to_adds_servo() {
        let doc = sample_doc();
        let q = Arc::new(MpscQueue::new());
        let mut control = PatchbayControl::new(q);
        let registry = FunctionRegistry::builtin();
        doc.apply_to(&mut control, &registry).unwrap();
        control.update(0.01);
    }

    #[test]
    fn test_missing_automaton_error() {
        let doc = PatchbayDocument {
            automata: vec![],
            servos: vec![ServoDef {
                automaton_id: "nonexistent".into(),
                target_node: 1,
                target_param: "gain".into(),
                mapping: MappingType::Linear,
                min: 0.0,
                max: 1.0,
                enabled: true,
                async_interval_ms: None,
                control_strategy: None,
                conflict_strategy: None,
            }],
            mappings: vec![],
            osc_surface: vec![],
            description: None,
        };
        let q = Arc::new(MpscQueue::new());
        let mut control = PatchbayControl::new(q);
        let registry = FunctionRegistry::builtin();
        assert!(doc.apply_to(&mut control, &registry).is_err());
    }

    #[test]
    fn test_apply_to_async_roundtrip() {
        let doc = PatchbayDocument {
            automata: vec![AutomatonDef::Lfo {
                id: "lfo1".into(),
                frequency: 1.0,
                amplitude: 1.0,
                offset: 0.0,
                waveform: LfoWaveform::Sine,
            }],
            servos: vec![ServoDef {
                automaton_id: "lfo1".into(),
                target_node: 1,
                target_param: "cutoff".into(),
                mapping: MappingType::Linear,
                min: 100.0,
                max: 1000.0,
                enabled: true,
                async_interval_ms: Some(10.0),
                control_strategy: Some(ControlStrategy::Absolute),
                conflict_strategy: Some(ConflictStrategy::LastWriteWins),
            }],
            mappings: vec![],
            osc_surface: vec![],
            description: None,
        };

        let json = to_json(&doc).unwrap();
        let restored = from_json(&json).unwrap();
        assert_eq!(restored.servos.len(), 1);
        assert_eq!(restored.servos[0].async_interval_ms, Some(10.0));
        assert_eq!(
            restored.servos[0].control_strategy,
            Some(ControlStrategy::Absolute)
        );
        assert_eq!(
            restored.servos[0].conflict_strategy,
            Some(ConflictStrategy::LastWriteWins)
        );
    }

    #[tokio::test]
    async fn test_apply_to_async_spawns_tasks() {
        use rill_core::queues::{MpscQueue, SetParameter};

        let doc = PatchbayDocument {
            automata: vec![AutomatonDef::Lfo {
                id: "lfo1".into(),
                frequency: 10.0,
                amplitude: 1.0,
                offset: 0.0,
                waveform: LfoWaveform::Sine,
            }],
            servos: vec![ServoDef {
                automaton_id: "lfo1".into(),
                target_node: 1,
                target_param: "cutoff".into(),
                mapping: MappingType::Linear,
                min: 100.0,
                max: 1000.0,
                enabled: true,
                async_interval_ms: Some(10.0),
                control_strategy: Some(ControlStrategy::Absolute),
                conflict_strategy: Some(ConflictStrategy::LastWriteWins),
            }],
            mappings: vec![],
            osc_surface: vec![],
            description: None,
        };

        let q: Arc<MpscQueue<SetParameter>> = Arc::new(MpscQueue::new());
        let mut control = PatchbayControl::new(q.clone());
        let registry = FunctionRegistry::builtin();
        doc.apply_to_async(&mut control, &registry).unwrap();

        // Let the green thread produce a value
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
        assert!(!q.is_empty(), "async LFO should have pushed a value");
    }
}