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
//! Cell-level and song-level effect types — the discrete pieces
//! that ride on a [`Cell`] or `TimelineMap` entry.
//!
//! Three orthogonal families:
//!
//! - [`TrackEffect`] — per-cell, per-trigger effects (Volume,
//!   Panning, ChannelVolume, Arpeggio, Tremor, NoteCut, NoteDelay,
//!   NoteRetrig, MidiMacro, instrument knobs, …). Continuous
//!   families (Vibrato* / Tremolo* / Panbrello* / Portamento /
//!   TonePortamento / VolumeSlide / ChannelVolumeSlide /
//!   PanningSlide) do not live on the cell — they live exclusively
//!   on [`AutomationLane`]s.
//! - [`NavigationEffect`] — flow-control on the order list
//!   (PatternBreak, PatternDelay, PatternLoop, PositionJump).
//!   Absorbed into the [`TimelineMap`] at import time; never read at
//!   runtime.
//! - [`SongLevelEffect`] — song-wide rate / amplitude controls (Bpm,
//!   Speed, Volume, BpmSlide, VolumeSlide). Drives the song-wide
//!   [`AutomationLane`]s at extraction time.
//!
//! [`Cell`]: crate::core::cell::Cell
//! [`AutomationLane`]: crate::core::daw::automation::AutomationLane
//! [`TimelineMap`]: crate::core::daw::timeline::TimelineMap

use crate::core::fixed::fixed::Q15;
use crate::core::fixed::units::{ChannelVolume, Finetune, Panning, RetrigMul, Volume};
use crate::prelude::NewNoteAction;
use serde::{Deserialize, Serialize};

/// Volume-update rule applied at each retrigger of a `Qxy` note-
/// retrig effect. `Qxy` triggers the note every `y` ticks; the `x`
/// nibble selects one of these operators to scale or offset the
/// running volume between retrigs.
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum NoteRetrigOperator {
    #[default]
    None,
    /// Add a signed Q1.15 delta to the running volume on
    /// each retrigger. Was `f32`. Range is `[-1, +1]`; the
    /// player clamps the resulting volume to `[0, 1]`.
    Sum(Q15),
    /// Multiply the running volume on each retrigger.
    /// `RetrigMul` is Q3.13 in `[-4, +4)`, matching the IT
    /// retrigger multiplier table (`1/3`, `1/2`, `2`, `1.5`,
    /// etc.).
    Mul(RetrigMul),
}

