moont 1.0.0

Roland CM-32L synthesizer emulator
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
// Copyright (C) 2021-2026 Geoff Hill <geoff@geoffhill.org>
// Copyright (C) 2003-2026 Dean Beeler, Jerome Fisher, Sergey V. Mikayev
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or (at
// your option) any later version. Read COPYING.LESSER.txt for details.

//! Roland CM-32L synthesizer emulator.
//!
//! Renders 32kHz stereo PCM audio from MIDI input. `no_std` compatible
//! (requires `alloc`). Based on [Munt](https://github.com/munt/munt/),
//! with no external dependencies.
//!
//! The CM-32L is in the [MT-32 family](https://en.wikipedia.org/wiki/Roland_MT-32)
//! of synthesizers. This hardware predates
//! [General MIDI](https://en.wikipedia.org/wiki/General_MIDI), but
//! [many early 1990s PC games][vogons] directly support these synths.
//!
//! [vogons]: https://www.vogonswiki.com/index.php/List_of_MT-32-compatible_computer_games
//!
//! # Quick start
//!
//! ```no_run
//! use moont::{Frame, Synth, cm32l};
//!
//! let control = std::fs::read("CM32L_CONTROL.ROM").unwrap();
//! let pcm = std::fs::read("CM32L_PCM.ROM").unwrap();
//! let rom = cm32l::Rom::new(&control, &pcm).expect("invalid ROM");
//! let mut synth = cm32l::Device::new(rom);
//!
//! // Note On: MIDI channel 2, note C4, max velocity.
//! synth.play_msg(0x7f3c91);
//!
//! // Render 1 second of audio at 32 kHz.
//! let mut buf = vec![Frame(0, 0); 32000];
//! synth.render(&mut buf);
//!
//! // Note Off: MIDI channel 2.
//! synth.play_msg(0x3c81);
//! ```
//!
//! # Loading ROMs
//!
//! The CM-32L ROMs are not distributed with this crate. Load them at
//! runtime with [`cm32l::Rom::new`]:
//!
//! ```no_run
//! # use moont::cm32l;
//! let control = std::fs::read("CM32L_CONTROL.ROM").unwrap();
//! let pcm = std::fs::read("CM32L_PCM.ROM").unwrap();
//! let rom = cm32l::Rom::new(&control, &pcm).expect("invalid ROM");
//! ```
//!
//! With the **`bundle-rom`** feature, ROMs are parsed at compile time and
//! embedded in the binary, enabling `cm32l::Rom::bundled()`. Place
//! `CM32L_CONTROL.ROM` and `CM32L_PCM.ROM` in `rom/` inside the crate
//! directory, or set the `MOONT_ROM_DIR` environment variable:
//!
//! ```ignore
//! let rom = cm32l::Rom::bundled();
//! ```
//!
//! # General MIDI translation
//!
//! The CM-32L uses its own instrument map. When the input is General MIDI,
//! use [`cm32l::GmDevice`] to translate program changes, drum notes, and pan
//! direction into CM-32L equivalents. GM defaults are automatically
//! reapplied after any device reset:
//!
//! ```no_run
//! use moont::{Synth, cm32l};
//!
//! let control = std::fs::read("CM32L_CONTROL.ROM").unwrap();
//! let pcm = std::fs::read("CM32L_PCM.ROM").unwrap();
//! let mut synth =
//!     cm32l::GmDevice::new(cm32l::Rom::new(&control, &pcm).unwrap());
//! synth.play_msg(0x7f3c90);
//! ```
//!
//! # Type-safe MIDI messages
//!
//! The [`Message`] type provides validated message construction as
//! an alternative to raw `u32` values:
//!
//! ```
//! use moont::Message;
//!
//! let msg = Message::note_on(60, 100, 0).unwrap();
//! let packed: u32 = msg.try_into().unwrap();
//! ```
//!
//! # Features
//!
//! | Feature | Description |
//! |---------|-------------|
//! | **`bundle-rom`** | Embed pre-parsed ROMs in the binary (enables `cm32l::Rom::bundled()`) |
//! | **`tracing`** | Emit [`tracing`](https://docs.rs/tracing) spans and events |
//!
//! # Related crates
//!
//! | Crate | Description |
//! |-------|-------------|
//! | [`moont-render`](https://docs.rs/moont-render) | Render .mid files to .wav |
//! | [`moont-live`](https://docs.rs/moont-live) | Real-time ALSA MIDI sink |
//! | [`moont-web`](https://docs.rs/moont-web) | WebAssembly wrapper with Web Audio API |

#![no_std]

extern crate alloc;

#[cfg(feature = "tracing")]
macro_rules! trace {
    ($($arg:tt)*) => { ::tracing::trace!($($arg)*) };
}
#[cfg(not(feature = "tracing"))]
macro_rules! trace {
    ($($arg:tt)*) => {};
}

#[cfg(feature = "tracing")]
macro_rules! debug {
    ($($arg:tt)*) => { ::tracing::debug!($($arg)*) };
}
#[cfg(not(feature = "tracing"))]
macro_rules! debug {
    ($($arg:tt)*) => {};
}

#[cfg(feature = "tracing")]
macro_rules! info {
    ($($arg:tt)*) => { ::tracing::info!($($arg)*) };
}
#[cfg(not(feature = "tracing"))]
macro_rules! info {
    ($($arg:tt)*) => {};
}

#[cfg(feature = "tracing")]
macro_rules! warn {
    ($($arg:tt)*) => { ::tracing::warn!($($arg)*) };
}
#[cfg(not(feature = "tracing"))]
macro_rules! warn {
    ($($arg:tt)*) => {};
}

#[cfg(feature = "tracing")]
macro_rules! debug_span {
    ($($arg:tt)*) => { ::tracing::debug_span!($($arg)*).entered() };
}
#[cfg(not(feature = "tracing"))]
macro_rules! debug_span {
    ($($arg:tt)*) => {
        ()
    };
}

use alloc::boxed::Box;
use core::{error, fmt};
pub use midi::{Error as MidiError, Message};
use rom::Rom;

mod dispatch;
mod element;
pub mod gm;
mod lpf;
mod midi;
mod midiqueue;
pub mod param;
mod pcm;
mod ramp;
mod render;
mod reverb;
mod rom;
pub mod smf;
mod synth;
mod sysex;
mod tables;
mod tva;
mod tvf;
mod tvp;

#[cfg(feature = "bundle-rom")]
mod bundle;

/// Audio frames (stereo samples) per second.
pub const SAMPLE_RATE: u32 = 32000;

#[cfg(feature = "bundle-rom")]
impl Rom {
    /// Returns the bundled ROM (pre-parsed at compile time).
    ///
    /// Each call returns a new [`cm32l::Rom`] containing references to the
    /// embedded ROM data. This is a cheap operation (two pointers).
    ///
    /// Requires the **`bundle-rom`** feature. At compile time, the build
    /// script reads ROMs from `MOONT_ROM_DIR` if set, otherwise `rom/`
    /// within the crate directory.
    pub const fn bundled() -> Rom {
        bundle::bundled_rom()
    }
}

/// CM-32L-specific API surface.
pub mod cm32l {
    pub use crate::CM32L as Device;
    pub use crate::gm::GmSynth as GmDevice;
    pub use crate::midi::{MelodicInstrument, RhythmInstrument};
    pub use crate::rom::{
        CONTROL_SIZE, ControlArray, Error as RomError, PADDED_TIMBRE_SIZE,
        PCM_SIZE, PcmArray, PcmMeta, RawTimbreBank, Rom, TIMBRES_COUNT,
    };
}

use element::{PartArena, PartialArena, PolyArena};
use lpf::CoarseLpf;
use midiqueue::MidiQueue;
use reverb::Reverb;
use sysex::MemState;

/// Stereo PCM audio frame of two native-endian signed 16-bit samples.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
#[repr(C)]
pub struct Frame(pub i16, pub i16);

/// High-level runtime control commands for a synth instance.
#[non_exhaustive]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ControlCommand {
    /// Set program on melodic part (part 0-7, program 0-127).
    SetPartProgram {
        /// Zero-based melodic part index in the range `0..=7`.
        part: u8,
        /// CM-32L program number in the range `0..=127`.
        program: u8,
    },
    /// Set part volume (part 0-8, volume 0-100).
    SetPartVolume {
        /// Zero-based part index in the range `0..=8`.
        part: u8,
        /// Part output level in the range `0..=100`.
        volume: u8,
    },
    /// Set master volume (0-100).
    SetMasterVolume {
        /// Master output level in the range `0..=100`.
        volume: u8,
    },
    /// Set reverb mode only.
    SetReverbMode {
        /// Reverb mode in the range `0..=3`.
        mode: u8,
    },
    /// Set reverb time only.
    SetReverbTime {
        /// Reverb time in the range `0..=7`.
        time: u8,
    },
    /// Set reverb level only.
    SetReverbLevel {
        /// Reverb send level in the range `0..=7`.
        level: u8,
    },
    /// Reset synthesizer state to power-on defaults.
    Reset,
}

