xmrs 0.14.6

Read, edit and serialize SoundTracker music with pleasure — MOD/XM/S3M/IT/DW import plus SID & OPL chip synthesis, no_std.
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
//! High-level OPL driver: translates tracker-channel gestures into chip
//! calls. A Rust re-implementation of the documented AdLib programming
//! procedure in Schism's `player/snd_fm.c` (note→F-number/block,
//! `OPL_Touch` volume law, `OPL_Pan`, voice allocation) — the procedure
//! is documented hardware programming, not copied code.

use alloc::vec;
use alloc::vec::Vec;

use crate::tracker::instr_opl::{InstrOpl, MdiOpl, OplRhythm};

use super::{ChannelPatch, OpPatch, OplChip, OPL_NATIVE_RATE};

/// Per-hardware-slot ownership + the patch's resting carrier/modulator
/// total levels (needed to recompute volume via the `OPL_Touch` law).
#[derive(Clone, Copy, Default)]
struct SlotState {
    owner: Option<usize>, // tracker channel currently holding this slot
    keyed: bool,
    carrier_tl: u8,
    modulator_tl: u8,
    additive: bool,
}

/// A live percussion voice's placement + resting level, so a later volume change can re-apply
/// `OPL_Touch` to the correct operator (a rhythm drum shares its chip channel with another drum,
/// so it can't be addressed through the melodic slot table).
#[derive(Clone, Copy)]
struct RhythmVoice {
    track_ch: usize,
    ch: usize,
    carrier: bool,
    full: bool,
    resting_tl: u8,
}

pub struct OplDriver {
    chip: OplChip,
    slots: Vec<SlotState>,
    /// Current rhythm register (0xBD) drum bits, and which tracker channel triggered each drum
    /// (so note-off clears the right bit). Empty until a percussion instrument plays.
    rhythm_owner: Vec<(usize, u8)>,
    /// Per-tracker-channel percussion voice placement + resting TL (for per-note volume).
    rhythm_vol: Vec<RhythmVoice>,
    rhythm_on: bool,
}

/// `OPL_Touch` volume law (Bisqwit's ST3-measured curve, `snd_fm.c`): effective operator TL =
/// `63 + (resting_tl·vol/63) − vol`, clamped to 0..63.
fn touch_tl(resting_tl: u8, vol: u8) -> u8 {
    let v = vol.min(63) as i32;
    (63 + (resting_tl as i32 * v / 63) - v).clamp(0, 63) as u8
}

/// Fixed rhythm placement of a percussion role: `(chip channel, use carrier operator?, full
/// 2-op channel?, 0xBD drum bit)`. BD is a full FM channel (both operators); the others are
/// single operators sharing channels 7 and 8.
fn rhythm_placement(role: OplRhythm) -> Option<(usize, bool, bool, u8)> {
    match role {
        OplRhythm::Melodic => None,
        OplRhythm::BassDrum => Some((6, false, true, 0x10)),
        OplRhythm::HiHat => Some((7, false, false, 0x01)),
        OplRhythm::Snare => Some((7, true, false, 0x08)),
        OplRhythm::TomTom => Some((8, false, false, 0x04)),
        OplRhythm::Cymbal => Some((8, true, false, 0x02)),
    }
}

impl OplDriver {
    pub fn new(output_rate: u32) -> Self {
        let chip = OplChip::new(output_rate);
        let n = chip.channel_count();
        Self {
            chip,
            slots: vec![SlotState::default(); n],
            rhythm_owner: Vec::new(),
            rhythm_vol: Vec::new(),
            rhythm_on: false,
        }
    }

    /// Import the imports needed for rhythm mapping (kept local to avoid a wide `use`).
    fn drum_bit_of(&self, track_ch: usize) -> Option<u8> {
        self.rhythm_owner
            .iter()
            .find(|(c, _)| *c == track_ch)
            .map(|(_, b)| *b)
    }

    /// Key on/off a rhythm drum bit in the 0xBD register and update ownership.
    fn set_drum(&mut self, track_ch: usize, bit: u8, on: bool) {
        // current 0xBD drum bits = OR of all owned bits
        self.rhythm_owner.retain(|(c, _)| *c != track_ch);
        if on {
            self.rhythm_owner.push((track_ch, bit));
        }
        let drums = self.rhythm_owner.iter().fold(0u8, |a, (_, b)| a | b);
        self.chip.write_rhythm(0x20 | drums); // bit5 = rhythm mode enabled
    }

    pub fn any_active(&self) -> bool {
        self.chip.any_active()
    }

    pub fn render_frame(&mut self) -> (i32, i32) {
        self.chip.render_frame()
    }

