rill-patchbay 0.6.0-M2

The world where Automata live - control system for Rill
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! MIDI sensor — receives raw MIDI messages from a backend,
//! parses them into `ControlEvent`s, and sends them via `ActorRef`.
//!
//! Two implementations:
//! - [`MidiHub`] — standalone sensor with its own `ActorRef<ControlEvent>` (legacy)
//! - [`spawn_midi_sensor`] — integrates with the actor model: control through
//!   `ActorRef<CommandEnum>`, polling in a dedicated OS thread (like Graph's
//!   I/O callback that calls `actor.drain()`).

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread::{self, JoinHandle};
use std::time::Duration;

use rill_core::queues::{CommandEnum, SensorCommand};
use rill_core_actor::{ActorRef, ActorSystem};
use rill_io::midi_input::MidiInput;
use rill_io::midi_message::MidiMessage;

use crate::engine::{ControlEvent, MidiTransportKind, Module};
use crate::midi_clock::MidiClockTracker;
use crate::sensor::Sensor;

/// MIDI sensor — polls a [`MidiInput`] on a dedicated OS thread,
/// parses raw bytes into `ControlEvent`s, and dispatches via `ActorRef`.
///
/// Optionally integrates a [`MidiClockTracker`] for MIDI clock sync:
/// when present, each raw status byte is fed to the tracker before
/// normal parsing, enabling BPM derivation from clock pulses.
pub struct MidiHub {
    id: String,
    pub(crate) thread: Option<JoinHandle<()>>,
    running: Arc<AtomicBool>,
    events: Option<ActorRef<ControlEvent>>,
    backend: Option<Box<dyn MidiInput>>,
    pub(crate) tracker: Option<MidiClockTracker>,
}

impl MidiHub {
    /// Create a new MIDI sensor with a backend.
    pub fn new(id: impl Into<String>, backend: Box<dyn MidiInput>) -> Self {
        Self {
            id: id.into(),
            thread: None,
            running: Arc::new(AtomicBool::new(true)),
            events: None,
            backend: Some(backend),
            tracker: None,
        }
    }

    /// Create a MIDI sensor with an integrated [`MidiClockTracker`].
    ///
    /// The tracker receives raw status bytes from every incoming message.
    /// Use [`MidiHub::shared_clock`] to obtain the `Arc<SystemClock>` for
    /// wiring into the signal graph.
    pub fn with_clock_tracker(
        id: impl Into<String>,
        backend: Box<dyn MidiInput>,
        tracker: MidiClockTracker,
    ) -> Self {
        Self {
            id: id.into(),
            thread: None,
            running: Arc::new(AtomicBool::new(true)),
            events: None,
            backend: Some(backend),
            tracker: Some(tracker),
        }
    }

    /// Convenience: create, attach, and start in one call.
    pub fn start(
        id: impl Into<String>,
        backend: Box<dyn MidiInput>,
        events: ActorRef<ControlEvent>,
    ) -> Self {
        let mut hub = Self::new(id, backend);
        hub.attach(events);
        hub.start();
        hub
    }

    /// Return a clone of the shared `SystemClock` if a clock tracker is active.
    pub fn shared_clock(&self) -> Option<Arc<rill_core::time::SystemClock>> {
        self.tracker.as_ref().map(|t| t.shared_clock())
    }
}

impl Module for MidiHub {
    fn id(&self) -> &str {
        &self.id
    }

    fn stop(&mut self) {
        self.running.store(false, Ordering::Release);
        if let Some(handle) = self.thread.take() {
            let _ = handle.join();
        }
    }
}

impl Sensor for MidiHub {
    fn attach(&mut self, events: ActorRef<ControlEvent>) {
        self.events = Some(events);
    }

    fn start(&mut self) {
        let events = self
            .events
            .take()
            .expect("MidiHub: attach() must be called before start()");
        let backend = self
            .backend
            .take()
            .expect("MidiHub: already started or no backend");
        let mut tracker = self.tracker.take();
        let r = self.running.clone();

        self.thread = Some(thread::spawn(move || {
            let mut backend = backend;
            while r.load(Ordering::Acquire) {
                match backend.poll() {
                    Ok(msgs) => {
                        for msg in msgs {
                            if let Some(ref mut t) = tracker {
                                t.process_status(msg.status());
                            }
                            if let Some(event) = parse_midi(&msg) {
                                events.send(event);
                            }
                        }
                    }
                    Err(e) => {
                        log::warn!("midi backend poll error: {e}");
                        thread::sleep(Duration::from_millis(10));
                    }
                }
                thread::sleep(Duration::from_millis(1));
            }
        }));
    }
}