/// Error applying [`ControlCommand`].
#[non_exhaustive]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ControlError {
    /// Part index exceeds 8.
    PartOutOfRange(u8),
    /// Melodic part index exceeds 7.
    MelodicPartOutOfRange(u8),
    /// Program number exceeds 127.
    ProgramOutOfRange(u8),
    /// Volume value exceeds 100.
    VolumeOutOfRange(u8),
    /// Reverb mode exceeds 3.
    ReverbModeOutOfRange(u8),
    /// Reverb time exceeds 7.
    ReverbTimeOutOfRange(u8),
    /// Reverb level exceeds 7.
    ReverbLevelOutOfRange(u8),
}

impl fmt::Display for ControlError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            ControlError::PartOutOfRange(part) => {
                write!(f, "part out of range (expected 0-8): {part}")
            }
            ControlError::MelodicPartOutOfRange(part) => {
                write!(f, "melodic part out of range (expected 0-7): {part}")
            }
            ControlError::ProgramOutOfRange(program) => {
                write!(f, "program out of range (expected 0-127): {program}")
            }
            ControlError::VolumeOutOfRange(volume) => {
                write!(f, "volume out of range (expected 0-100): {volume}")
            }
            ControlError::ReverbModeOutOfRange(mode) => {
                write!(f, "reverb mode out of range: {mode}")
            }
            ControlError::ReverbTimeOutOfRange(time) => {
                write!(f, "reverb time out of range: {time}")
            }
            ControlError::ReverbLevelOutOfRange(level) => {
                write!(f, "reverb level out of range: {level}")
            }
        }
    }
}