/// Per-cell effect catalogue.
///
/// The continuous families (Vibrato* / Tremolo* / Panbrello* /
/// Portamento / TonePortamento / VolumeSlide / ChannelVolumeSlide /
/// PanningSlide) are **not** in this enum — they live exclusively on
/// [`crate::core::daw::automation::AutomationLane`]s. The runtime
/// player consults the lanes for those; the cell only carries the
/// discrete / per-trigger effects below.
#[repr(u8)]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum TrackEffect {
    /// Pitch effect
    Arpeggio {
        /// 1st halftone
        half1: usize,
        /// 2nd halftone
        half2: usize,
    },

    /// `value`, set the Channel Volume.
    /// Was `f32` — Q1.15 in `[0, 1]`. See [`ChannelVolume`].
    ChannelVolume(ChannelVolume),

    /// `bool`, round to the nearest halftone when using effects
    /// Pitch effect
    Glissando(bool),

    /// `tune`, this effet should be used together with a note.
    /// It will cause another fine-tune value to be used.
    /// Was `f32` — Q1.15 in `[-1, +1]`. See [`Finetune`].
    InstrumentFineTune(Finetune),

    /// `nna` Change Instrument New Note Action
    /// Misc effect
    InstrumentNewNoteAction(NewNoteAction),

    /// `position`, change the panning envelope position
    /// Panning effect
    InstrumentPanningEnvelopePosition(usize),

    /// `activate`, set the panning envelope on
    /// Panning effect
    InstrumentPanningEnvelope(bool),

    /// `activate`, set the pitch envelope on
    /// Pitch effect
    InstrumentPitchEnvelope(bool),

    /// `offset`, this effect should be used together with a note
    /// The sample will be played from `offset` instead of zero
    /// Misc effect
    InstrumentSampleOffset(usize),

    /// `surround`
    /// Misc effect
    InstrumentSurround(bool),

    /// `position`, change the volume envelope position
    /// Volume effect
    InstrumentVolumeEnvelopePosition(usize),

    /// `activate`, set the volume envelope on
    /// Volume effect
    InstrumentVolumeEnvelope(bool),

    /// `(tick, past)`, cut the note at the specified tick.
    /// if past is true, do it for past note too
    /// Note that it will only set the volume to zero, and the sample will still be played.
    /// Volume effect
    NoteCut {
        /// cut at tick
        tick: usize,
        /// do it for past note too
        past: bool,
    },

    /// `ticks`, this effect will delay the note the selected number of ticks
    /// Misc effect
    NoteDelay(usize),

    /// `(tick, past)`, fadeout the note at the specified tick
    /// if past is true, do it for past note too
    /// Volume effect
    NoteFadeOut {
        /// fadeout the note at the specified tick
        tick: usize,
        /// do it for past note too
        past: bool,
    },

    /// `tick`, this effect will trigger a "Note Off" at the specified tick
    /// if past is true, do it for past note too
    /// Misc effect
    NoteOff {
        /// off the note at the specified tick
        tick: usize,
        /// do it for past note too
        past: bool,
    },

    /// `(speed, volume modifier)`
    /// Misc effect
    NoteRetrig {
        speed: usize,
        volume_modifier: NoteRetrigOperator,
    },

    /// `position` Q1.15 in `[0, 1]`, sets the panning position.
    /// `0` is fully left, `1` fully right. Was `f32`. See
    /// [`Panning`].
    Panning(Panning),

    /// `(On time, Off time)`
    /// This weird effect will set the volume to zero during `Off time` number of ticks
    /// Volume effect
    Tremor {
        on_time: usize,
        /// set the volume to zero during off time numbre of ticks
        off_time: usize,
    },

    /// `(value, tick)`, set the current volume at the current tick.
    /// `value` was `f32` — Q1.15 in `[0, 1]`. See [`Volume`].
    /// Volume effect
    Volume {
        value: Volume,
        /// set at the current tick
        tick: usize,
    },

    /// MIDI macro invocation. Despite IT's classification of the
    /// macro effect as global, it is **per-channel-scoped at
    /// runtime**: the macro byte stream substitutes the channel's
    /// note / volume / pan / instrument fields, and writes through
    /// to the channel's filter envelope or MIDI-out port. The
    /// importer
    /// ([`crate::tracker::import::unit::TrackImportUnit::prepare_cell`])
    /// is the only producer.
    MidiMacro(MidiMacroType),
}

/// MIDI-macro effect variant. IT's macro system has two user-
/// visible dispatch axes and a per-channel selector register; the
/// three variants below capture them distinctly.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum MidiMacroType {
    /// `SFx` — set the channel's active parametric-macro slot to
    /// `idx` (0..15). Does not invoke the macro; the next `Zxx`
    /// with `xx < 0x80` on this channel will use it.
    SelectParametric(usize),
    /// `Zxx` with `xx < 0x80` — invoke the channel's currently
    /// selected parametric macro, substituting the byte `z` (0x7A)
    /// in the macro string with the `xx` parameter.
    Parametric(u8),
    /// `Zxx` with `xx >= 0x80` — invoke fixed macro at `idx =
    /// xx - 0x80`. The `z` byte (if present in the macro string)
    /// is substituted with the literal `xx` parameter, matching
    /// OpenMPT's interpretation.
    Fixed { idx: usize, z: u8 },
}

/// Navigation effects — control which row/order/pattern plays next.
///
/// Consumed exclusively by
/// [`crate::tracker::import::build::build_timeline_map`]: the walker
/// absorbs them into the
/// [`crate::core::daw::timeline::TimelineMap`], after which they are
/// dropped. Runtime navigation is driven by the timeline map plus
/// [`crate::core::module::Module::song_loop_to`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum NavigationEffect {
    /// `pattern-position`, jump to the next pattern and play from the specified position.
    PatternBreak(usize),

    /// `(quantity, unit)`, this effect will delay the row the selected number of units.
    /// if `unit` is true, `unit` is on tempo, `else` unit is on tick
    /// If multiple commands are on the same row, the sum of their parameters is used.
    ///
    /// All effects in the row will be repeated for each row delayed.
    ///
    /// if `unit` is true (tempo unit)
    ///     does not delay for the sum of all commands in in the row
    /// else
    ///     delays by the sum of that row
    PatternDelay {
        quantity: usize,
        /// if true, `unit` is on tempo, `else` unit is on tick
        tempo: bool,
    },

    /// `value`, if value is zero, set the loopbackpoint
    /// is value is a non-zero, loop from previous loopback point value times
    PatternLoop(usize),

    /// `position`, jump to the selected song position and play the pattern from the beginning
    PositionJump(usize),
}