impl Drop for MidiHub {
    fn drop(&mut self) {
        self.stop();
    }
}

#[cfg(feature = "debug")]
impl MidiHub {
    /// Capture a snapshot of this MIDI sensor's status.
    pub fn inspect(&self) -> crate::debug::SensorSnapshot {
        crate::debug::SensorSnapshot {
            name: self.id.clone(),
            kind: "midi".into(),
            connected: self.thread.is_some(),
            event_count: 0,
            last_event: None,
            tracker_active: self.tracker.is_some(),
        }
    }
}

// =============================================================================
// MidiSensor — actor-model MIDI sensor
// =============================================================================

/// Spawns a MIDI sensor that integrates with the actor model.
///
/// The polling loop runs in a dedicated OS thread. Raw MIDI bytes are
/// decoded into `ControlEvent`s and sent to the **servo** via
/// `CommandEnum::Control`. The servo applies mappings and sends
/// `SetParameter` to the graph — the sensor never maps or writes
/// parameters directly.
///
/// # Arguments
/// * `id` — unique sensor identifier
/// * `backend` — MIDI I/O backend (e.g. [`MidirBackend`], [`AlsaSeqBackend`])
/// * `system` — actor system for spawning the control actor
/// * `servo_ref` — target servo's actor reference for delivering events
pub fn spawn_midi_sensor(
    id: &str,
    backend: Box<dyn MidiInput>,
    system: &ActorSystem,
    servo_ref: ActorRef<CommandEnum>,
) -> ActorRef<CommandEnum> {
    let enabled = Arc::new(AtomicBool::new(true));
    let sr = servo_ref.clone();
    let mid = id.to_string();

    // Control actor — receives messages from RackActor fan-out (SetEnabled, etc.).
    let actor_ref = system.spawn_detached(
        &format!("midi_{id}"),
        {
            let e2 = enabled.clone();
            move || {
                Box::new(move |msg: CommandEnum| {
                    if let CommandEnum::Sensor(SensorCommand::SetEnabled { enabled: en, .. }) = msg
                    {
                        e2.store(en, Ordering::Release);
                    }
                })
            }
        },
        10,
    );

    // Polling thread — decodes MIDI, sends raw events to the servo
    thread::spawn(move || {
        let mut backend = backend;
        loop {
            thread::sleep(Duration::from_millis(5));

            if !enabled.load(Ordering::Acquire) {
                continue;
            }
            match backend.poll() {
                Ok(msgs) => {
                    for msg in &msgs {
                        if let Some(event) = parse_midi(msg) {
                            sr.send(CommandEnum::Control(event));
                        }
                    }
                }
                Err(e) => {
                    log::warn!("midi sensor '{mid}' poll error: {e}");
                    thread::sleep(Duration::from_millis(50));
                }
            }
        }
    });

    actor_ref
}

