Skip to main content

rill_patchbay/
engine.rs

1//! Control and automation subsystem.
2//!
3//! Provides event mapping (MIDI/OSC → parameters), automaton-based
4//! modulation (LFO, envelopes), and a two-thread model with lock-free
5//! queues for control → signal communication.
6
7use std::fmt::Debug;
8use std::sync::{Arc, Mutex};
9
10use rill_core::prelude::*;
11use rill_core::queues::{AutomatonCommand, CommandEnum, SetParameter, SignalOrigin};
12use rill_core_actor::{ActorRef, ActorSystem};
13
14pub use crate::automaton::{EnvelopeAutomaton, LfoAutomaton, LfoWaveform, Range};
15use crate::strategy::{ConflictStrategy, ControlStrategy};
16
17// Re-export control event types from rill-core (canonical home)
18pub use rill_core::queues::control_event::{
19    ControlEvent, EventPattern, MidiNoteKind, MidiTransportKind,
20};
21
22// =============================================================================
23// 2b. OSC Surface
24// =============================================================================
25
26/// A single entry in an OSC control surface, binding an OSC path to an event pattern.
27#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
28#[derive(Debug, Clone)]
29pub struct OscSurfaceEntry {
30    /// The OSC address path this entry listens to.
31    pub osc_path: String,
32    /// The event pattern that triggered actions should match.
33    pub event_pattern: EventPattern,
34    #[cfg_attr(
35        feature = "serde",
36        serde(default, skip_serializing_if = "Option::is_none")
37    )]
38    /// Optional human-readable label for UI display.
39    pub label: Option<String>,
40}
41
42/// A list of OSC address → event mappings forming a control surface layout.
43pub type OscSurface = Vec<OscSurfaceEntry>;
44
45// =============================================================================
46// 3. Value transforms
47// =============================================================================
48
49/// Transfer function applied to a normalized [0,1] value before scaling to parameter range.
50#[derive(Clone)]
51pub enum Transform {
52    /// Identity: value passes through unchanged.
53    Linear,
54    /// Square mapping: finer control near zero, coarser near one.
55    Exponential,
56    /// Logarithmic mapping: finer control near maximum.
57    Logarithmic,
58    /// Reversed mapping: 1.0 becomes min, 0.0 becomes max.
59    Inverted,
60    /// User-defined custom transfer function.
61    Custom(Arc<dyn Fn(f32) -> f32 + Send + Sync>),
62}
63
64impl Debug for Transform {
65    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
66        match self {
67            Transform::Linear => write!(f, "Linear"),
68            Transform::Exponential => write!(f, "Exponential"),
69            Transform::Logarithmic => write!(f, "Logarithmic"),
70            Transform::Inverted => write!(f, "Inverted"),
71            Transform::Custom(_) => write!(f, "Custom"),
72        }
73    }
74}
75
76impl Transform {
77    /// Applies the transform to a normalized value, mapping it into the [min, max] range.
78    pub fn apply(&self, value: f32, min: f32, max: f32) -> f32 {
79        let range = max - min;
80        let normalized = value.clamp(0.0, 1.0);
81        let mapped = match self {
82            Transform::Linear => min + normalized * range,
83            Transform::Exponential => min + normalized * normalized * range,
84            Transform::Logarithmic => min + (1.0 + normalized * 9.0).log10() * range,
85            Transform::Inverted => max - normalized * range,
86            Transform::Custom(f) => min + f(normalized) * range,
87        };
88        mapped.clamp(min, max)
89    }
90}
91
92// =============================================================================
93// 4. Event mapping
94// =============================================================================
95
96/// The destination of an event mapping: a specific parameter on a specific graph node.
97#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
98#[derive(Debug, Clone)]
99pub struct Target {
100    /// Graph node that owns the target parameter.
101    pub node_id: NodeId,
102    /// Name of the parameter to control.
103    pub param_name: String,
104    /// Lower bound of the parameter value range.
105    pub min: f32,
106    /// Upper bound of the parameter value range.
107    pub max: f32,
108}
109
110/// A complete mapping from an input event to a target parameter, with a value transform.
111#[derive(Debug, Clone)]
112pub struct Mapping {
113    /// Event pattern that triggers this mapping.
114    pub pattern: EventPattern,
115    /// Target parameter to set when the pattern matches.
116    pub target: Target,
117    /// Transform applied to the normalized event value before scaling.
118    pub transform: Transform,
119    /// Human-readable name for debugging and UI.
120    pub name: String,
121    /// Whether this mapping is currently active.
122    pub enabled: bool,
123}
124
125impl Mapping {
126    /// Creates a new mapping with an auto-generated name.
127    pub fn new(pattern: EventPattern, target: Target, transform: Transform) -> Self {
128        let name = format!("{:?} -> {}", pattern, target.param_name);
129        Self {
130            pattern,
131            target,
132            transform,
133            name,
134            enabled: true,
135        }
136    }
137
138    /// Returns `true` if this mapping is enabled and matches the given event.
139    pub fn matches(&self, event: &ControlEvent) -> bool {
140        self.enabled && self.pattern.matches(event)
141    }
142
143    /// Produces a parameter-set command if the event matches this mapping.
144    pub fn apply(&self, event: &ControlEvent) -> Option<SetParameter> {
145        if !self.matches(event) {
146            return None;
147        }
148
149        // MidiNote with kind: extract value from note event, bypassing
150        // the standard normalized_value() pipeline.
151        if let (
152            EventPattern::MidiNote { kind, .. },
153            ControlEvent::MidiNote {
154                note, velocity, on, ..
155            },
156        ) = (&self.pattern, event)
157        {
158            let value = match kind {
159                MidiNoteKind::Frequency => {
160                    if !*on {
161                        return None;
162                    }
163                    // midi_to_freq produces absolute Hz — bypass Transform
164                    rill_core_dsp::math::midi_to_freq::<f32>(*note)
165                }
166                MidiNoteKind::Amplitude => {
167                    let raw = if *on { *velocity as f32 / 127.0 } else { 0.0 };
168                    self.transform.apply(raw, self.target.min, self.target.max)
169                }
170                MidiNoteKind::Gate => {
171                    let raw = if *on { 1.0 } else { 0.0 };
172                    self.transform.apply(raw, self.target.min, self.target.max)
173                }
174            };
175            let pid = ParameterId::new(&self.target.param_name).unwrap();
176            return Some(SetParameter::new(
177                PortId::param(self.target.node_id, 0),
178                pid,
179                ParamValue::Float(value),
180                SignalOrigin::External(self.name.clone()),
181            ));
182        }
183
184        // All other patterns: use the standard normalized_value() pipeline.
185        let norm = event.normalized_value()?;
186        let value = self.transform.apply(norm, self.target.min, self.target.max);
187        let pid = ParameterId::new(&self.target.param_name).unwrap();
188        Some(SetParameter::new(
189            PortId::param(self.target.node_id, 0),
190            pid,
191            ParamValue::Float(value),
192            SignalOrigin::External(self.name.clone()),
193        ))
194    }
195}
196
197// =============================================================================
198// 5. Automaton core trait
199// =============================================================================
200
201/// Time in seconds, used for automaton clocks and timekeeping.
202pub type Time = f64;
203
204/// A unit action for automatons that need no external action per step.
205///
206/// Also implements [`Automaton`] as a no-op — useful for mapping-only servos
207/// where the automaton output is irrelevant.
208#[derive(Debug, Clone, Default)]
209pub struct NoAction;
210
211impl Automaton for NoAction {
212    type Internal = ();
213    type Action = ();
214
215    fn step(
216        &self,
217        _internal: &mut Self::Internal,
218        _current: &ParamValue,
219        _time: Time,
220        _action: &Self::Action,
221    ) -> ParamValue {
222        ParamValue::Float(0.0)
223    }
224
225    fn initial_internal(&self) -> Self::Internal {}
226
227    fn name(&self) -> &str {
228        "NoAction"
229    }
230}
231
232/// Core trait for automatons — stateful signal generators that advance per step.
233pub trait Automaton: Send + Sync + Debug {
234    /// The automaton's internal state, carried across step invocations.
235    type Internal: Clone + Send + Sync + 'static;
236    /// An optional action type driving state transitions on each step.
237    type Action: Debug + Clone + Send + Sync + Default + 'static;
238
239    /// Advances the automaton by one step, producing a new output value.
240    ///
241    /// `internal` holds mutable state, `current` is the last output value,
242    /// `time` is the elapsed time in seconds, and `action` is an optional trigger.
243    fn step(
244        &self,
245        internal: &mut Self::Internal,
246        current: &ParamValue,
247        time: Time,
248        action: &Self::Action,
249    ) -> ParamValue;
250
251    /// Returns the automaton's initial internal state (at time zero).
252    fn initial_internal(&self) -> Self::Internal;
253
254    /// Resets the automaton to its initial internal state.
255    fn reset(&self) -> Self::Internal {
256        self.initial_internal()
257    }
258
259    /// Returns the human-readable name of this automaton.
260    fn name(&self) -> &str;
261}
262
263// =============================================================================
264// 6. Parameter mapping
265// =============================================================================
266
267/// Transfer function for mapping raw automaton output [0,1] to parameter space.
268#[derive(Clone)]
269pub enum ParameterMapping {
270    /// Identity: output equals input.
271    Linear,
272    /// Square mapping: finer control near zero.
273    Exponential,
274    /// Logarithmic mapping: finer control near maximum.
275    Logarithmic,
276    /// Inverted: 1.0 maps to 0.0 and vice versa.
277    Inverted,
278    /// User-defined custom mapping function.
279    Custom(Arc<dyn Fn(f64) -> f64 + Send + Sync>),
280}
281
282impl std::fmt::Debug for ParameterMapping {
283    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284        match self {
285            ParameterMapping::Linear => write!(f, "Linear"),
286            ParameterMapping::Exponential => write!(f, "Exponential"),
287            ParameterMapping::Logarithmic => write!(f, "Logarithmic"),
288            ParameterMapping::Inverted => write!(f, "Inverted"),
289            ParameterMapping::Custom(_) => write!(f, "Custom(<fn>)"),
290        }
291    }
292}
293
294impl ParameterMapping {
295    /// Applies this mapping to a raw value in the [0, 1] range.
296    pub fn apply(&self, raw: f64) -> f64 {
297        match self {
298            ParameterMapping::Linear => raw,
299            ParameterMapping::Exponential => raw * raw,
300            ParameterMapping::Logarithmic => (1.0 + raw * 9.0).log10(),
301            ParameterMapping::Inverted => 1.0 - raw,
302            ParameterMapping::Custom(f) => f(raw),
303        }
304    }
305}
306
307// =============================================================================
308// 6.5. Control context — stateful MIDI controller aggregation
309// =============================================================================
310
311/// Per-servo mutable context for stateful control events.
312///
313/// Pitch bend and mod wheel values accumulate here. When a note-on
314/// arrives, the servo composes the final frequency/amplitude from
315/// the context and sends it directly (bypassing mappings).
316#[derive(Debug, Clone)]
317pub(crate) struct ControlContext {
318    pitch_bend_semitones: f64,
319    mod_wheel: f64,
320    active_note: Option<u8>,
321    active_velocity: Option<f32>,
322}
323
324impl Default for ControlContext {
325    fn default() -> Self {
326        Self {
327            pitch_bend_semitones: 0.0,
328            mod_wheel: 1.0,
329            active_note: None,
330            active_velocity: None,
331        }
332    }
333}
334
335/// Convert a MIDI note number to frequency in Hz (A4 = 440 Hz).
336fn midi_note_to_freq(note: u8) -> f64 {
337    440.0 * 2.0f64.powf((note as f64 - 69.0) / 12.0)
338}
339
340// =============================================================================
341// 7. ServoState
342// =============================================================================
343
344/// Internal runtime state of a Servo, shared between the control actor and automation logic.
345pub(crate) struct ServoState<A: Automaton> {
346    /// Current automaton internal state.
347    pub(crate) internal: A::Internal,
348    /// Most recent output value produced by the automaton.
349    pub(crate) value: ParamValue,
350    /// Elapsed time in seconds since the automaton started.
351    pub(crate) time: Time,
352    /// Whether the servo is actively stepping the automaton.
353    pub(crate) enabled: bool,
354    /// Base value for modulation strategies (offset added to modulation output).
355    pub(crate) base: f64,
356    /// When `true`, the servo is frozen from UI touch (used with TouchOverride).
357    pub(crate) frozen: bool,
358    /// Last value sent to the graph, used for change detection.
359    pub(crate) last_sent_value: f64,
360    /// Last table index sent (only used with value tables).
361    pub(crate) last_sent_index: i64,
362    /// Stateful control context for pitch bend / mod wheel / note tracking.
363    pub(crate) control_ctx: ControlContext,
364}
365
366// =============================================================================
367// 8. Servo — automaton-to-parameter bridge
368// =============================================================================
369
370/// Bridges an automaton to a graph parameter, stepping on every clock tick and
371/// sending control commands to the signal graph.
372///
373/// Also accepts external control events (MIDI, OSC, CV/Gate) via
374/// `CommandEnum::Control`, applying registered [`Mapping`]s to convert
375/// them into `SetParameter` commands.
376pub struct Servo<A: Automaton> {
377    id: String,
378    automaton: Arc<A>,
379    state: Arc<Mutex<ServoState<A>>>,
380    graph_ref: ActorRef<CommandEnum>,
381    target_node: NodeId,
382    target_param: String,
383    mapping: ParameterMapping,
384    min: f64,
385    max: f64,
386    control: ControlStrategy,
387    conflict: ConflictStrategy,
388    table: Option<Vec<ParamValue>>,
389    /// Event-to-parameter mappings for sensor-driven control events.
390    mappings: Vec<Mapping>,
391    /// MIDI CC number for pitch bend (default 128 = pitch bend message).
392    pitch_bend_cc: Option<u8>,
393    /// Pitch bend range in semitones (±).
394    pitch_bend_semis: f64,
395    /// MIDI CC number for mod wheel (default 1).
396    mod_wheel_cc: Option<u8>,
397}
398
399impl<A: Automaton + 'static> Servo<A> {
400    /// Creates a new Servo linking an automaton to a target parameter.
401    pub fn new(
402        id: impl Into<String>,
403        automaton: A,
404        target_node: NodeId,
405        target_param: impl Into<String>,
406        mapping: ParameterMapping,
407        min: f64,
408        max: f64,
409        system: Arc<ActorSystem>,
410        graph_ref: ActorRef<CommandEnum>,
411    ) -> Self {
412        let _ = system;
413        let automaton = Arc::new(automaton);
414        let mut internal = automaton.initial_internal();
415        let initial_value = automaton.step(
416            &mut internal,
417            &ParamValue::Float(0.0),
418            0.0,
419            &A::Action::default(),
420        );
421
422        Self {
423            id: id.into(),
424            automaton,
425            state: Arc::new(Mutex::new(ServoState {
426                internal,
427                value: initial_value,
428                time: 0.0,
429                enabled: true,
430                base: (min + max) / 2.0,
431                frozen: false,
432                last_sent_value: f64::NAN,
433                last_sent_index: -1,
434                control_ctx: ControlContext::default(),
435            })),
436            graph_ref,
437            target_node,
438            target_param: target_param.into(),
439            mapping,
440            min,
441            max,
442            control: ControlStrategy::Absolute,
443            conflict: ConflictStrategy::LastWriteWins,
444            table: None,
445            mappings: Vec::new(),
446            pitch_bend_cc: None,
447            pitch_bend_semis: 2.0,
448            mod_wheel_cc: None,
449        }
450    }
451
452    /// Spawns this servo as a detached tokio actor, returning its address.
453    ///
454    /// The actor listens for `ClockTick` to step the automaton, and for
455    /// `AutomatonCommand` variants to handle enable/reset/UI value events.
456    pub fn spawn(self, system: &ActorSystem) -> ActorRef<CommandEnum> {
457        let Servo {
458            id,
459            automaton,
460            state,
461            graph_ref,
462            target_node,
463            target_param,
464            mapping,
465            min,
466            max,
467            control,
468            conflict,
469            table,
470            mappings,
471            pitch_bend_cc,
472            pitch_bend_semis,
473            mod_wheel_cc,
474        } = self;
475
476        let a = automaton;
477        let s = state;
478        let gr = graph_ref;
479        let nid = target_node;
480        let param = target_param;
481        let map = mapping;
482        let ctrl = control;
483        let confl = conflict;
484        let tbl = table;
485        let pitch_cc = pitch_bend_cc;
486        let pitch_semis = pitch_bend_semis;
487        let mod_cc = mod_wheel_cc;
488        let serv_id = id.clone();
489
490        let s2 = s.clone();
491        system.spawn_detached(
492            &format!("servo_{id}"),
493            move || {
494                Box::new(move |msg: CommandEnum| match msg {
495                    CommandEnum::ClockTick(clock) => {
496                        let mut state = s2.lock().unwrap();
497                        if !state.enabled {
498                            return;
499                        }
500                        let dt = clock.samples_since_last as f64 / clock.sample_rate as f64;
501                        state.time += dt;
502                        if state.frozen && matches!(confl, ConflictStrategy::TouchOverride) {
503                            return;
504                        }
505                        let current_value = state.value.clone();
506                        let current_time = state.time;
507                        let action = A::Action::default();
508                        let new_val =
509                            a.step(&mut state.internal, &current_value, current_time, &action);
510                        let raw = new_val.as_f32().unwrap_or(0.0) as f64;
511                        state.value = new_val;
512
513                        if let Some(ref table) = tbl {
514                            let index = raw as usize;
515                            if index >= table.len() {
516                                return;
517                            }
518                            let idx = index as i64;
519                            if idx == state.last_sent_index {
520                                return;
521                            }
522                            state.last_sent_index = idx;
523                            let pid = ParameterId::new(&param).unwrap();
524                            gr.send(CommandEnum::SetParameter(SetParameter::new(
525                                PortId::param(nid, 0),
526                                pid,
527                                table[index].clone(),
528                                SignalOrigin::Automaton(serv_id.clone()),
529                            )));
530                            return;
531                        }
532
533                        let mapped = map.apply(raw);
534                        let base = state.base;
535                        let value = match ctrl {
536                            ControlStrategy::Absolute => min + mapped * (max - min),
537                            ControlStrategy::Modulation { depth } => {
538                                (base + mapped * depth * (max - min)).clamp(min, max)
539                            }
540                        };
541                        if (value - state.last_sent_value).abs() < 1e-6 {
542                            return;
543                        }
544                        state.last_sent_value = value;
545
546                        // Skip SetParameter when no target parameter configured
547                        // (mapping-only servos with NoAction automaton).
548                        if param.is_empty() {
549                            return;
550                        }
551
552                        let pid = ParameterId::new(&param).unwrap();
553                        gr.send(CommandEnum::SetParameter(SetParameter::new(
554                            PortId::param(nid, 0),
555                            pid,
556                            ParamValue::Float(value as f32),
557                            SignalOrigin::Automaton(serv_id.clone()),
558                        )));
559                    }
560                    CommandEnum::Automaton(AutomatonCommand::SetEnabled { enabled, .. }) => {
561                        s.lock().unwrap().enabled = enabled;
562                    }
563                    CommandEnum::Automaton(AutomatonCommand::Reset { .. }) => {
564                        s.lock().unwrap().internal = a.reset();
565                    }
566                    CommandEnum::Automaton(AutomatonCommand::UiValue { value, .. }) => {
567                        let mut state = s.lock().unwrap();
568                        let pid = ParameterId::new(&param).unwrap();
569                        let cmd = SetParameter::new(
570                            PortId::param(nid, 0),
571                            pid,
572                            ParamValue::Float(value as f32),
573                            SignalOrigin::Automaton(serv_id.clone()),
574                        );
575                        match confl {
576                            ConflictStrategy::TouchOverride => {
577                                state.base = value;
578                                state.frozen = true;
579                                gr.send(CommandEnum::SetParameter(cmd));
580                            }
581                            ConflictStrategy::BasePlusModulation => {
582                                state.base = value;
583                            }
584                            ConflictStrategy::LastWriteWins => {
585                                gr.send(CommandEnum::SetParameter(cmd));
586                            }
587                        }
588                    }
589                    CommandEnum::Automaton(AutomatonCommand::UiRelease { .. }) => {
590                        let mut state = s.lock().unwrap();
591                        if state.frozen {
592                            state.frozen = false;
593                        }
594                    }
595                    CommandEnum::Control(event) => {
596                        match &event {
597                            // ── Pitch bend: update context, recalc if note active ──
598                            ControlEvent::MidiControl {
599                                controller,
600                                normalized,
601                                ..
602                            } if Some(*controller) == pitch_cc => {
603                                let mut state = s.lock().unwrap();
604                                let semis = (*normalized as f64 - 0.5) * 2.0 * pitch_semis;
605                                state.control_ctx.pitch_bend_semitones = semis;
606                                drop(state);
607
608                                let s3 = s.lock().unwrap();
609                                if let (Some(note), Some(_vel)) =
610                                    (s3.control_ctx.active_note, s3.control_ctx.active_velocity)
611                                {
612                                    let freq = midi_note_to_freq(note)
613                                        * 2.0f64.powf(s3.control_ctx.pitch_bend_semitones / 12.0);
614                                    let pid = ParameterId::new("frequency").unwrap();
615                                    gr.send(CommandEnum::SetParameter(SetParameter::new(
616                                        PortId::param(nid, 0),
617                                        pid,
618                                        ParamValue::Float(freq as f32),
619                                        SignalOrigin::Automaton(serv_id.clone()),
620                                    )));
621                                }
622                                drop(s3);
623                            }
624                            // ── Mod wheel: update context, recalc if note active ──
625                            ControlEvent::MidiControl {
626                                controller,
627                                normalized,
628                                ..
629                            } if Some(*controller) == mod_cc => {
630                                let mut state = s.lock().unwrap();
631                                state.control_ctx.mod_wheel = *normalized as f64;
632                                drop(state);
633
634                                let s3 = s.lock().unwrap();
635                                if let (Some(_note), Some(vel)) =
636                                    (s3.control_ctx.active_note, s3.control_ctx.active_velocity)
637                                {
638                                    let amp = vel as f64 * s3.control_ctx.mod_wheel;
639                                    let pid = ParameterId::new("amplitude").unwrap();
640                                    gr.send(CommandEnum::SetParameter(SetParameter::new(
641                                        PortId::param(nid, 0),
642                                        pid,
643                                        ParamValue::Float(amp as f32),
644                                        SignalOrigin::Automaton(serv_id.clone()),
645                                    )));
646                                }
647                                drop(s3);
648                            }
649                            // ── Note on: activate, compose from context ──
650                            ControlEvent::MidiNote {
651                                note,
652                                velocity,
653                                on: true,
654                                ..
655                            } if velocity > &0u8 => {
656                                let vel_norm = *velocity as f32 / 127.0;
657                                let mut state = s.lock().unwrap();
658                                state.control_ctx.active_note = Some(*note);
659                                state.control_ctx.active_velocity = Some(vel_norm);
660                                let freq = midi_note_to_freq(*note)
661                                    * 2.0f64.powf(state.control_ctx.pitch_bend_semitones / 12.0);
662                                let amp = vel_norm as f64 * state.control_ctx.mod_wheel;
663                                drop(state);
664
665                                // Send frequency
666                                let pid = ParameterId::new("frequency").unwrap();
667                                gr.send(CommandEnum::SetParameter(SetParameter::new(
668                                    PortId::param(nid, 0),
669                                    pid,
670                                    ParamValue::Float(freq as f32),
671                                    SignalOrigin::Automaton(serv_id.clone()),
672                                )));
673                                // Send amplitude
674                                let pid_amp = ParameterId::new("amplitude").unwrap();
675                                gr.send(CommandEnum::SetParameter(SetParameter::new(
676                                    PortId::param(nid, 0),
677                                    pid_amp,
678                                    ParamValue::Float(amp as f32),
679                                    SignalOrigin::Automaton(serv_id.clone()),
680                                )));
681                            }
682                            // ── Note off: deactivate, silence ──
683                            ControlEvent::MidiNote { on: false, .. } => {
684                                let mut state = s.lock().unwrap();
685                                state.control_ctx.active_note = None;
686                                state.control_ctx.active_velocity = None;
687                                drop(state);
688
689                                let pid = ParameterId::new("amplitude").unwrap();
690                                gr.send(CommandEnum::SetParameter(SetParameter::new(
691                                    PortId::param(nid, 0),
692                                    pid,
693                                    ParamValue::Float(0.0),
694                                    SignalOrigin::Automaton(serv_id.clone()),
695                                )));
696                            }
697                            // ── Fallback: iterate user-defined mappings ──
698                            _ => {
699                                let mut state = s.lock().unwrap();
700                                for mapping in &mappings {
701                                    if let Some(sp) = mapping.apply(&event) {
702                                        match confl {
703                                            ConflictStrategy::TouchOverride => {
704                                                state.frozen = true;
705                                                if let Some(nv) = event.normalized_value() {
706                                                    state.base = nv as f64;
707                                                }
708                                                gr.send(CommandEnum::SetParameter(sp));
709                                                break; // one mapping match — freeze + send
710                                            }
711                                            ConflictStrategy::BasePlusModulation => {
712                                                if let Some(nv) = event.normalized_value() {
713                                                    state.base = nv as f64;
714                                                }
715                                                // Don't send SetParameter — automaton
716                                                // modulates around new base on next ClockTick.
717                                            }
718                                            ConflictStrategy::LastWriteWins => {
719                                                gr.send(CommandEnum::SetParameter(sp));
720                                            }
721                                        }
722                                    }
723                                }
724                            }
725                        }
726                    }
727                    _ => {}
728                })
729            },
730            1,
731        )
732    }
733
734    /// Attaches a preset value table; raw automaton output selects table entries by index.
735    pub fn with_table(mut self, table: Vec<ParamValue>) -> Self {
736        self.table = Some(table);
737        self
738    }
739
740    /// Enable pitch bend tracking via MIDI CC.
741    ///
742    /// When a pitch bend CC arrives and a note is active, the servo
743    /// recalculates frequency as `midi_to_freq(note) * 2^(bend/12)`.
744    pub fn with_pitch_bend(mut self, cc: u8, semitones: f64) -> Self {
745        self.pitch_bend_cc = Some(cc);
746        self.pitch_bend_semis = semitones;
747        self
748    }
749
750    /// Enable mod wheel tracking via MIDI CC.
751    ///
752    /// When a mod wheel CC arrives and a note is active, the servo
753    /// recalculates amplitude as `(velocity/127) * mod_wheel`.
754    pub fn with_mod_wheel(mut self, cc: u8) -> Self {
755        self.mod_wheel_cc = Some(cc);
756        self
757    }
758
759    /// Attaches sensor event mappings for [`Control`](CommandEnum::Control) dispatch.
760    ///
761    /// When the servo receives a `ControlEvent`, each mapping is checked;
762    /// matching events produce `SetParameter` commands sent to the graph.
763    pub fn with_mappings(mut self, mappings: Vec<Mapping>) -> Self {
764        self.mappings = mappings;
765        self
766    }
767
768    /// Set the control strategy — how the automaton affects the parameter value.
769    ///
770    /// - `Absolute` (default): automaton output [0,1] maps to [min,max].
771    /// - `Modulation { depth }`: automaton output [-1,1] modulates around `base`.
772    pub fn with_control(mut self, strategy: ControlStrategy) -> Self {
773        self.control = strategy;
774        self
775    }
776
777    /// Set the conflict resolution strategy — how UI/HID input interacts with
778    /// automaton control for the same parameter.
779    ///
780    /// - `LastWriteWins` (default): both sources send independently; mailbox order.
781    /// - `TouchOverride`: HID input freezes automaton until `UiRelease`.
782    /// - `BasePlusModulation`: HID input sets the base value; automaton modulates around it.
783    pub fn with_conflict(mut self, strategy: ConflictStrategy) -> Self {
784        self.conflict = strategy;
785        self
786    }
787
788    /// Returns this servo's unique identifier.
789    pub fn id(&self) -> &str {
790        &self.id
791    }
792}
793
794// =============================================================================
795// 9. Module trait — unified interface for sensors
796// =============================================================================
797
798/// Type-erased, heap-allocated reference to any module.
799pub type BoxedModule = Box<dyn Module>;
800
801/// Unified interface for sensor and control modules (MIDI hubs, OSC servers, etc.).
802pub trait Module: Send {
803    /// Returns this module's unique identifier.
804    fn id(&self) -> &str;
805    /// Returns the actor handle if this module has a control actor, `None` otherwise.
806    fn handle(&self) -> Option<ActorRef<CommandEnum>> {
807        None
808    }
809    /// Enables or disables the module.
810    fn set_enabled(&mut self, _enabled: bool) {}
811    /// Stops the module, joining any background threads.
812    fn stop(&mut self);
813}
814
815// =============================================================================
816// 10. Helper constructors
817// =============================================================================
818
819/// Convenience constructor for a MIDI control change mapping.
820pub fn midi_cc(
821    controller: u8,
822    channel: Option<u8>,
823    target_node: NodeId,
824    target_param: &str,
825    min: f32,
826    max: f32,
827    transform: Transform,
828) -> Mapping {
829    Mapping::new(
830        EventPattern::MidiControl {
831            channel,
832            controller,
833        },
834        Target {
835            node_id: target_node,
836            param_name: target_param.to_string(),
837            min,
838            max,
839        },
840        transform,
841    )
842}
843
844/// Convenience constructor for a MIDI note mapping.
845///
846/// Use [`MidiNoteKind`] to select which aspect of the note event to extract:
847/// - `Frequency` — `midi_to_freq(note)`, Note Off produces no value
848/// - `Amplitude` — `velocity / 127` (On) or `0.0` (Off)
849/// - `Gate` — `1.0` (On) or `0.0` (Off)
850pub fn midi_note(
851    kind: MidiNoteKind,
852    note: Option<u8>,
853    channel: Option<u8>,
854    target_node: NodeId,
855    target_param: &str,
856    min: f32,
857    max: f32,
858    transform: Transform,
859) -> Mapping {
860    Mapping::new(
861        EventPattern::MidiNote {
862            channel,
863            note,
864            kind,
865        },
866        Target {
867            node_id: target_node,
868            param_name: target_param.to_string(),
869            min,
870            max,
871        },
872        transform,
873    )
874}
875
876/// Convenience constructor for an OSC address mapping.
877pub fn osc_address(
878    address: &str,
879    target_node: NodeId,
880    target_param: &str,
881    min: f32,
882    max: f32,
883    transform: Transform,
884) -> Mapping {
885    Mapping::new(
886        EventPattern::OscAddress(address.to_string()),
887        Target {
888            node_id: target_node,
889            param_name: target_param.to_string(),
890            min,
891            max,
892        },
893        transform,
894    )
895}
896
897// =============================================================================
898// 11. Tests
899// =============================================================================
900
901#[cfg(test)]
902mod tests {
903    use super::*;
904
905    #[test]
906    fn test_midi_mapping() {
907        let node = NodeId(1);
908        let mapping = midi_cc(7, Some(1), node, "volume", 0.0, 1.0, Transform::Linear);
909        let event = ControlEvent::MidiControl {
910            channel: 1,
911            controller: 7,
912            value: 64,
913            normalized: 0.5,
914        };
915        assert!(mapping.matches(&event));
916        let cmd = mapping.apply(&event).unwrap();
917        assert_eq!(cmd.port.node_id(), node);
918        assert_eq!(cmd.parameter.as_ref(), "volume");
919        assert!((cmd.value.as_f32().unwrap() - 0.5).abs() < 1e-6);
920    }
921}