midi-io 0.2.1

Stream and send strictly-typed MIDI messages
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

use futures_channel::oneshot;
use wasm_bindgen::closure::Closure;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use wasm_bindgen_futures::spawn_local;
use wasm_bindgen_futures::JsFuture;
use web_sys::DomException;
use web_sys::MidiAccess;
use web_sys::MidiConnectionEvent;
use web_sys::MidiInput;
use web_sys::MidiMessageEvent;
use web_sys::MidiOptions;
use web_sys::MidiOutput;
use web_sys::MidiPort;
use web_sys::MidiPortDeviceState;
use web_sys::MidiPortType;

use super::common::prune_send;
use super::common::Command;
use super::common::DestinationSubscribers;
use super::common::SourceSubscribers;
use super::common::StreamReceivers;
use super::common::StreamSenders;
use super::log_error;
use super::MutexExt;
use crate::midi::stream_parser::StreamParser;
use crate::name::Name;
use crate::time::Instant;
use crate::Destination;
use crate::DestinationChange;
use crate::Error;
use crate::IoError;
use crate::PortId;
use crate::Source;
use crate::SourceChange;

fn port_handle(js_id: &str) -> u64 {
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for byte in js_id.bytes() {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
    }
    hash
}

fn find_input(inputs: &js_sys::Map, handle: u64) -> Option<MidiInput> {
    let mut found = None;
    inputs.for_each(&mut |value, _key| {
        let input: MidiInput = value.unchecked_into();
        if port_handle(&input.id()) == handle {
            found = Some(input);
        }
    });
    found
}

fn find_output(outputs: &js_sys::Map, handle: u64) -> Option<MidiOutput> {
    let mut found = None;
    outputs.for_each(&mut |value, _key| {
        let output: MidiOutput = value.unchecked_into();
        if port_handle(&output.id()) == handle {
            found = Some(output);
        }
    });
    found
}

struct SourceConnection {
    input: MidiInput,
    _on_message: Closure<dyn FnMut(MidiMessageEvent)>,
}

struct WebState {
    cmd_rx: std::sync::mpsc::Receiver<Command>,
    source_subs: SourceSubscribers,
    destination_subs: DestinationSubscribers,
    access: Option<MidiAccess>,
    connections: HashMap<u64, SourceConnection>,
    destinations: HashMap<u64, MidiOutput>,
    _on_statechange: Option<Closure<dyn FnMut(MidiConnectionEvent)>>,
}

impl WebState {
    fn list_sources(&self) -> Vec<Source> {
        self.ports(MidiPortType::Input)
            .into_iter()
            .map(|(id, name)| Source {
                id,
                name,
                is_virtual: false,
            })
            .collect()
    }

    fn list_destinations(&self) -> Vec<Destination> {
        self.ports(MidiPortType::Output)
            .into_iter()
            .map(|(id, name)| Destination {
                id,
                name,
                is_virtual: false,
            })
            .collect()
    }

    fn ports(&self, kind: MidiPortType) -> Vec<(PortId, String)> {
        let Some(access) = &self.access else {
            return Vec::new();
        };
        let map: js_sys::Map = match kind {
            MidiPortType::Output => access.outputs().unchecked_into(),
            _ => access.inputs().unchecked_into(),
        };
        let mut out = Vec::new();
        map.for_each(&mut |value, _key| {
            let port: MidiPort = value.unchecked_into();
            out.push((
                PortId(port_handle(&port.id())),
                port.name().unwrap_or_default(),
            ));
        });
        out
    }

    fn connect_source(&mut self, port_id: PortId) -> Result<StreamReceivers, Error> {
        let handle = port_id.0;
        if self.connections.contains_key(&handle) {
            return Err(IoError::AlreadyConnected.into());
        }
        let Some(access) = self.access.clone() else {
            return Err(IoError::NotReady.into());
        };
        let inputs: js_sys::Map = access.inputs().unchecked_into();
        let Some(input) = find_input(&inputs, handle) else {
            return Err(IoError::PortNotFound.into());
        };
        let (senders, receivers) = StreamSenders::channel();
        let mut parser = StreamParser::new();
        let on_message =
            Closure::<dyn FnMut(MidiMessageEvent)>::new(move |ev: MidiMessageEvent| {
                match ev.data() {
                    Ok(bytes) => {
                        let timestamp = Instant::now();
                        parser.push(&bytes, &mut |event| senders.emit(timestamp, event));
                    }
                    Err(e) => log_error!("failed to read MIDI message data: {e:?}"),
                }
            });
        input.set_onmidimessage(Some(on_message.as_ref().unchecked_ref()));
        self.connections.insert(
            handle,
            SourceConnection {
                input,
                _on_message: on_message,
            },
        );
        Ok(receivers)
    }

