Skip to main content

aether_midi/
router.rs

1//! MIDI router — dispatches events to registered instrument handlers.
2
3use std::collections::HashMap;
4use crate::event::MidiEvent;
5
6/// A function that handles a MIDI event.
7pub type MidiHandler = Box<dyn Fn(&MidiEvent) + Send + Sync>;
8
9/// Routes MIDI events to registered handlers by channel.
10pub struct MidiRouter {
11    /// Per-channel handlers. Channel 255 = all channels.
12    handlers: HashMap<u8, Vec<MidiHandler>>,
13}
14
15impl MidiRouter {
16    pub fn new() -> Self {
17        Self { handlers: HashMap::new() }
18    }
19
20    /// Register a handler for a specific MIDI channel (0–15).
21    /// Use channel 255 to receive events from all channels.
22    pub fn register(&mut self, channel: u8, handler: MidiHandler) {
23        self.handlers.entry(channel).or_default().push(handler);
24    }
25
26    /// Dispatch an event to all matching handlers.
27    pub fn dispatch(&self, event: &MidiEvent) {
28        // Channel-specific handlers
29        if let Some(handlers) = self.handlers.get(&event.channel) {
30            for h in handlers { h(event); }
31        }
32        // All-channel handlers
33        if let Some(handlers) = self.handlers.get(&255) {
34            for h in handlers { h(event); }
35        }
36    }
37
38    /// Remove all handlers for a channel.
39    pub fn clear_channel(&mut self, channel: u8) {
40        self.handlers.remove(&channel);
41    }
42}
43
44impl Default for MidiRouter {
45    fn default() -> Self { Self::new() }
46}