xmrs 0.14.2

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
//! `Cell` — one row of a [`crate::core::daw::track::Track`].
//!
//! A cell carries a typed [`CellEvent`] (the note/instrument-column
//! state) and a vector of row-pinned [`TrackEffect`]s. The instrument
//! itself is **not** stored per-cell: it lives at
//! [`crate::core::daw::track::Track::instrument`] and is invariant for
//! the lifetime of the track. The replayer reads it from a
//! per-channel state field rather than from the cell.
//!
//! Song-level globals (tempo, speed, master volume, slides) live in
//! [`crate::core::daw::automation::AutomationLane`]s, navigation
//! (pattern jump, pattern break, pattern loop, pattern delay) lives in
//! [`crate::core::daw::timeline::TimelineMap`], and MIDI macros are
//! row-local [`TrackEffect::MidiMacro`] entries.

use crate::core::cell_note::CellNote;
use crate::core::effect::TrackEffect;
use crate::core::fixed::fixed::Q15;
use crate::core::fixed::units::{PitchDelta, Volume};
use crate::core::pitch::Pitch;
use core::fmt::*;
use serde::{Deserialize, Serialize};

use alloc::vec::Vec;

/// Unified pattern-cell event.
///
/// The variants encode every `(note column, instrument column)`
/// combination an XM/IT/S3M/MOD cell can carry, plus the
/// ghost-vs-fresh distinction (whether the instrument column was
/// non-empty on the trigger row).
///
/// | Variant | Note source | Instr-col source |
/// |---|---|---|
/// | [`Self::None`] | Empty | absent |
/// | [`Self::NoteOn`] | `Play(p)` | present |
/// | [`Self::NoteOnGhost`] | `Play(p)` | absent |
/// | [`Self::InstrReset`] | Empty | present |
/// | [`Self::NoteOff`] `{ retrig: false }` | `KeyOff` (`===`) | absent |
/// | [`Self::NoteOff`] `{ retrig: true }` | `KeyOff` (`===`) | present |
/// | [`Self::NoteCut`] | `^^^` | * |
/// | [`Self::NoteFade`] | `~~~` | * |
///
/// `NoteOff::retrig` is a **semantic distinction**, not a quirk.
/// `=== xx` with an instrument column re-triggers the instrument
/// and then immediately fires `key_off`: a one-tick attack followed
/// by release — universal to XM/IT/S3M.
#[derive(Default, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum CellEvent {
    /// Nothing on this cell — both columns empty.
    #[default]
    None,
    /// Fresh trigger: play `pitch` with `velocity`, reset envelopes
    /// and sample. Instrument column is present; the actual
    /// instrument value comes from `Track.instrument`.
    NoteOn { pitch: Pitch, velocity: Volume },
    /// Ghost trigger: play `pitch` with `velocity` without resetting
    /// the live voice (`TRIGGER_KEEP_VOLUME`). Instrument column is
    /// empty; the current voice is reused for the new pitch.
    NoteOnGhost { pitch: Pitch, velocity: Volume },
    /// Instrument column present but note column empty:
    /// reload instrument defaults without re-pitching.
    /// Drives `tick0_change_instr(true)` on the channel.
    InstrReset,
    /// Release (KeyOff column, `===`).
    ///
    /// `retrig = false` (no instrument column): plain `key_off(0)`.
    /// `retrig = true` (instrument column present): re-trigger the
    /// instrument with `KEEP_PERIOD`, *then* `key_off(0)` — a click
    /// attack followed by release on the same row. Universal to
    /// XM/IT/S3M.
    NoteOff { retrig: bool },
    /// Hard cut (`^^^`). Volume → 0 immediately. The actual cut work
    /// happens via the row's [`TrackEffect::NoteCut`] effect; the
    /// note-column `^^^` is inert at dispatch.
    NoteCut,
    /// Start fadeout without releasing the envelope (`~~~`). IT-style
    /// note-column event; behaves identically regardless of
    /// instrument-column state.
    NoteFade,
}