    /// Find (or reuse) a hardware slot for a tracker channel. Prefers the
    /// channel's existing slot, then a silent/free slot, then steals the
    /// first slot (mirrors `snd_fm.c`'s GetVoice/SetVoice intent — when
    /// the chip is oversubscribed something has to give).
    fn assign_slot(&mut self, track_ch: usize) -> usize {
        // In rhythm mode, channels 6/7/8 are reserved for percussion — melodic notes avoid them.
        let melodic_max = if self.rhythm_on {
            self.slots.len().min(6)
        } else {
            self.slots.len()
        };
        if let Some(i) = self.slots[..melodic_max]
            .iter()
            .position(|s| s.owner == Some(track_ch))
        {
            return i;
        }
        if let Some(i) = self.slots[..melodic_max]
            .iter()
            .position(|s| s.owner.is_none() || !s.keyed)
        {
            return i;
        }
        if let Some(i) = (0..melodic_max).find(|&i| self.chip.channel_is_silent(i)) {
            return i;
        }
        0
    }

    fn slot_of(&self, track_ch: usize) -> Option<usize> {
        self.slots.iter().position(|s| s.owner == Some(track_ch))
    }

    /// Trigger an OPL instrument on a tracker channel: allocate a slot,
    /// program the patch + pitch + volume + pan, and key it on.
    pub fn note_on(
        &mut self,
        track_ch: usize,
        instr: &InstrOpl,
        milli_hz: u32,
        volume_0_63: u8,
        pan_l: bool,
        pan_r: bool,
    ) {
        // Percussion (rhythm mode): route to the fixed rhythm channel instead of a melodic slot.
        if let Some((ch, carrier, full, bit)) = rhythm_placement(instr.rhythm) {
            self.rhythm_on = true;
            let patch = channel_patch_from_instr(instr);
            let (fnum, block) = hz_to_fnum_block(milli_hz);
            // The operator that carries this drum's level: the carrier for BD (2-op) / SD / CY,
            // the modulator for HH / TT. Its patch TL is the resting level `OPL_Touch` scales.
            let resting_tl = if full || carrier {
                patch.carrier.tl
            } else {
                patch.modulator.tl
            };
            let touched = touch_tl(resting_tl, volume_0_63);
            if full {
                self.chip.set_patch(ch, &patch);
                self.chip.set_frequency(ch, fnum, block);
                self.chip.set_carrier_tl(ch, touched);
            } else {
                let op = if carrier {
                    &patch.carrier
                } else {
                    &patch.modulator
                };
                self.chip.set_rhythm_operator(ch, carrier, op);
                self.chip.set_operator_frequency(ch, carrier, fnum, block);
                self.chip.set_rhythm_operator_tl(ch, carrier, touched);
            }
            self.chip.set_pan(ch, pan_l, pan_r);
            // Remember this voice so a later `set_volume` re-touches the right operator.
            self.rhythm_vol.retain(|v| v.track_ch != track_ch);
            self.rhythm_vol.push(RhythmVoice {
                track_ch,
                ch,
                carrier,
                full,
                resting_tl,
            });
            // Retrigger: clear then set the drum bit so a repeated hit re-keys the envelope.
            self.set_drum(track_ch, bit, false);
            self.set_drum(track_ch, bit, true);
            return;
        }

        // Melodic note takes this tracker channel: drop any stale percussion binding for it.
        self.rhythm_vol.retain(|v| v.track_ch != track_ch);
        let slot = self.assign_slot(track_ch);
        let patch = channel_patch_from_instr(instr);

        self.slots[slot] = SlotState {
            owner: Some(track_ch),
            keyed: true,
            carrier_tl: patch.carrier.tl,
            modulator_tl: patch.modulator.tl,
            additive: patch.additive,
        };

        self.chip.set_patch(slot, &patch);
        let (fnum, block) = hz_to_fnum_block(milli_hz);
        self.chip.set_frequency(slot, fnum, block);
        self.chip.set_pan(slot, pan_l, pan_r);
        self.apply_volume(slot, volume_0_63);
        self.chip.key_on(slot);
    }

    pub fn set_frequency(&mut self, track_ch: usize, milli_hz: u32) {
        if let Some(slot) = self.slot_of(track_ch) {
            let (fnum, block) = hz_to_fnum_block(milli_hz);
            self.chip.set_frequency(slot, fnum, block);
        }
    }

