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