impl CellEvent {
    /// Build a `CellEvent` from the three pattern-editor columns:
    /// note, instrument, velocity.
    ///
    /// This is the single mapping site between the column-oriented
    /// representation (still used by importers and pattern-editor
    /// UIs) and the typed variant. See
    /// [`crate::tracker::import::unit::TrackImportUnit`] for the
    /// importer-side column trio.
    #[inline]
    pub fn from_columns(note: CellNote, instrument: Option<usize>, velocity: Volume) -> Self {
        match (note, instrument) {
            (CellNote::Empty, None) => Self::None,
            (CellNote::Empty, Some(_)) => Self::InstrReset,
            (CellNote::Play(p), Some(_)) => Self::NoteOn { pitch: p, velocity },
            (CellNote::Play(p), None) => Self::NoteOnGhost { pitch: p, velocity },
            (CellNote::KeyOff, None) => Self::NoteOff { retrig: false },
            (CellNote::KeyOff, Some(_)) => Self::NoteOff { retrig: true },
            (CellNote::NoteCut, _) => Self::NoteCut,
            (CellNote::NoteFade, _) => Self::NoteFade,
        }
    }

    /// Pitch carried by note-on variants; `None` otherwise.
    #[inline]
    pub fn pitch(&self) -> Option<Pitch> {
        match *self {
            Self::NoteOn { pitch, .. } | Self::NoteOnGhost { pitch, .. } => Some(pitch),
            _ => None,
        }
    }

    /// Trigger velocity for [`Self::NoteOn`] / [`Self::NoteOnGhost`].
    /// `Volume::FULL` for any other variant — non-trigger cells have
    /// no meaningful velocity, and downstream code that always
    /// multiplies by velocity sees a no-op.
    #[inline]
    pub fn velocity(&self) -> Volume {
        match *self {
            Self::NoteOn { velocity, .. } | Self::NoteOnGhost { velocity, .. } => velocity,
            _ => Volume::FULL,
        }
    }

    /// `true` when the originating cell had a non-empty instrument
    /// column.
    #[inline]
    pub fn has_instrument_column(&self) -> bool {
        matches!(
            self,
            Self::NoteOn { .. } | Self::InstrReset | Self::NoteOff { retrig: true }
        )
    }

    /// `true` for variants that fire a fresh playback trigger
    /// (NoteOn / NoteOnGhost).
    #[inline]
    pub fn is_trigger(&self) -> bool {
        matches!(self, Self::NoteOn { .. } | Self::NoteOnGhost { .. })
    }

    /// `true` for variants that release / cut / fade the held note
    /// (NoteOff / NoteCut / NoteFade).
    #[inline]
    pub fn is_release(&self) -> bool {
        matches!(self, Self::NoteOff { .. } | Self::NoteCut | Self::NoteFade)
    }

    /// Project onto a [`CellNote`] enum (note-column only). Useful
    /// for debug printers and UI code that surfaces the
    /// soundtracker-style `--- / C-5 / === / ^^^ / ~~~` notation.
    /// Lossy: discards the retrig flag of [`Self::NoteOff`] and
    /// flattens [`Self::InstrReset`] back onto `CellNote::Empty`.
    #[inline]
    pub fn to_cell_note(&self) -> CellNote {
        match *self {
            Self::None | Self::InstrReset => CellNote::Empty,
            Self::NoteOn { pitch, .. } | Self::NoteOnGhost { pitch, .. } => CellNote::Play(pitch),
            Self::NoteOff { .. } => CellNote::KeyOff,
            Self::NoteCut => CellNote::NoteCut,
            Self::NoteFade => CellNote::NoteFade,
        }
    }
}