    pub fn set_volume(&mut self, track_ch: usize, volume_0_63: u8) {
        // Percussion voice: re-touch the drum's operator TL (it isn't in the melodic slot table).
        if let Some(v) = self
            .rhythm_vol
            .iter()
            .find(|v| v.track_ch == track_ch)
            .copied()
        {
            let tl = touch_tl(v.resting_tl, volume_0_63);
            if v.full {
                self.chip.set_carrier_tl(v.ch, tl);
            } else {
                self.chip.set_rhythm_operator_tl(v.ch, v.carrier, tl);
            }
            return;
        }
        if let Some(slot) = self.slot_of(track_ch) {
            self.apply_volume(slot, volume_0_63);
        }
    }

    pub fn set_pan(&mut self, track_ch: usize, pan_l: bool, pan_r: bool) {
        if let Some(slot) = self.slot_of(track_ch) {
            self.chip.set_pan(slot, pan_l, pan_r);
        }
    }

    pub fn note_off(&mut self, track_ch: usize) {
        if let Some(bit) = self.drum_bit_of(track_ch) {
            self.set_drum(track_ch, bit, false);
            return;
        }
        if let Some(slot) = self.slot_of(track_ch) {
            self.chip.key_off(slot);
            self.slots[slot].keyed = false;
        }
    }

    /// Hard cut (note-cut / channel reused by a sample instrument): key
    /// off and release ownership immediately.
    pub fn note_cut(&mut self, track_ch: usize) {
        if let Some(bit) = self.drum_bit_of(track_ch) {
            self.set_drum(track_ch, bit, false);
            return;
        }
        if let Some(slot) = self.slot_of(track_ch) {
            self.chip.key_off(slot);
            self.slots[slot] = SlotState::default();
        }
    }

    /// Apply the per-note volume to a melodic voice via the [`touch_tl`] `OPL_Touch` law.
    /// The additive modulator TL is mirrored inside `set_carrier_tl`.
    fn apply_volume(&mut self, slot: usize, vol: u8) {
        let st = self.slots[slot];
        self.chip.set_carrier_tl(slot, touch_tl(st.carrier_tl, vol));
        let _ = st.modulator_tl;
    }
}

/// Decode an [`InstrOpl`] into a [`ChannelPatch`]. The OPL connection bit
/// (`con`) and feedback live in the modulator's register fields.
fn channel_patch_from_instr(instr: &InstrOpl) -> ChannelPatch {
    let m = op_patch(
        &instr.element.modulator,
        instr.element.modulator_wave_select,
    );
    let c = op_patch(&instr.element.carrier, instr.element.carrier_wave_select);
    ChannelPatch {
        modulator: m,
        carrier: c,
        feedback: instr.element.modulator.feedback & 0x07,
        // `con = true` → additive (AM); `false` → FM. The importer sets
        // `con` on both operators from the same register bit.
        additive: instr.element.modulator.con,
    }
}

fn op_patch(mdi: &MdiOpl, waveform: u8) -> OpPatch {
    OpPatch {
        mul: mdi.multiple,
        waveform,
        tl: mdi.total_level,
        ksl: mdi.ksl,
        ksr: mdi.ksr,
        sustaining: mdi.eg,
        attack: mdi.attack,
        decay: mdi.decay,
        sustain: mdi.sustain,
        release: mdi.release,
        am: mdi.am,
        vib: mdi.vib,
    }
}

