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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
/// Generic Effect enum Helper to parse and record memory data definitively to TrackEffect.
use crate::prelude::*;
use alloc::vec;
use alloc::vec::Vec;
use serde::{Deserialize, Serialize};
// Float math backend (only needed when `std` is disabled).
// Priority: std > libm > micromath.
#[cfg(all(not(feature = "std"), not(feature = "libm"), feature = "micromath"))]
#[allow(unused_imports)]
use micromath::F32Ext;
#[cfg(all(not(feature = "std"), feature = "libm"))]
#[allow(unused_imports)]
use num_traits::float::Float;
/// FT2/ST3 multi-retrig volume modifier table.
///
/// FT2 (`doMultiRetrig`) and ST3 (`s_retrig` via `retrigvoladd`) share
/// the same shape: nibbles 1–5 subtract 1/2/4/8/16, nibbles 9–D add
/// the same, and nibbles 6/7/E/F are multiplicative. The two formats
/// disagree on the nibble-6 constant only — FT2 uses `11/16`, ST3
/// `10/16` — which the caller supplies via `mul6`.
///
/// Additive deltas use `1/64` as the unit (xmrs's normalised volume
/// scale, where 0.0 = silent and 1.0 = full).
fn note_retrig_volume_modifier(nibble: usize, mul6: f32) -> NoteRetrigOperator {
const S: f32 = 1.0 / 64.0;
match nibble {
1 => NoteRetrigOperator::Sum(-S),
2 => NoteRetrigOperator::Sum(-2.0 * S),
3 => NoteRetrigOperator::Sum(-4.0 * S),
4 => NoteRetrigOperator::Sum(-8.0 * S),
5 => NoteRetrigOperator::Sum(-16.0 * S),
6 => NoteRetrigOperator::Mul(mul6),
7 => NoteRetrigOperator::Mul(1.0 / 2.0),
9 => NoteRetrigOperator::Sum(S),
0xA => NoteRetrigOperator::Sum(2.0 * S),
0xB => NoteRetrigOperator::Sum(4.0 * S),
0xC => NoteRetrigOperator::Sum(8.0 * S),
0xD => NoteRetrigOperator::Sum(16.0 * S),
0xE => NoteRetrigOperator::Mul(3.0 / 2.0),
0xF => NoteRetrigOperator::Mul(2.0),
_ => NoteRetrigOperator::None,
}
}
// This step is mandatory to manage the effects memory before TrackEffect...
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
pub enum TrackImportEffect {
/// `(1st halftone, 2nd halftone)`
/// F / XM0=0(0), XM=0(0)
Arpeggio(usize, usize),
/// `value`, set the Channel Volume
/// Channel Volume
ChannelVolume(f32),
/// `value`, slide the Channel Volume
/// Channel Volume
ChannelVolumeSlide0(f32),
ChannelVolumeSlideN(f32),
/// `bool`, round to the nearest halftone when using effects
/// F / XM0=0xE3(E3)
Glissando(bool),
/// `tune`, this effet should be used together with a note.
/// It will cause another fine-tune value to be used
/// F / XM0=0xE5(E5)
InstrumentFineTune(f32),
/// `nna` Change Instrument New Note Action
InstrumentNewNoteAction(NewNoteAction),
/// `position`, change the panning envelope position
/// P / XM0=0x15(L) (if instr.sustained)
InstrumentPanningEnvelopePosition(usize),
InstrumentPanningEnvelope(bool),
InstrumentPitchEnvelope(bool),
/// `offset`, this effect should be used together with a note
/// The sample will be played from `offset` instead of zero
/// XM0=9(9)
InstrumentSampleOffset(usize),
InstrumentSampleOffsetAddHigh(usize),
/// `surround`
InstrumentSurround(bool),
/// `position`, change the volume envelope position
/// V / XM0=0x15(L)
InstrumentVolumeEnvelopePosition(usize),
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.
/// V / XM=0xEC(EC)
NoteCut(usize, bool),
/// `ticks`, this effect will delay the note the selected number of ticks
/// XM0=0xED(ED), XM=0xED(ED)
NoteDelay(usize),
/// `(tick, past)`, fadeout the note at the specified tick
/// if past is true, do it for past note too
NoteFadeOut(usize, bool),
/// `(tick, past)`, this effect will trigger a "Note Off" at the specified tick
/// if past is true, do it for past note too
/// XM0=0x14(K), XM=0x14(K)
NoteOff(usize, bool),
/// `interval`, this effect will retrigs the note with the specified interval
/// V / XM0=0xE9(E9), XM=0xE9(E9)
NoteRetrig(usize),
/// `(interval, volume modifier)`
/// Extended version of the `TrackImportEffectffect::NoteRetrig` effect
/// V / XM0=0x1B(R), XM=0x1B(R)
NoteRetrigExtended(usize, usize),
/// `(interval, volume modifier)` — ST3/S3M flavour of
/// [`Self::NoteRetrigExtended`] (command Qxy). The LUT differs
/// from FT2's on nibble 6 only: FT2 uses `vol * 11/16` (from
/// `doMultiRetrig` in `ft2_replayer.c`), ST3 uses `vol * 10/16 =
/// vol * 5/8` (`retrigvoladd[22] = 10` in `digdata.c`). All other
/// nibbles share identical semantics across the two formats, so
/// keeping a separate variant only for this bucket is wasteful,
/// but variant-level splitting is the simplest way to keep the
/// format-specific constant out of the generic converter.
NoteRetrigExtendedS3m(usize, usize),
/// `(speed, depth)`, set Panbrello
Panbrello(f32, f32),
/// `(waveform, retrig)`, change Panbrello waveform.
/// `retrig` to true to retrig when a new instrument is played.
PanbrelloWaveform(Waveform, bool),
/// `position` [0.0..1.0], sets the panning position for the channel
/// 0.0 is the leftmost position and 1.0 the rightmost
/// P / XM0=8(8), XM0=v0xC(vP)
Panning(f32),
/// `speed`, this effect slide the panning position
/// P / XM0=0x19(P), XM=0x19(P), XM0=v0xD(L), XM0=v0xE(R)
PanningSlide0(f32),
PanningSlideN(f32),
/// `speed`
/// F / XM0=1(1), XM=1(1), XM0=2(2), XM=2(2), XM0=0xE1(E1), XM0=0xE2(E2), XM0=0x21(X1), XM=0x21(X2)
PortamentoUp(f32),
PortamentoDown(f32),
/// `speed`
/// F / XM0=0xE1(E1), XM0=0xE2(E2)
PortamentoFineUp(f32),
PortamentoFineDown(f32),
/// `speed`
/// F / XM0=0x21(X1), XM=0x21(X2)
PortamentoExtraFineUp(f32),
PortamentoExtraFineDown(f32),
/// `speed`, see `ControlChangeEffect::Glissando` to round to the nearest halftone
/// F / XM0=3(3), XM=3(3), XM0=5x?(5), XM=5x?(5), XM0=v0xF(vM), XM=v0xF(vM)
TonePortamento(f32),
TonePortamentoFxVol(f32),
/// `(speed, depth)`, see `ControlChangeEffect::Waveform` to change waveform
/// V / XM0=7(7), XM=7(7)
Tremolo(f32, f32),
/// `(waveform, retrig)`, change Tremolo waveform.
/// `retrig` to true to retrig when a new instrument is played.
/// V / XM0=0xE7(E7)
TremoloWaveform(Waveform, bool),
/// `(On time, Off time)`
/// This weird effect will set the volume to zero during `Off time` number of ticks
/// V / XM0=0x1D(T), XM=0x1D(T)
Tremor(usize, usize),
/// `(speed, depth)`, set Vibrato
/// F / XM0=4(4), XM=4(4), XM0=6x?(6), XM=6x?(6), XM=v0xB(vV)
Vibrato(f32, f32),
/// `(speed, depth)`, set Vibrato
/// IT with memory
VibratoFine(f32, f32),
/// `speed`, set Vibrato speed
/// F / XM0=v0xA(S)
VibratoSpeed(f32),
/// `depth`, set Vibrato depth
/// F / XM0=v0xB(V)
VibratoDepth(f32),
VibratoDepthFxVol(f32),
/// `(waveform, retrig)`, change Vibrato waveform.
/// `retrig` to true to retrig when a new instrument is played.
/// F / XM0=0xE4(E4)
VibratoWaveform(Waveform, bool),
/// `(value, tick)`, sets the current volume at the current tick
/// V / XM0=C(C), XM0=vV1..5(V)
Volume(f32, usize),
/// `(speed, tick)`, slides the current volume up or down
/// V / XM0=5?y(5), XM=5?y(5), XM0=6?y(6), XM=6?y(6), XM=0xA(A), XM0=0xEA(EA), XM0=0xEB(EB), XM=v6(v6), XM=v7(v7), XM0=v8(v8), XM0=v9(v9)
VolumeSlide0(f32),
VolumeSlideN(f32),
}
impl TrackImportEffect {
fn sum_vibrato_depth(effects: &[TrackImportEffect]) -> Option<TrackEffect> {
let s = effects
.iter()
.map(|effect| match effect {
TrackImportEffect::VibratoDepth(depth)
| TrackImportEffect::VibratoDepthFxVol(depth) => *depth,
_ => 0.0, // Ignore other variants
})
.sum();
if s == 0.0 {
None
} else {
Some(TrackEffect::VibratoDepth(s))
}
}
fn sum_vibratos(effects: &[TrackImportEffect]) -> Option<TrackEffect> {
let s = effects
.iter()
.map(|effect| match effect {
TrackImportEffect::Vibrato(speed, depth)
| TrackImportEffect::VibratoFine(speed, depth) => (*speed, *depth),
_ => (0.0, 0.0), // Ignore other variants
})
.fold((0.0, 0.0), |acc, (a, b)| (acc.0 + a, acc.1 + b));
if s.0 == 0.0 && s.1 == 0.0 {
None
} else {
Some(TrackEffect::Vibrato {
speed: s.0,
depth: s.1,
})
}
}
fn sum_tone_portamento(effects: &[TrackImportEffect]) -> Option<TrackEffect> {
let s = effects
.iter()
.map(|effect| match effect {
TrackImportEffect::TonePortamento(speed)
| TrackImportEffect::TonePortamentoFxVol(speed) => *speed,
_ => 0.0, // Ignore other variants
})
.sum();
if s == 0.0 {
None
} else {
Some(TrackEffect::TonePortamento(s))
}
}
/// Sum all *regular* (tick > 0) pitch-slide speeds on the row.
/// Returns `Some(Portamento { fine: false, ... })` if any regular
/// slide is present, else `None`.
fn sum_portamento_speeds_regular(effects: &[TrackImportEffect]) -> Option<TrackEffect> {
let s: f32 = effects
.iter()
.map(|effect| match effect {
TrackImportEffect::PortamentoUp(speed)
| TrackImportEffect::PortamentoDown(speed) => *speed,
_ => 0.0,
})
.sum();
if s == 0.0 {
None
} else {
Some(TrackEffect::Portamento {
speed: s,
fine: false,
})
}
}
/// Sum all *fine* and *extra-fine* (tick 0) pitch-slide speeds on
/// the row. Fine and extra-fine share a tick scope (both fire at
/// tick 0) and the importer has already applied the correct per-
/// variant unit scaling, so their speeds can be summed directly.
/// Returns `Some(Portamento { fine: true, ... })` or `None`.
///
/// Keeping this separate from the regular sum is critical: in FT2
/// a row can carry both a regular 2xx on the main effect column
/// AND a fine E2x or extra-fine X2y on another row-level slot
/// (e.g. via format-specific extensions), and they must fire at
/// their own tick scopes. Before this split, everything collapsed
/// into a single `Portamento` that fired at tick > 0 only, over-
/// applying fine slides by `(speed − 1)×`.
fn sum_portamento_speeds_fine(effects: &[TrackImportEffect]) -> Option<TrackEffect> {
let s: f32 = effects
.iter()
.map(|effect| match effect {
TrackImportEffect::PortamentoFineUp(speed)
| TrackImportEffect::PortamentoFineDown(speed)
| TrackImportEffect::PortamentoExtraFineUp(speed)
| TrackImportEffect::PortamentoExtraFineDown(speed) => *speed,
_ => 0.0,
})
.sum();
if s == 0.0 {
None
} else {
Some(TrackEffect::Portamento {
speed: s,
fine: true,
})
}
}
// all others fx
fn to_track_effect(self) -> Option<TrackEffect> {
match self {
TrackImportEffect::Arpeggio(h1, h2) => {
if h1 != 0 || h2 != 0 {
Some(TrackEffect::Arpeggio {
half1: h1,
half2: h2,
})
} else {
None
}
}
TrackImportEffect::Panning(pos) => Some(TrackEffect::Panning(pos)),
TrackImportEffect::PanningSlide0(speed) => {
Some(TrackEffect::PanningSlide { speed, fine: true })
}
TrackImportEffect::PanningSlideN(speed) => {
Some(TrackEffect::PanningSlide { speed, fine: false })
}
TrackImportEffect::ChannelVolume(pos) => Some(TrackEffect::ChannelVolume(pos)),
TrackImportEffect::ChannelVolumeSlide0(pos) => Some(TrackEffect::ChannelVolumeSlide {
speed: pos,
fine: true,
}),
TrackImportEffect::ChannelVolumeSlideN(pos) => Some(TrackEffect::ChannelVolumeSlide {
speed: pos,
fine: false,
}),
TrackImportEffect::Glissando(value) => Some(TrackEffect::Glissando(value)),
TrackImportEffect::InstrumentFineTune(tune) => {
Some(TrackEffect::InstrumentFineTune(tune))
}
TrackImportEffect::InstrumentNewNoteAction(nna) => {
Some(TrackEffect::InstrumentNewNoteAction(nna))
}
TrackImportEffect::InstrumentPanningEnvelopePosition(pos) => {
Some(TrackEffect::InstrumentPanningEnvelopePosition(pos))
}
TrackImportEffect::InstrumentPanningEnvelope(set) => {
Some(TrackEffect::InstrumentPanningEnvelope(set))
}
TrackImportEffect::InstrumentPitchEnvelope(set) => {
Some(TrackEffect::InstrumentPitchEnvelope(set))
}
TrackImportEffect::InstrumentSampleOffset(offset) => {
Some(TrackEffect::InstrumentSampleOffset(offset))
}
TrackImportEffect::InstrumentSurround(set) => {
Some(TrackEffect::InstrumentSurround(set))
}
TrackImportEffect::InstrumentVolumeEnvelopePosition(pos) => {
Some(TrackEffect::InstrumentVolumeEnvelopePosition(pos))
}
TrackImportEffect::InstrumentVolumeEnvelope(set) => {
Some(TrackEffect::InstrumentVolumeEnvelope(set))
}
TrackImportEffect::NoteCut(tick, past) => Some(TrackEffect::NoteCut { tick, past }),
TrackImportEffect::NoteDelay(ticks) => {
if ticks != 0 {
Some(TrackEffect::NoteDelay(ticks))
} else {
None
}
}
TrackImportEffect::NoteFadeOut(tick, past) => {
Some(TrackEffect::NoteFadeOut { tick, past })
}
TrackImportEffect::NoteOff(tick, past) => Some(TrackEffect::NoteOff { tick, past }),
TrackImportEffect::NoteRetrig(interval) => Some(TrackEffect::NoteRetrig {
speed: interval,
volume_modifier: NoteRetrigOperator::None,
}),
TrackImportEffect::NoteRetrigExtended(interval, vol) => {
// each additive delta is divided by 64. Multiplicative ratios
// are scale-independent.
//
// The nibble-6 and nibble-E ratios mirror FT2's integer
// arithmetic: `vol * 11/16` (= vol>>1 + vol>>3 + vol>>4) and
// `vol * 3/2` (= vol>>1 + vol) respectively — see
// ft2_replayer.c:doMultiNoteRetrig. The common 2/3 and 3/2
// approximations diverge from FT2 by ~3% on nibble 6 which
// is audible over a long Rxy passage; keep 11/16 here.
Some(TrackEffect::NoteRetrig {
speed: interval,
volume_modifier: note_retrig_volume_modifier(vol, 11.0 / 16.0),
})
}
TrackImportEffect::NoteRetrigExtendedS3m(interval, vol) => {
// ST3 Qxy: same LUT as FT2 Rxy except nibble 6, where
// `retrigvoladd[22] = 10` yields `vol * 10/16 = vol *
// 5/8` (`digcmd.c:s_retrig`). All other nibbles match,
// so we share `note_retrig_volume_modifier` with just
// a different nibble-6 constant.
Some(TrackEffect::NoteRetrig {
speed: interval,
volume_modifier: note_retrig_volume_modifier(vol, 10.0 / 16.0),
})
}
TrackImportEffect::Panbrello(speed, depth) => {
Some(TrackEffect::Panbrello { speed, depth })
}
TrackImportEffect::PanbrelloWaveform(waveform, retrig) => {
Some(TrackEffect::PanbrelloWaveform { waveform, retrig })
}
TrackImportEffect::Tremolo(speed, depth) => Some(TrackEffect::Tremolo { speed, depth }),
TrackImportEffect::TremoloWaveform(waveform, retrig) => {
Some(TrackEffect::TremoloWaveform { waveform, retrig })
}
TrackImportEffect::Tremor(on, off) => Some(TrackEffect::Tremor {
on_time: on,
off_time: off,
}),
TrackImportEffect::VibratoSpeed(speed) => Some(TrackEffect::VibratoSpeed(speed)),
TrackImportEffect::VibratoWaveform(waveform, retrig) => {
Some(TrackEffect::VibratoWaveform { waveform, retrig })
}
TrackImportEffect::Volume(value, tick) => Some(TrackEffect::Volume { value, tick }),
TrackImportEffect::VolumeSlide0(value) => Some(TrackEffect::VolumeSlide {
speed: value,
fine: true,
}),
TrackImportEffect::VolumeSlideN(value) => Some(TrackEffect::VolumeSlide {
speed: value,
fine: false,
}),
_ => None,
}
}
/// Collapse effects that can be merged; **preserve** entries that
/// share a discriminant but whose `merge` returns `None`.
///
/// `TrackEffect::merge` returns `None` when two effects of the same
/// Rust variant are semantically distinct — today this happens for
/// `VolumeSlide`, `PanningSlide`, `ChannelVolumeSlide` and
/// `Portamento`, where the `fine` flag partitions the variant into
/// two independent tick scopes (tick 0 vs ticks > 0). Those pairs
/// must coexist on the same row (e.g. XM row with main-effect Axy
/// + vol-column D/U produces both a regular and a fine
/// `VolumeSlide`).
///
/// The previous implementation used `Vec::iter().position()` to
/// find the first same-discriminant entry and discarded the new
/// one when `merge` returned `None`, which dropped the fine
/// variant on the floor. The updated loop walks entries, accepts
/// the first one whose `merge` actually succeeds, and otherwise
/// pushes the new effect as a parallel entry.
fn remove_duplicates_and_merge(mut effects: Vec<TrackEffect>) -> Vec<TrackEffect> {
let mut unique_effects: Vec<TrackEffect> = Vec::new();
for effect in effects.drain(..) {
let merge_target = unique_effects.iter().enumerate().find_map(|(idx, e)| {
if core::mem::discriminant(e) == core::mem::discriminant(&effect) {
e.merge(&effect).map(|m| (idx, m))
} else {
None
}
});
match merge_target {
Some((idx, merged)) => unique_effects[idx] = merged,
None => unique_effects.push(effect),
}
}
unique_effects
}
pub fn to_track_effects(effects: &[TrackImportEffect]) -> Vec<TrackEffect> {
let mut vte: Vec<TrackEffect> = vec![];
// This part is used to aggregate sub-effects which are subject
// to memory management in the different trackers
// Portamento — regular (tick > 0) and fine (tick 0) are summed
// independently and emitted as two separate TrackEffects so the
// replayer can apply each at its own tick scope. A row may
// legitimately carry both (e.g. 2xx + E2x).
if let Some(te) = Self::sum_portamento_speeds_regular(effects) {
vte.push(te);
}
if let Some(te) = Self::sum_portamento_speeds_fine(effects) {
vte.push(te);
}
// TonePortamento
if let Some(te) = Self::sum_tone_portamento(effects) {
vte.push(te);
}
// VibratoDepth
if let Some(te) = Self::sum_vibrato_depth(effects) {
vte.push(te);
}
// Vibrato
if let Some(te) = Self::sum_vibratos(effects) {
vte.push(te);
}
// All others
for fx in effects {
if let Some(te) = Self::to_track_effect(*fx) {
vte.push(te);
}
}
// Remove duplicates
Self::remove_duplicates_and_merge(vte)
}
}