    fn disconnect(&mut self, port_id: PortId) {
        if let Some(conn) = self.connections.remove(&port_id.0) {
            conn.input.set_onmidimessage(None);
        }
    }

    fn send(&self, port_id: PortId, data: &[u8]) -> Result<(), Error> {
        let Some(output) = self.destinations.get(&port_id.0) else {
            return Err(IoError::PortDisconnected.into());
        };
        let array = js_sys::Uint8Array::from(data);
        output
            .send(array.as_ref())
            .map_err(|e| map_web_error(e).into())
    }

    fn disconnect_destination(&mut self, port_id: PortId) {
        if let Some(output) = self.destinations.remove(&port_id.0) {
            let _ = output.close();
        }
    }
}

pub(super) struct Backend {
    state: Rc<RefCell<WebState>>,
}

impl Backend {
    pub(super) fn start(
        _name: Name,
        source_subs: SourceSubscribers,
        destination_subs: DestinationSubscribers,
        cmd_rx: std::sync::mpsc::Receiver<Command>,
        _cmd_tx: &std::sync::mpsc::SyncSender<Command>,
        ready_tx: oneshot::Sender<Result<(), Error>>,
    ) -> Result<Self, Error> {
        let state = Rc::new(RefCell::new(WebState {
            cmd_rx,
            source_subs,
            destination_subs,
            access: None,
            connections: HashMap::new(),
            destinations: HashMap::new(),
            _on_statechange: None,
        }));

        let init_state = Rc::clone(&state);
        spawn_local(async move {
            match request_access().await {
                Ok(access) => {
                    install_statechange(&init_state, &access);
                    init_state.borrow_mut().access = Some(access);
                    let _ = ready_tx.send(Ok(()));
                    drain(&init_state);
                }
                Err(e) => {
                    let _ = ready_tx.send(Err(e));
                }
            }
        });

        Ok(Backend { state })
    }

    pub(super) fn wake(&self) {
        let state = Rc::clone(&self.state);
        spawn_local(async move {
            drain(&state);
        });
    }

    pub(super) fn on_drop(&self, _cmd_tx: &std::sync::mpsc::SyncSender<Command>) {
        let mut st = self.state.borrow_mut();
        if let Some(access) = &st.access {
            access.set_onstatechange(None);
        }
        for (_, conn) in st.connections.drain() {
            conn.input.set_onmidimessage(None);
        }
        for (_, output) in st.destinations.drain() {
            let _ = output.close();
        }
        st._on_statechange = None;
        st.access = None;
    }
}

async fn request_access() -> Result<MidiAccess, Error> {
    let window = web_sys::window().ok_or(IoError::Unsupported)?;
    let options = MidiOptions::new();
    options.set_sysex(true);
    let promise = window
        .navigator()
        .request_midi_access_with_options(&options)
        .map_err(map_web_error)?;
    let value = JsFuture::from(promise).await.map_err(map_web_error)?;
    Ok(value.unchecked_into::<MidiAccess>())
}

fn map_web_error(value: JsValue) -> IoError {
    let Ok(exception) = value.dyn_into::<DomException>() else {
        return IoError::Unsupported;
    };
    match exception.name().as_str() {
        "SecurityError" | "NotAllowedError" => IoError::PermissionDenied,
        "NotSupportedError" => IoError::Unsupported,
        "InvalidStateError" => IoError::PortDisconnected,
        _ => IoError::Web(exception.message()),
    }
}

fn connect_destination(
    state: &Rc<RefCell<WebState>>,
    port_id: PortId,
    reply: oneshot::Sender<Result<(), Error>>,
) {
    let handle = port_id.0;
    let state = Rc::clone(state);
    spawn_local(async move {
        let output = {
            let st = state.borrow();
            if st.destinations.contains_key(&handle) {
                let _ = reply.send(Err(IoError::AlreadyConnected.into()));
                return;
            }
            let Some(access) = st.access.clone() else {
                let _ = reply.send(Err(IoError::NotReady.into()));
                return;
            };
            let outputs: js_sys::Map = access.outputs().unchecked_into();
            let Some(output) = find_output(&outputs, handle) else {
                let _ = reply.send(Err(IoError::PortNotFound.into()));
                return;
            };
            output
        };
        match JsFuture::from(output.open()).await {
            Ok(_) => {
                state.borrow_mut().destinations.insert(handle, output);
                let _ = reply.send(Ok(()));
            }
            Err(e) => {
                let _ = reply.send(Err(map_web_error(e).into()));
            }
        }
    });
}