impl error::Error for ControlError {}

/// Interface for MIDI synthesizers.
///
/// The event queue preserves insertion order and does not sort by timestamp.
/// Callers should enqueue events in playback order.
pub trait Synth {
    /// Returns the number of frames rendered so far.
    fn current_time(&self) -> u32;

    /// Enqueues one MIDI message at a specific frame.
    ///
    /// A MIDI baud rate transfer delay is added to `time` before
    /// enqueuing: 24 frames for 3-byte messages, 16 frames for
    /// 2-byte messages (program change and channel pressure).
    ///
    /// Returns `false` only if the internal MIDI queue is full. Invalid
    /// channel messages are ignored and still return `true`.
    fn play_msg_at(&mut self, msg: u32, time: u32) -> bool;

    /// Enqueues one MIDI message starting from the current frame.
    ///
    /// Equivalent to `play_msg_at(msg, current_time())`. The message
    /// is processed after the MIDI baud rate transfer delay (16 or
    /// 24 frames), not at the current frame itself.
    fn play_msg(&mut self, msg: u32) -> bool {
        self.play_msg_at(msg, self.current_time())
    }

    /// Enqueues one MIDI System Exclusive message at a specific frame.
    ///
    /// No transfer delay is added; the message is processed at
    /// exactly the given frame. Returns `false` only if the internal
    /// MIDI queue is full.
    fn play_sysex_at(&mut self, sysex: &[u8], time: u32) -> bool;

    /// Enqueues one MIDI System Exclusive message at the current frame.
    ///
    /// Equivalent to `play_sysex_at(sysex, current_time())`. The
    /// message is processed immediately at the current frame.
    fn play_sysex(&mut self, sysex: &[u8]) -> bool {
        self.play_sysex_at(sysex, self.current_time())
    }

    /// Renders audio samples into a slice of frames.
    ///
    /// The output slice is filled with stereo audio frames. Each [`Frame`]
    /// is comprised of two 16-bit, native-endian, signed PCM audio samples.
    ///
    /// The internal clock is advanced by the number of frames rendered.
    fn render(&mut self, out: &mut [Frame]);

    /// Applies a typed runtime control command.
    fn apply_command(
        &mut self,
        command: ControlCommand,
    ) -> Result<(), ControlError>;
}