impl Debug for CellEvent {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
        match self {
            Self::None => write!(f, "---"),
            Self::NoteOn { pitch, .. } => write!(f, "{:?}", pitch),
            Self::NoteOnGhost { pitch, .. } => write!(f, "{:?}g", pitch),
            Self::InstrReset => write!(f, "i--"),
            Self::NoteOff { retrig: true } => write!(f, "==!"),
            Self::NoteOff { retrig: false } => write!(f, "==="),
            Self::NoteCut => write!(f, "^^^"),
            Self::NoteFade => write!(f, "~~~"),
        }
    }
}

/// One row of a [`crate::core::daw::track::Track`] — a single pattern
/// cell. Carries a typed [`CellEvent`] plus any effects pinned to
/// this row.
///
/// The instrument is **not** stored here — it lives on
/// [`crate::core::daw::track::Track::instrument`] (invariant for the
/// Track's lifetime). The replayer pushes the track's instrument
/// alongside the cell through its per-row dispatch.
///
/// Song-level globals (Bpm/Speed/GlobalVolume + slides) are not
/// row-local: they live on [`crate::core::daw::automation::AutomationLane`]s.
/// Navigation events (pattern jump / break / loop / delay) live on
/// [`crate::core::daw::timeline::TimelineMap`]. The only "global"
/// effect that stays on a cell is the MIDI macro, encoded as
/// [`TrackEffect::MidiMacro`] in `effects`.
/// RFC §2C — per-note expression (MPE). Modulation that belongs to a
/// single triggered note rather than the whole track, so two voices
/// sounding on the same channel (a held NNA ghost and a fresh note)
/// can modulate **independently**. The player snapshots it onto the
/// voice at trigger time and folds it into that voice's own pitch /
/// volume / pan — on top of the channel-wide bus (RFC §2A) and
/// whatever `ModScope` (§2B) routes.
///
/// Every field is a **neutral-at-zero delta**, so the default is
/// `NEUTRAL` and a cell that carries no expression (every tracker
/// import — the importers never populate it) leaves the voice exactly
/// as the pre-2C player did. Bit-identical by construction.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, Default, PartialEq)]
pub struct NoteExpression {
    /// Per-note pitch bend, in semitones (Q8.8). Summed into the
    /// voice pitch alongside the channel vibrato / Points transpose.
    pub pitch_bend: PitchDelta,
    /// Per-note volume delta (Q1.15 signed, MPE channel-pressure).
    /// Folded like a tremolo offset; `ZERO` = no change.
    pub volume: Q15,
    /// Per-note pan offset (Q1.15 signed). Added to the voice pan;
    /// `ZERO` = no change.
    pub pan: Q15,
}

impl NoteExpression {
    /// The do-nothing expression: every delta zero.
    pub const NEUTRAL: Self = Self {
        pitch_bend: PitchDelta::ZERO,
        volume: Q15::ZERO,
        pan: Q15::ZERO,
    };