fn install_statechange(state: &Rc<RefCell<WebState>>, access: &MidiAccess) {
    let cb_state = Rc::clone(state);
    let closure = Closure::<dyn FnMut(MidiConnectionEvent)>::new(move |ev: MidiConnectionEvent| {
        handle_statechange(&cb_state, ev);
    });
    access.set_onstatechange(Some(closure.as_ref().unchecked_ref()));
    state.borrow_mut()._on_statechange = Some(closure);
}

fn handle_statechange(state: &Rc<RefCell<WebState>>, ev: MidiConnectionEvent) {
    let Some(port) = ev.port() else {
        return;
    };
    let handle = port_handle(&port.id());
    let mut st = state.borrow_mut();
    let connected = port.state() == MidiPortDeviceState::Connected;
    let name = port.name().unwrap_or_default();
    match port.type_() {
        MidiPortType::Input => {
            let source = Source {
                id: PortId(handle),
                name,
                is_virtual: false,
            };
            let change = if connected {
                SourceChange::Added(source)
            } else {
                SourceChange::Removed(source)
            };
            let mut guard = st.source_subs.lock_unpoisoned();
            prune_send(&mut guard, &change);
            drop(guard);
            if !connected {
                st.disconnect(PortId(handle));
            }
        }
        MidiPortType::Output => {
            let destination = Destination {
                id: PortId(handle),
                name,
                is_virtual: false,
            };
            let change = if connected {
                DestinationChange::Added(destination)
            } else {
                DestinationChange::Removed(destination)
            };
            let mut guard = st.destination_subs.lock_unpoisoned();
            prune_send(&mut guard, &change);
            drop(guard);
            if !connected {
                st.disconnect_destination(PortId(handle));
            }
        }
        _ => {}
    }
}

fn drain(state: &Rc<RefCell<WebState>>) {
    loop {
        let cmd = state.borrow_mut().cmd_rx.try_recv();
        match cmd {
            Ok(cmd) => process(state, cmd),
            Err(_) => break,
        }
    }
}

fn process(state: &Rc<RefCell<WebState>>, cmd: Command) {
    match cmd {
        Command::ListSources { reply } => {
            let sources = state.borrow_mut().list_sources();
            let _ = reply.send(Ok(sources));
        }
        Command::ListDestinations { reply } => {
            let destinations = state.borrow_mut().list_destinations();
            let _ = reply.send(Ok(destinations));
        }
        Command::ConnectSource { port_id, reply } => {
            let result = state.borrow_mut().connect_source(port_id);
            let _ = reply.send(result);
        }
        Command::Disconnect(port_id) => {
            state.borrow_mut().disconnect(port_id);
        }
        Command::ConnectDestination { port_id, reply } => {
            connect_destination(state, port_id, reply);
        }
        Command::SendMidi {
            port_id,
            msg,
            reply,
        } => {
            let result = state.borrow().send(port_id, &msg);
            let _ = reply.send(result);
        }
        Command::SendSysex {
            port_id,
            data,
            reply,
        } => {
            let result = state.borrow().send(port_id, &data);
            let _ = reply.send(result);
        }
        Command::CreateVirtualSource { reply, .. } => {
            let _ = reply.send(Err(IoError::Unsupported.into()));
        }
        Command::CreateVirtualDestination { reply, .. } => {
            let _ = reply.send(Err(IoError::Unsupported.into()));
        }
        Command::SendVirtualMidi { reply, .. } => {
            let _ = reply.send(Err(IoError::Unsupported.into()));
        }
        Command::SendVirtualSysex { reply, .. } => {
            let _ = reply.send(Err(IoError::Unsupported.into()));
        }
        Command::DisconnectDestination(port_id) => {
            state.borrow_mut().disconnect_destination(port_id);
        }
        Command::DestroyVirtualSource(_) => {}
        Command::DestroyVirtualDestination(_) => {}
    }
}