/// Convert a frequency in milli-Hertz to an OPL (F-number, block) pair,
/// integer-only. Mirrors `snd_fm.c::milliHertzToFnum` with the documented
/// block thresholds and `fnum = (mHz << (20 − block)) / (49716·1000)`.
pub fn hz_to_fnum_block(milli_hz: u32) -> (u16, u8) {
    let mhz = milli_hz as u64;
    if mhz == 0 {
        return (0, 0);
    }
    let block: u32 = if mhz > 3_104_215 {
        7
    } else if mhz > 1_552_107 {
        6
    } else if mhz > 776_053 {
        5
    } else if mhz > 388_026 {
        4
    } else if mhz > 194_013 {
        3
    } else if mhz > 97_006 {
        2
    } else if mhz > 48_503 {
        1
    } else {
        0
    };
    let denom = OPL_NATIVE_RATE as u64 * 1000;
    let mut fnum = (mhz << (20 - block)) / denom;
    let mut block = block;
    // Carry into the next block if the F-number overflowed its 10 bits.
    if fnum > 1023 && block < 7 {
        block += 1;
        fnum = (mhz << (20 - block)) / denom;
    }
    ((fnum.min(1023)) as u16, block as u8)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn fnum_block_round_trips_a440() {
        // 440 Hz → fnum/block → reconstruct freq, within a few cents.
        let (fnum, block) = hz_to_fnum_block(440_000);
        // freq = fnum * 49716 / 2^(20-block)
        let freq = (fnum as u64 * OPL_NATIVE_RATE as u64) as f64 / (1u64 << (20 - block)) as f64;
        assert!((freq - 440.0).abs() < 2.0, "freq={freq}");
    }

    #[test]
    fn rhythm_instrument_routes_to_percussion() {
        use crate::tracker::instr_opl::{InstrOpl, MdiInstr, MdiOpl, OplRhythm};
        let mut drv = OplDriver::new(44100);
        // Percussive patch (fast attack, quick decay) as a bass-drum instrument.
        let op = MdiOpl {
            multiple: 1,
            attack: 15,
            decay: 4,
            sustain: 0,
            release: 7,
            total_level: 0,
            ..Default::default()
        };
        let bd = InstrOpl {
            element: MdiInstr {
                modulator: op,
                carrier: op,
                ..Default::default()
            },
            volume: 63,
            rhythm: OplRhythm::BassDrum,
            ..Default::default()
        };
        // A bass-drum note on tracker channel 0 must produce sound via rhythm mode,
        // without consuming a melodic slot.
        drv.note_on(0, &bd, 100_000, 63, true, true);
        let mut peak = 0i32;
        for _ in 0..4410 {
            let (l, _r) = drv.render_frame();
            peak = peak.max(l.abs());
        }
        assert!(peak > 100, "bass drum silent, peak={peak}");
        assert!(
            drv.slots.iter().all(|s| s.owner.is_none()),
            "no melodic slot used"
        );
    }

    /// A rhythm drum's per-note volume must attenuate its output (via `OPL_Touch` on the drum's
    /// operator), for both the full 2-op voice (BD) and the single-operator voices sharing a
    /// channel (carrier = CY, modulator = HH). Before this was wired, `note_on` dropped the
    /// volume for rhythm voices and every hit played at full level.
    #[test]
    fn rhythm_note_volume_attenuates() {
        use crate::tracker::instr_opl::{InstrOpl, MdiInstr, MdiOpl, OplRhythm};
        // Sustaining operator so the level is steady while we measure.
        let op = MdiOpl {
            multiple: 1,
            attack: 15,
            eg: true,
            total_level: 0,
            ..Default::default()
        };
        let make = |role| InstrOpl {
            element: MdiInstr {
                modulator: op,
                carrier: op,
                ..Default::default()
            },
            volume: 63,
            rhythm: role,
            ..Default::default()
        };
        let peak = |instr: &InstrOpl, vol: u8| -> i32 {
            let mut drv = OplDriver::new(44100);
            drv.note_on(0, instr, 200_000, vol, true, true);
            let mut p = 0i32;
            for _ in 0..4410 {
                let (l, _r) = drv.render_frame();
                p = p.max(l.abs());
            }
            p
        };
        for role in [OplRhythm::BassDrum, OplRhythm::Cymbal, OplRhythm::HiHat] {
            let instr = make(role);
            let loud = peak(&instr, 63);
            let soft = peak(&instr, 12);
            assert!(
                loud > 100,
                "{role:?}: full-volume drum silent (peak={loud})"
            );
            assert!(
                soft * 2 < loud,
                "{role:?}: note volume ignored (loud={loud}, soft={soft})"
            );
        }
    }

    /// A mid-note `set_volume` must also re-touch the drum's operator (percussion voices aren't in
    /// the melodic slot table, so the old `slot_of`-only path was a no-op for them).
    #[test]
    fn rhythm_set_volume_attenuates() {
        use crate::tracker::instr_opl::{InstrOpl, MdiInstr, MdiOpl, OplRhythm};
        let op = MdiOpl {
            multiple: 1,
            attack: 15,
            eg: true,
            total_level: 0,
            ..Default::default()
        };
        let instr = InstrOpl {
            element: MdiInstr {
                modulator: op,
                carrier: op,
                ..Default::default()
            },
            volume: 63,
            rhythm: OplRhythm::BassDrum,
            ..Default::default()
        };
        let mut drv = OplDriver::new(44100);
        drv.note_on(0, &instr, 200_000, 63, true, true);
        let mut loud = 0i32;
        for _ in 0..2205 {
            let (l, _r) = drv.render_frame();
            loud = loud.max(l.abs());
        }
        drv.set_volume(0, 8);
        // Let the level settle (the abrupt TL change clicks; skip that transient).
        for _ in 0..512 {
            let _ = drv.render_frame();
        }
        let mut soft = 0i32;
        for _ in 0..2205 {
            let (l, _r) = drv.render_frame();
            soft = soft.max(l.abs());
        }
        assert!(
            loud > 100 && soft * 2 < loud,
            "set_volume ignored (loud={loud}, soft={soft})"
        );
    }
}