    /// `true` when this expression has no effect — the common case
    /// (every tracker note), letting the player skip the fold.
    #[inline]
    pub fn is_neutral(&self) -> bool {
        self.pitch_bend == PitchDelta::ZERO && self.volume == Q15::ZERO && self.pan == Q15::ZERO
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
pub struct Cell {
    pub event: CellEvent,
    pub effects: Vec<TrackEffect>,
    /// RFC §2C — per-note expression (MPE). Defaults to
    /// [`NoteExpression::NEUTRAL`]; `#[serde(default)]` keeps older
    /// serialised modules readable. Tracker importers never set it.
    #[serde(default)]
    pub expression: NoteExpression,
}

impl Cell {
    /// Build a cell from the four pattern-editor columns:
    /// note, instrument, velocity, effects.
    ///
    /// The importers still surface the three event columns
    /// independently in
    /// [`crate::tracker::import::unit::TrackImportUnit`]; this helper
    /// is the single conversion site to the typed cell.
    #[inline]
    pub fn from_columns(
        note: CellNote,
        instrument: Option<usize>,
        velocity: Volume,
        effects: Vec<TrackEffect>,
    ) -> Self {
        Self {
            event: CellEvent::from_columns(note, instrument, velocity),
            effects,
            expression: NoteExpression::NEUTRAL,
        }
    }

    /// Pitch carried by note-on variants. Forwards to
    /// [`CellEvent::pitch`].
    #[inline]
    pub fn pitch(&self) -> Option<Pitch> {
        self.event.pitch()
    }

    /// Velocity attached to a trigger. Forwards to
    /// [`CellEvent::velocity`].
    #[inline]
    pub fn velocity(&self) -> Volume {
        self.event.velocity()
    }

    /// `true` when the originating cell carried an instrument column.
    /// Forwards to [`CellEvent::has_instrument_column`].
    #[inline]
    pub fn has_instrument_column(&self) -> bool {
        self.event.has_instrument_column()
    }

    pub fn has_arpeggio(&self) -> bool {
        self.effects
            .iter()
            .any(|effect| matches!(effect, TrackEffect::Arpeggio { half1: _, half2: _ }))
    }

    pub fn has_delay(&self) -> bool {
        self.effects
            .iter()
            .any(|effect| matches!(effect, TrackEffect::NoteDelay(_)))
    }

    pub fn get_delay(&self) -> usize {
        self.effects
            .iter()
            .find_map(|effect| {
                if let TrackEffect::NoteDelay(delay) = effect {
                    Some(*delay)
                } else {
                    None
                }
            })
            .unwrap_or(0)
    }

    pub fn has_note_off(&self) -> bool {
        let fx = self
            .effects
            .iter()
            .any(|effect| matches!(effect, TrackEffect::NoteOff { tick: _, past: _ }));
        fx || matches!(self.event, CellEvent::NoteOff { .. })
    }

    /// Returns true iff the slot carries a Kxx *effect* note-off.
    ///
    /// Unlike [`Self::has_note_off`], this does NOT match a note-column
    /// `===` ([`CellEvent::NoteOff`]). It is intended for replayer
    /// paths that need to apply FT2 Kxy-effect quirks without also
    /// misfiring on note-column key-offs, which have different
    /// playback semantics in FT2 (see `ft2_replayer.c:keyOff()` vs.
    /// the `keyOffCmd` / K00 paths).
    pub fn has_note_off_effect(&self) -> bool {
        self.effects
            .iter()
            .any(|effect| matches!(effect, TrackEffect::NoteOff { tick: _, past: _ }))
    }

    /// Returns true iff the slot carries a Kxx *effect* note-off whose
    /// trigger tick is 0 — i.e. specifically K00, not K01..K1F.
    ///
    /// Used by the FT2 "K00 eats note" quirk: in FT2, only K00 is
    /// handled at tickZero via the special branch in `getNewNote`,
    /// and this is what causes the note column to be skipped.
    /// Non-zero Kxy effects go through the normal note trigger path
    /// and must not short-circuit it.
    pub fn has_note_off_at_tick_zero(&self) -> bool {
        self.effects
            .iter()
            .any(|effect| matches!(effect, TrackEffect::NoteOff { tick: 0, past: _ }))
    }
}

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

    fn pitch() -> Pitch {
        Pitch::C5
    }

    #[test]
    fn from_columns_maps_every_arm() {
        // Play + instr → NoteOn
        assert!(matches!(
            CellEvent::from_columns(CellNote::Play(pitch()), Some(3), Volume::FULL),
            CellEvent::NoteOn { .. }
        ));
        // Play, no instr → NoteOnGhost
        assert!(matches!(
            CellEvent::from_columns(CellNote::Play(pitch()), None, Volume::FULL),
            CellEvent::NoteOnGhost { .. }
        ));
        // Empty + instr → InstrReset
        assert!(matches!(
            CellEvent::from_columns(CellNote::Empty, Some(0), Volume::FULL),
            CellEvent::InstrReset
        ));
        // Empty, no instr → None
        assert!(matches!(
            CellEvent::from_columns(CellNote::Empty, None, Volume::FULL),
            CellEvent::None
        ));
        // KeyOff, no instr → NoteOff{retrig:false}
        assert_eq!(
            CellEvent::from_columns(CellNote::KeyOff, None, Volume::FULL),
            CellEvent::NoteOff { retrig: false }
        );
        // KeyOff + instr → NoteOff{retrig:true}
        assert_eq!(
            CellEvent::from_columns(CellNote::KeyOff, Some(0), Volume::FULL),
            CellEvent::NoteOff { retrig: true }
        );
        // NoteCut / NoteFade collapse irrespective of instrument
        assert_eq!(
            CellEvent::from_columns(CellNote::NoteCut, None, Volume::FULL),
            CellEvent::NoteCut
        );
        assert_eq!(
            CellEvent::from_columns(CellNote::NoteCut, Some(5), Volume::FULL),
            CellEvent::NoteCut
        );
        assert_eq!(
            CellEvent::from_columns(CellNote::NoteFade, None, Volume::FULL),
            CellEvent::NoteFade
        );
        assert_eq!(
            CellEvent::from_columns(CellNote::NoteFade, Some(5), Volume::FULL),
            CellEvent::NoteFade
        );
    }

    #[test]
    fn pitch_velocity_extraction() {
        let e = CellEvent::NoteOn {
            pitch: pitch(),
            velocity: Volume::FULL,
        };
        assert_eq!(e.pitch(), Some(pitch()));
        assert_eq!(e.velocity(), Volume::FULL);

        let e = CellEvent::NoteOnGhost {
            pitch: pitch(),
            velocity: Volume::SILENT,
        };
        assert_eq!(e.pitch(), Some(pitch()));
        assert_eq!(e.velocity(), Volume::SILENT);

        // Non-trigger variants — pitch is None, velocity is FULL.
        for e in [
            CellEvent::None,
            CellEvent::InstrReset,
            CellEvent::NoteOff { retrig: false },
            CellEvent::NoteOff { retrig: true },
            CellEvent::NoteCut,
            CellEvent::NoteFade,
        ] {
            assert_eq!(e.pitch(), None);
            assert_eq!(e.velocity(), Volume::FULL);
        }
    }

    #[test]
    fn has_instrument_column_truth_table() {
        // True: instrument column non-empty AND not a pure ghost note.
        assert!(CellEvent::NoteOn {
            pitch: pitch(),
            velocity: Volume::FULL
        }
        .has_instrument_column());
        assert!(CellEvent::InstrReset.has_instrument_column());
        assert!(CellEvent::NoteOff { retrig: true }.has_instrument_column());

        assert!(!CellEvent::NoteOnGhost {
            pitch: pitch(),
            velocity: Volume::FULL
        }
        .has_instrument_column());
        assert!(!CellEvent::NoteOff { retrig: false }.has_instrument_column());
        assert!(!CellEvent::None.has_instrument_column());
        assert!(!CellEvent::NoteCut.has_instrument_column());
        assert!(!CellEvent::NoteFade.has_instrument_column());
    }

    #[test]
    fn to_cell_note_round_trip() {
        // The lossy projection must preserve the shape:
        // Empty / Play / KeyOff / NoteCut / NoteFade.
        assert_eq!(CellEvent::None.to_cell_note(), CellNote::Empty);
        assert_eq!(CellEvent::InstrReset.to_cell_note(), CellNote::Empty);
        assert_eq!(
            CellEvent::NoteOn {
                pitch: pitch(),
                velocity: Volume::FULL
            }
            .to_cell_note(),
            CellNote::Play(pitch())
        );
        assert_eq!(
            CellEvent::NoteOff { retrig: false }.to_cell_note(),
            CellNote::KeyOff
        );
        assert_eq!(
            CellEvent::NoteOff { retrig: true }.to_cell_note(),
            CellNote::KeyOff
        );
        assert_eq!(CellEvent::NoteCut.to_cell_note(), CellNote::NoteCut);
        assert_eq!(CellEvent::NoteFade.to_cell_note(), CellNote::NoteFade);
    }
}