/// CM-32L synthesizer state.
#[non_exhaustive]
#[derive(Debug)]
pub struct CM32L {
    time: u32,
    rom: Rom,
    mem: Box<MemState>,
    midi_queue: MidiQueue,
    parts: PartArena,
    free_polys: PolyArena,
    free_partials: PartialArena,
    reverb: Reverb,
    lpf_left: CoarseLpf,
    lpf_right: CoarseLpf,
    last_midi_timestamp: u32,
    chantable: [[u8; 9]; 16],
    aborting_part_ix: usize,
    master_tune_pitch_delta: i32,
}

impl CM32L {
    /// Creates a new synthesizer instance.
    ///
    /// Use the bundled ROM or load ROMs at runtime:
    /// - `cm32l::Device::new(cm32l::Rom::bundled())` - uses bundled ROM
    /// - `cm32l::Device::new(cm32l::Rom::new(ctrl, pcm)?)` - for dynamically loaded ROMs
    ///
    /// By default, the CM-32L maps part 1 to MIDI channel 2. For General MIDI
    /// sources on channel 1, use [`crate::cm32l::GmDevice`] instead.
    pub fn new(rom: Rom) -> CM32L {
        let reverb = Reverb::new();
        let mem = MemState::new(&rom);
        let master_volume = mem.master_volume;
        let parts = PartArena::new(master_volume, &rom);
        let free_partials = PartialArena::new(&rom.meta().reserve_settings);
        let mut chantable = [[0xFF; 9]; 16];
        dispatch::rebuild_chantable(&mut chantable, &mem.raw_system);
        CM32L {
            time: 0,
            rom,
            mem,
            midi_queue: MidiQueue::new(),
            parts,
            free_polys: PolyArena::new(),
            free_partials,
            reverb,
            lpf_left: CoarseLpf::new(),
            lpf_right: CoarseLpf::new(),
            last_midi_timestamp: 0,
            chantable,
            aborting_part_ix: 0,
            master_tune_pitch_delta: 0,
        }
    }

    fn apply_command_inner(
        &mut self,
        command: ControlCommand,
    ) -> Result<(), ControlError> {
        match command {
            ControlCommand::SetPartProgram { part, program } => {
                if part > 7 {
                    return Err(ControlError::MelodicPartOutOfRange(part));
                }
                if program > 127 {
                    return Err(ControlError::ProgramOutOfRange(program));
                }
                let idx = part as usize;
                self.parts.parts[idx].hold_pedal = false;
                self.parts.parts[idx].all_sound_off(
                    &mut self.free_polys,
                    &mut self.free_partials,
                    &self.mem,
                );
                self.parts.parts[idx].program = program as usize;
                self.mem.set_program(idx, program as usize);
                let timbre = &self.mem.timbre_temp[idx];
                self.free_partials.update_tvp_params(idx, timbre);
                Ok(())
            }
            ControlCommand::SetPartVolume { part, volume } => {
                if part > 8 {
                    return Err(ControlError::PartOutOfRange(part));
                }
                if volume > 100 {
                    return Err(ControlError::VolumeOutOfRange(volume));
                }
                let idx = part as usize;
                self.mem.raw_patch_temp[idx][8] = volume;
                self.mem.patch_temp[idx].output_level = volume as usize;
                self.parts.parts[idx].amp_ctx.part_volume = volume as usize;
                Ok(())
            }
            ControlCommand::SetMasterVolume { volume } => {
                if volume > 100 {
                    return Err(ControlError::VolumeOutOfRange(volume));
                }
                self.mem.raw_system[22] = volume;
                self.mem.master_volume = volume as usize;
                for part in &mut self.parts.parts {
                    part.amp_ctx.master_volume = volume as usize;
                }
                Ok(())
            }
            ControlCommand::SetReverbMode { mode } => {
                if mode > 3 {
                    return Err(ControlError::ReverbModeOutOfRange(mode));
                }
                self.mem.raw_system[1] = mode;
                self.reverb.set_mode(mode);
                Ok(())
            }
            ControlCommand::SetReverbTime { time } => {
                if time > 7 {
                    return Err(ControlError::ReverbTimeOutOfRange(time));
                }
                self.mem.raw_system[2] = time;
                self.reverb.set_time(time);
                Ok(())
            }
            ControlCommand::SetReverbLevel { level } => {
                if level > 7 {
                    return Err(ControlError::ReverbLevelOutOfRange(level));
                }
                self.mem.raw_system[3] = level;
                self.reverb.set_level(level);
                Ok(())
            }
            ControlCommand::Reset => {
                self.reset();
                Ok(())
            }
        }
    }
}