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(
525                                SetParameter::new(
526                                    PortId::param(nid, 0),
527                                    pid,
528                                    table[index].clone(),
529                                    SignalOrigin::Automaton(serv_id.clone()),
530                                )
531                                .with_sample_pos(clock.sample_pos + clock.io_quantum as u64),
532                            ));
533                            return;
534                        }
535
536                        let mapped = map.apply(raw);
537                        let base = state.base;
538                        let value = match ctrl {
539                            ControlStrategy::Absolute => min + mapped * (max - min),
540                            ControlStrategy::Modulation { depth } => {
541                                (base + mapped * depth * (max - min)).clamp(min, max)
542                            }
543                        };
544                        if (value - state.last_sent_value).abs() < 1e-6 {
545                            return;
546                        }
547                        state.last_sent_value = value;
548
549                        // Skip SetParameter when no target parameter configured
550                        // (mapping-only servos with NoAction automaton).
551                        if param.is_empty() {
552                            return;
553                        }
554
555                        let pid = ParameterId::new(&param).unwrap();
556                        gr.send(CommandEnum::SetParameter(
557                            SetParameter::new(
558                                PortId::param(nid, 0),
559                                pid,
560                                ParamValue::Float(value as f32),
561                                SignalOrigin::Automaton(serv_id.clone()),
562                            )
563                            .with_sample_pos(clock.sample_pos + clock.io_quantum as u64),
564                        ));
565                    }
566                    CommandEnum::Automaton(AutomatonCommand::SetEnabled { enabled, .. }) => {
567                        s.lock().unwrap().enabled = enabled;
568                    }
569                    CommandEnum::Automaton(AutomatonCommand::Reset { .. }) => {
570                        s.lock().unwrap().internal = a.reset();
571                    }
572                    CommandEnum::Automaton(AutomatonCommand::UiValue { value, .. }) => {
573                        let mut state = s.lock().unwrap();
574                        let pid = ParameterId::new(&param).unwrap();
575                        let cmd = SetParameter::new(
576                            PortId::param(nid, 0),
577                            pid,
578                            ParamValue::Float(value as f32),
579                            SignalOrigin::Automaton(serv_id.clone()),
580                        );
581                        match confl {
582                            ConflictStrategy::TouchOverride => {
583                                state.base = value;
584                                state.frozen = true;
585                                gr.send(CommandEnum::SetParameter(cmd));
586                            }
587                            ConflictStrategy::BasePlusModulation => {
588                                state.base = value;
589                            }
590                            ConflictStrategy::LastWriteWins => {
591                                gr.send(CommandEnum::SetParameter(cmd));
592                            }
593                        }
594                    }
595                    CommandEnum::Automaton(AutomatonCommand::UiRelease { .. }) => {
596                        let mut state = s.lock().unwrap();
597                        if state.frozen {
598                            state.frozen = false;
599                        }
600                    }
601                    CommandEnum::Control(event) => {
602                        match &event {
603                            // ── Pitch bend: update context, recalc if note active ──
604                            ControlEvent::MidiControl {
605                                controller,
606                                normalized,
607                                ..
608                            } if Some(*controller) == pitch_cc => {
609                                let mut state = s.lock().unwrap();
610                                let semis = (*normalized as f64 - 0.5) * 2.0 * pitch_semis;
611                                state.control_ctx.pitch_bend_semitones = semis;
612                                drop(state);
613
614                                let s3 = s.lock().unwrap();
615                                if let (Some(note), Some(_vel)) =
616                                    (s3.control_ctx.active_note, s3.control_ctx.active_velocity)
617                                {
618                                    let freq = midi_note_to_freq(note)
619                                        * 2.0f64.powf(s3.control_ctx.pitch_bend_semitones / 12.0);
620                                    let pid = ParameterId::new("frequency").unwrap();
621                                    gr.send(CommandEnum::SetParameter(SetParameter::new(
622                                        PortId::param(nid, 0),
623                                        pid,
624                                        ParamValue::Float(freq as f32),
625                                        SignalOrigin::Automaton(serv_id.clone()),
626                                    )));
627                                }
628                                drop(s3);
629                            }
630                            // ── Mod wheel: update context, recalc if note active ──
631                            ControlEvent::MidiControl {
632                                controller,
633                                normalized,
634                                ..
635                            } if Some(*controller) == mod_cc => {
636                                let mut state = s.lock().unwrap();
637                                state.control_ctx.mod_wheel = *normalized as f64;
638                                drop(state);
639
640                                let s3 = s.lock().unwrap();
641                                if let (Some(_note), Some(vel)) =
642                                    (s3.control_ctx.active_note, s3.control_ctx.active_velocity)
643                                {
644                                    let amp = vel as f64 * s3.control_ctx.mod_wheel;
645                                    let pid = ParameterId::new("amplitude").unwrap();
646                                    gr.send(CommandEnum::SetParameter(SetParameter::new(
647                                        PortId::param(nid, 0),
648                                        pid,
649                                        ParamValue::Float(amp as f32),
650                                        SignalOrigin::Automaton(serv_id.clone()),
651                                    )));
652                                }
653                                drop(s3);
654                            }
655                            // ── Note on: activate, compose from context ──
656                            ControlEvent::MidiNote {
657                                note,
658                                velocity,
659                                on: true,
660                                ..
661                            } if velocity > &0u8 => {
662                                let vel_norm = *velocity as f32 / 127.0;
663                                let mut state = s.lock().unwrap();
664                                state.control_ctx.active_note = Some(*note);
665                                state.control_ctx.active_velocity = Some(vel_norm);
666                                let freq = midi_note_to_freq(*note)
667                                    * 2.0f64.powf(state.control_ctx.pitch_bend_semitones / 12.0);
668                                let amp = vel_norm as f64 * state.control_ctx.mod_wheel;
669                                drop(state);
670
671                                // Send frequency
672                                let pid = ParameterId::new("frequency").unwrap();
673                                gr.send(CommandEnum::SetParameter(SetParameter::new(
674                                    PortId::param(nid, 0),
675                                    pid,
676                                    ParamValue::Float(freq as f32),
677                                    SignalOrigin::Automaton(serv_id.clone()),
678                                )));
679                                // Send amplitude
680                                let pid_amp = ParameterId::new("amplitude").unwrap();
681                                gr.send(CommandEnum::SetParameter(SetParameter::new(
682                                    PortId::param(nid, 0),
683                                    pid_amp,
684                                    ParamValue::Float(amp as f32),
685                                    SignalOrigin::Automaton(serv_id.clone()),
686                                )));
687                            }
688                            // ── Note off: deactivate, silence ──
689                            ControlEvent::MidiNote { on: false, .. } => {
690                                let mut state = s.lock().unwrap();
691                                state.control_ctx.active_note = None;
692                                state.control_ctx.active_velocity = None;
693                                drop(state);
694
695                                let pid = ParameterId::new("amplitude").unwrap();
696                                gr.send(CommandEnum::SetParameter(SetParameter::new(
697                                    PortId::param(nid, 0),
698                                    pid,
699                                    ParamValue::Float(0.0),
700                                    SignalOrigin::Automaton(serv_id.clone()),
701                                )));
702                            }
703                            // ── Fallback: iterate user-defined mappings ──
704                            _ => {
705                                let mut state = s.lock().unwrap();
706                                for mapping in &mappings {
707                                    if let Some(sp) = mapping.apply(&event) {
708                                        match confl {
709                                            ConflictStrategy::TouchOverride => {
710                                                state.frozen = true;
711                                                if let Some(nv) = event.normalized_value() {
712                                                    state.base = nv as f64;
713                                                }
714                                                gr.send(CommandEnum::SetParameter(sp));
715                                                break; // one mapping match — freeze + send
716                                            }
717                                            ConflictStrategy::BasePlusModulation => {
718                                                if let Some(nv) = event.normalized_value() {
719                                                    state.base = nv as f64;
720                                                }
721                                                // Don't send SetParameter — automaton
722                                                // modulates around new base on next ClockTick.
723                                            }
724                                            ConflictStrategy::LastWriteWins => {
725                                                gr.send(CommandEnum::SetParameter(sp));
726                                            }
727                                        }
728                                    }
729                                }
730                            }
731                        }
732                    }
733                    _ => {}
734                })
735            },
736            1,
737        )
738    }
739
740    /// Attaches a preset value table; raw automaton output selects table entries by index.
741    pub fn with_table(mut self, table: Vec<ParamValue>) -> Self {
742        self.table = Some(table);
743        self
744    }
745
746    /// Enable pitch bend tracking via MIDI CC.
747    ///
748    /// When a pitch bend CC arrives and a note is active, the servo
749    /// recalculates frequency as `midi_to_freq(note) * 2^(bend/12)`.
750    pub fn with_pitch_bend(mut self, cc: u8, semitones: f64) -> Self {
751        self.pitch_bend_cc = Some(cc);
752        self.pitch_bend_semis = semitones;
753        self
754    }
755
756    /// Enable mod wheel tracking via MIDI CC.
757    ///
758    /// When a mod wheel CC arrives and a note is active, the servo
759    /// recalculates amplitude as `(velocity/127) * mod_wheel`.
760    pub fn with_mod_wheel(mut self, cc: u8) -> Self {
761        self.mod_wheel_cc = Some(cc);
762        self
763    }
764
765    /// Attaches sensor event mappings for [`Control`](CommandEnum::Control) dispatch.
766    ///
767    /// When the servo receives a `ControlEvent`, each mapping is checked;
768    /// matching events produce `SetParameter` commands sent to the graph.
769    pub fn with_mappings(mut self, mappings: Vec<Mapping>) -> Self {
770        self.mappings = mappings;
771        self
772    }
773
774    /// Set the control strategy — how the automaton affects the parameter value.
775    ///
776    /// - `Absolute` (default): automaton output [0,1] maps to [min,max].
777    /// - `Modulation { depth }`: automaton output [-1,1] modulates around `base`.
778    pub fn with_control(mut self, strategy: ControlStrategy) -> Self {
779        self.control = strategy;
780        self
781    }
782
783    /// Set the conflict resolution strategy — how UI/HID input interacts with
784    /// automaton control for the same parameter.
785    ///
786    /// - `LastWriteWins` (default): both sources send independently; mailbox order.
787    /// - `TouchOverride`: HID input freezes automaton until `UiRelease`.
788    /// - `BasePlusModulation`: HID input sets the base value; automaton modulates around it.
789    pub fn with_conflict(mut self, strategy: ConflictStrategy) -> Self {
790        self.conflict = strategy;
791        self
792    }
793
794    /// Returns this servo's unique identifier.
795    pub fn id(&self) -> &str {
796        &self.id
797    }
798}
799
800// =============================================================================
801// 9. Module trait — unified interface for sensors
802// =============================================================================
803
804/// Type-erased, heap-allocated reference to any module.
805pub type BoxedModule = Box<dyn Module>;
806
807/// Unified interface for sensor and control modules (MIDI hubs, OSC servers, etc.).
808pub trait Module: Send {
809    /// Returns this module's unique identifier.
810    fn id(&self) -> &str;
811    /// Returns the actor handle if this module has a control actor, `None` otherwise.
812    fn handle(&self) -> Option<ActorRef<CommandEnum>> {
813        None
814    }
815    /// Enables or disables the module.
816    fn set_enabled(&mut self, _enabled: bool) {}
817    /// Stops the module, joining any background threads.
818    fn stop(&mut self);
819}
820
821// =============================================================================
822// 10. Helper constructors
823// =============================================================================
824
825/// Convenience constructor for a MIDI control change mapping.
826pub fn midi_cc(
827    controller: u8,
828    channel: Option<u8>,
829    target_node: NodeId,
830    target_param: &str,
831    min: f32,
832    max: f32,
833    transform: Transform,
834) -> Mapping {
835    Mapping::new(
836        EventPattern::MidiControl {
837            channel,
838            controller,
839        },
840        Target {
841            node_id: target_node,
842            param_name: target_param.to_string(),
843            min,
844            max,
845        },
846        transform,
847    )
848}
849
850/// Convenience constructor for a MIDI note mapping.
851///
852/// Use [`MidiNoteKind`] to select which aspect of the note event to extract:
853/// - `Frequency` — `midi_to_freq(note)`, Note Off produces no value
854/// - `Amplitude` — `velocity / 127` (On) or `0.0` (Off)
855/// - `Gate` — `1.0` (On) or `0.0` (Off)
856pub fn midi_note(
857    kind: MidiNoteKind,
858    note: Option<u8>,
859    channel: Option<u8>,
860    target_node: NodeId,
861    target_param: &str,
862    min: f32,
863    max: f32,
864    transform: Transform,
865) -> Mapping {
866    Mapping::new(
867        EventPattern::MidiNote {
868            channel,
869            note,
870            kind,
871        },
872        Target {
873            node_id: target_node,
874            param_name: target_param.to_string(),
875            min,
876            max,
877        },
878        transform,
879    )
880}
881
882/// Convenience constructor for an OSC address mapping.
883pub fn osc_address(
884    address: &str,
885    target_node: NodeId,
886    target_param: &str,
887    min: f32,
888    max: f32,
889    transform: Transform,
890) -> Mapping {
891    Mapping::new(
892        EventPattern::OscAddress(address.to_string()),
893        Target {
894            node_id: target_node,
895            param_name: target_param.to_string(),
896            min,
897            max,
898        },
899        transform,
900    )
901}
902
903// =============================================================================
904// 11. Tests
905// =============================================================================
906
907#[cfg(test)]
908mod tests {
909    use super::*;
910
911    #[test]
912    fn test_midi_mapping() {
913        let node = NodeId(1);
914        let mapping = midi_cc(7, Some(1), node, "volume", 0.0, 1.0, Transform::Linear);
915        let event = ControlEvent::MidiControl {
916            channel: 1,
917            controller: 7,
918            value: 64,
919            normalized: 0.5,
920        };
921        assert!(mapping.matches(&event));
922        let cmd = mapping.apply(&event).unwrap();
923        assert_eq!(cmd.port.node_id(), node);
924        assert_eq!(cmd.parameter.as_ref(), "volume");
925        assert!((cmd.value.as_f32().unwrap() - 0.5).abs() < 1e-6);
926    }
927}