/// Song-level effects — drive the song-wide [`AutomationLane`]s
/// ([`Bpm`] / [`Speed`] / [`GlobalVolume`]) at extraction time.
///
/// Consumed exclusively by [`crate::tracker::import::extract`] (and
/// by `import::memory` for the slide-memory back-fill, a
/// `pub(crate)` helper). The build-timeline pass reads `Speed` and
/// `Bpm` too — they set per-row tick spacing alongside their lane
/// representation.
///
/// [`Bpm`]: crate::core::daw::automation::AutomationTarget::Bpm
/// [`Speed`]: crate::core::daw::automation::AutomationTarget::Speed
/// [`GlobalVolume`]: crate::core::daw::automation::AutomationTarget::GlobalVolume
/// [`AutomationLane`]: crate::core::daw::automation::AutomationLane
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum SongLevelEffect {
    /// `bpm` set the BPM of the song
    Bpm(usize),

    /// `value` slide the BPM on every tick of the row
    BpmSlide(isize),

    /// `speed` set the speed of the song
    Speed(usize),

    /// `value`, set the global Volume. Was `f32` — Q1.15 in
    /// `[0, 1]`. See [`Volume`].
    Volume(Volume),

    /// `(speed, fine)`, slide the global volume up or down.
    /// `speed` is a signed Q1.15 delta-per-tick (was `f32`).
    VolumeSlide { speed: Q15, fine: bool },
}

/// Parser-side wrapper used by the importers (XM / IT / S3M / MOD)
/// to return a single typed effect from a row-byte parse. The
/// [`crate::tracker::import::unit::TrackImportUnit::push_global`]
/// helper routes each variant into its dedicated typed `Vec` on the
/// import unit:
///
/// * [`Self::Navigation`] → `TrackImportUnit::navigation`
/// * [`Self::SongLevel`]  → `TrackImportUnit::song_level`
/// * [`Self::MidiMacro`]  → `TrackImportUnit::midi_macros` (and
///   then relocated onto `cell.effects` as
///   [`TrackEffect::MidiMacro`] by `prepare_cell`).
///
/// This wrapper exists only at the parser / TIU boundary;
/// downstream consumers (`build_timeline_map`,
/// `automation_extract`, `import_memory`) see the dedicated
/// [`NavigationEffect`] / [`SongLevelEffect`] / [`MidiMacroType`]
/// types directly.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum GlobalEffect {
    Navigation(NavigationEffect),
    SongLevel(SongLevelEffect),
    MidiMacro(MidiMacroType),
}

impl From<NavigationEffect> for GlobalEffect {
    fn from(n: NavigationEffect) -> Self {
        GlobalEffect::Navigation(n)
    }
}

impl From<SongLevelEffect> for GlobalEffect {
    fn from(s: SongLevelEffect) -> Self {
        GlobalEffect::SongLevel(s)
    }
}

impl From<MidiMacroType> for GlobalEffect {
    fn from(m: MidiMacroType) -> Self {
        GlobalEffect::MidiMacro(m)
    }
}