/// Parse a raw `MidiMessage` into a `ControlEvent`.
pub fn parse_midi(msg: &MidiMessage) -> Option<ControlEvent> {
    let status = msg.status();
    match msg.message_type() {
        // Note Off
        0x80 => Some(ControlEvent::MidiNote {
            channel: msg.channel(),
            note: msg.data1(),
            velocity: 0,
            on: false,
        }),
        // Note On
        0x90 => {
            let velocity = msg.data2();
            if velocity == 0 {
                // Velocity 0 NoteOn = NoteOff
                Some(ControlEvent::MidiNote {
                    channel: msg.channel(),
                    note: msg.data1(),
                    velocity: 0,
                    on: false,
                })
            } else {
                Some(ControlEvent::MidiNote {
                    channel: msg.channel(),
                    note: msg.data1(),
                    velocity,
                    on: true,
                })
            }
        }
        // Polyphonic Aftertouch
        0xA0 => Some(ControlEvent::MidiNote {
            channel: msg.channel(),
            note: msg.data1(),
            velocity: msg.data2(),
            on: true,
        }),
        // Control Change
        0xB0 => Some(ControlEvent::MidiControl {
            channel: msg.channel(),
            controller: msg.data1(),
            value: msg.data2(),
            normalized: msg.data2() as f32 / 127.0,
        }),
        // Program Change
        0xC0 => unsupported(msg),
        // Channel Aftertouch
        0xD0 => unsupported(msg),
        // Pitch Bend
        0xE0 => {
            let lsb = msg.data1() as i32;
            let msb = msg.data2() as i32;
            let val = (msb << 7) | lsb;
            let normalized = val as f32 / 8191.0; // 0.0–2.0 range, ~1.0 center
            Some(ControlEvent::MidiControl {
                channel: msg.channel(),
                controller: 128, // pseudo-controller for pitch bend
                value: ((normalized * 127.0) as u8).min(127),
                normalized,
            })
        }
        // System real-time / common
        0xF0 => match status {
            0xF2 => unsupported(msg), // Song Position
            0xF8 => Some(ControlEvent::MidiClock),
            0xFA => Some(ControlEvent::MidiTransport {
                kind: MidiTransportKind::Start,
            }),
            0xFB => Some(ControlEvent::MidiTransport {
                kind: MidiTransportKind::Continue,
            }),
            0xFC => Some(ControlEvent::MidiTransport {
                kind: MidiTransportKind::Stop,
            }),
            _ => unsupported(msg),
        },
        _ => unsupported(msg),
    }
}

#[allow(clippy::unnecessary_wraps)]
fn unsupported(_msg: &MidiMessage) -> Option<ControlEvent> {
    None
}

/// Serialize a `ControlEvent` back to a raw `MidiMessage`.
///
/// This is the reverse of [`parse_midi`]. Only Clock, Transport,
/// and Note events are supported. Other events return `None`.
pub fn serialize_to_midi(event: &ControlEvent) -> Option<MidiMessage> {
    match event {
        ControlEvent::MidiClock => Some(MidiMessage::new(0xF8, 0, 0)),
        ControlEvent::MidiTransport { kind } => {
            let status = match kind {
                MidiTransportKind::Start => 0xFA,
                MidiTransportKind::Stop => 0xFC,
                MidiTransportKind::Continue => 0xFB,
            };
            Some(MidiMessage::new(status, 0, 0))
        }
        ControlEvent::MidiNote {
            note, velocity, on, ..
        } => {
            let status = if *on { 0x90 } else { 0x80 };
            Some(MidiMessage::new(
                status,
                *note,
                if *on { *velocity } else { 0 },
            ))
        }
        _ => None,
    }
}

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

    #[test]
    fn test_serialize_midi_clock_roundtrip() {
        let event = ControlEvent::MidiClock;
        let msg = serialize_to_midi(&event).unwrap();
        let back = parse_midi(&msg).unwrap();
        assert_eq!(back, event);
    }

    #[test]
    fn test_serialize_midi_transport_roundtrip() {
        for kind in [
            MidiTransportKind::Start,
            MidiTransportKind::Stop,
            MidiTransportKind::Continue,
        ] {
            let event = ControlEvent::MidiTransport { kind };
            let msg = serialize_to_midi(&event).unwrap();
            let back = parse_midi(&msg).unwrap();
            assert_eq!(back, event);
        }
    }

    #[test]
    fn test_serialize_midi_note_roundtrip() {
        let event = ControlEvent::MidiNote {
            channel: 0,
            note: 64,
            velocity: 100,
            on: true,
        };
        let msg = serialize_to_midi(&event).unwrap();
        assert_eq!(msg, MidiMessage::new(0x90, 64, 100));

        let event_off = ControlEvent::MidiNote {
            channel: 0,
            note: 64,
            velocity: 0,
            on: false,
        };
        let msg_off = serialize_to_midi(&event_off).unwrap();
        assert_eq!(msg_off, MidiMessage::new(0x80, 64, 0));
    }

    #[test]
    fn test_serialize_unsupported_returns_none() {
        let event = ControlEvent::MidiControl {
            channel: 0,
            controller: 7,
            value: 100,
            normalized: 0.8,
        };
        assert!(serialize_to_midi(&event).is_none());
    }
}