impl TrackEffect {
    pub fn merge(&self, other: &Self) -> Option<Self> {
        match (self, other) {
            (
                TrackEffect::Arpeggio {
                    half1: h1,
                    half2: h2,
                },
                TrackEffect::Arpeggio {
                    half1: o1,
                    half2: o2,
                },
            ) => Some(TrackEffect::Arpeggio {
                half1: h1 + o1,
                half2: h2 + o2,
            }),
            (TrackEffect::ChannelVolume(value1), TrackEffect::ChannelVolume(value2)) => {
                // Two `ChannelVolume` events on one row: cumulative
                // sum (saturating in `+`), then clamped to `[0, 1]`.
                let sum = (*value1 + *value2).clamp(ChannelVolume::SILENT, ChannelVolume::FULL);
                Some(TrackEffect::ChannelVolume(sum))
            }
            (TrackEffect::Glissando(_h1), TrackEffect::Glissando(o1)) => {
                Some(TrackEffect::Glissando(*o1)) // overwrite glissando value.
            }
            (TrackEffect::InstrumentFineTune(h1), TrackEffect::InstrumentFineTune(o1)) => {
                // Two finetunes on one row → typed saturating
                // sum (kept inside Q1.15 by `Finetune`'s `+`).
                Some(TrackEffect::InstrumentFineTune(*h1 + *o1))
            }
            (
                TrackEffect::InstrumentPanningEnvelopePosition(h1),
                TrackEffect::InstrumentPanningEnvelopePosition(o1),
            ) => Some(TrackEffect::InstrumentPanningEnvelopePosition(h1 + o1)),
            (TrackEffect::InstrumentSampleOffset(h1), TrackEffect::InstrumentSampleOffset(o1)) => {
                Some(TrackEffect::InstrumentSampleOffset(h1 + o1))
            }
            (
                TrackEffect::InstrumentVolumeEnvelopePosition(h1),
                TrackEffect::InstrumentVolumeEnvelopePosition(o1),
            ) => Some(TrackEffect::InstrumentVolumeEnvelopePosition(h1 + o1)),
            // NoteCut / NoteFadeOut / NoteOff: ticks accumulate
            // additively, `past` flags OR together (a `past:true`
            // operand wins).
            (
                TrackEffect::NoteCut { tick: h1, past: h2 },
                TrackEffect::NoteCut { tick: o1, past: o2 },
            ) => Some(TrackEffect::NoteCut {
                tick: h1 + o1,
                past: *h2 || *o2,
            }),
            (
                TrackEffect::NoteFadeOut { tick: h1, past: h2 },
                TrackEffect::NoteFadeOut { tick: o1, past: o2 },
            ) => Some(TrackEffect::NoteFadeOut {
                tick: h1 + o1,
                past: *h2 || *o2,
            }),
            (
                TrackEffect::NoteOff { tick: h1, past: h2 },
                TrackEffect::NoteOff { tick: o1, past: o2 },
            ) => Some(TrackEffect::NoteOff {
                tick: h1 + o1,
                past: *h2 || *o2,
            }),
            (TrackEffect::NoteDelay(h1), TrackEffect::NoteDelay(o1)) => {
                Some(TrackEffect::NoteDelay(h1 + o1))
            }
            (
                TrackEffect::NoteRetrig {
                    speed: h1,
                    volume_modifier: h2,
                },
                TrackEffect::NoteRetrig {
                    speed: o1,
                    volume_modifier: o2,
                },
            ) => Some(TrackEffect::NoteRetrig {
                speed: h1 + o1,
                volume_modifier: match o2 {
                    NoteRetrigOperator::None => h2.clone(),
                    _ => o2.clone(),
                },
            }),
            (TrackEffect::Panning(h1), TrackEffect::Panning(o1)) => {
                // Two `Panning` events on one row → saturating
                // sum (corner case to begin with).
                Some(TrackEffect::Panning(*h1 + *o1))
            }
            (
                TrackEffect::Tremor {
                    on_time: h1,
                    off_time: h2,
                },
                TrackEffect::Tremor {
                    on_time: o1,
                    off_time: o2,
                },
            ) => Some(TrackEffect::Tremor {
                on_time: h1 + o1,
                off_time: h2 + o2,
            }),
            (
                TrackEffect::Volume {
                    value: value1,
                    tick: tick1,
                },
                TrackEffect::Volume {
                    value: value2,
                    tick: tick2,
                },
            ) => {
                // Two `Volume` events on one row → cumulative
                // sum, clamped to `[0, 1]`.
                let sum = (*value1 + *value2).clamp(Volume::SILENT, Volume::FULL);
                Some(TrackEffect::Volume {
                    value: sum,
                    tick: tick1 + tick2,
                })
            }
            _ => None,
        }
    }
}