xmrs 0.12.2

A library to edit SoundTracker data with pleasure
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
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
use serde::{Deserialize, Serialize};

use crate::daw::automation::AutomationLane;
use crate::daw::clip::Clip;
use crate::daw::sorted_clips::SortedClips;
use crate::daw::timeline::TimelineMap;
use crate::daw::track::Track;
use crate::fixed::units::{ChannelVolume, Panning, Period, Volume};
use crate::instrument::Instrument;
use crate::mix_plugin::MixPlugins;
use crate::period_helper::FrequencyType;
use crate::prelude::TrackUnit;

use alloc::string::String;
use alloc::string::ToString;
use alloc::{vec, vec::Vec};

/// Which tracker convention this module was imported from.
///
/// This is **metadata only** — it identifies the source format for
/// display, export, and editor UI purposes. Runtime playback
/// decisions are driven entirely by [`PlaybackQuirks`] on [`Module`],
/// which an editor can set independently of the format tag. This
/// lets a new module be authored with any combination of historical
/// quirks (or none at all) without having to lie about the format
/// it "came from".
///
/// Importers set two things: the `format` tag here (as metadata) and
/// the `quirks` struct (as behaviour). An editor creating a fresh
/// module from scratch typically leaves `format = Unknown` and
/// `quirks = PlaybackQuirks::default()` (all-off) for a clean,
/// quirk-free playback.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ModuleFormat {
    /// Unknown / hand-constructed / non-tracker source.
    #[default]
    Unknown,
    /// ProTracker-style MOD (Amiga Soundtracker family).
    Mod,
    /// ScreamTracker III (S3M).
    S3m,
    /// Fasttracker II (XM).
    Xm,
    /// Impulse Tracker (IT), including OpenMPT's IT extensions.
    It,
}

impl ModuleFormat {
    /// `true` when this tag is `Xm`.
    #[inline]
    pub fn is_xm(&self) -> bool {
        matches!(self, ModuleFormat::Xm)
    }

    /// `true` when this tag is `S3m`.
    #[inline]
    pub fn is_s3m(&self) -> bool {
        matches!(self, ModuleFormat::S3m)
    }

    /// `true` when this tag is `It`.
    #[inline]
    pub fn is_it(&self) -> bool {
        matches!(self, ModuleFormat::It)
    }

    /// `true` when this tag is `Mod`.
    #[inline]
    pub fn is_mod(&self) -> bool {
        matches!(self, ModuleFormat::Mod)
    }
}

/// Per-module playback behaviour switches.
///
/// These are the **runtime** knobs the replayer consults to decide
/// how to render a module. Each knob is an orthogonal switch for a
/// single historical tracker behaviour, named for what it *does*
/// rather than which tracker it came from — so an editor can compose
/// any subset of them without pretending the output is a specific
/// historical format.
///
/// The `Default` impl is fully conservative: every quirk is off
/// (`false` / `None`). A module built from scratch by an editor plays
/// cleanly, without inheriting any historical bug or edge case. The
/// importers (XM, S3M, IT, MOD) enable the quirks that are canonical
/// for their source format.
///
/// Every comment below is structured as: *what the knob does* ·
/// *which format(s) enable it by default* · *the upstream reference
/// point*.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Default)]
pub struct PlaybackQuirks {
    // --- Period / pitch ---
    /// Reproduce FT2's signed-overflow quirk in portamento-down:
    /// periods in `[32000, 32767]` snap to `31999`, but periods that
    /// grow past `32768` pass through unchanged (the int16 cast in
    /// FT2's source flips negative, so its own clamp check fails).
    /// Some XM modules rely on this to produce very deep pitch
    /// slides past the audible range. XM on. ft2_replayer.c:1914
    /// (explicit "FT2 bug" marker).
    pub ft2_pitch_slide_overflow: bool,

    /// If `Some((min, max))`, pitch slides clamp the period to this
    /// inclusive range. Models ST3's `amigalimits` masterflag
    /// (`[113.25, 856]` in xmrs Amiga-period units, = ST3's
    /// `[453, 3424]` / 4). Leave `None` for the default
    /// `[1 or 0 .. 31999]` fallback. S3M sets it when masterflag
    /// bit 0x10 is on. dig.c:setmasterflags.
    /// Period clamp `(min, max)` in xmrs Amiga period units,
    /// stored as [`Period`] (Q-typed `u16` raw).
    pub period_clamp: Option<(Period, Period)>,

    /// When a pitch slide tries to make the period go below 1,
    /// allow it to reach 0 ("infinitely high note") instead of
    /// clamping at 1. S3M convention (the minimum period is
    /// effectively silent anyway). FT2/IT clamp at 1.
    pub allow_zero_period: bool,

    // --- Arpeggio ---
    /// Use FT2's historical `arpeggioTab` for arpeggio index
    /// selection — a reverse-tick LUT with hand-crafted holes
    /// that produces FT2's signature odd rhythm at high speeds.
    /// Off = plain `tick % 3` rotation. XM on. ft2_replayer.c
    /// `arpeggioTab` + the reverse `song.tick` semantics.
    pub ft2_arpeggio_lut: bool,

    /// When arpeggio is active, clamp the base note to `≤ 95` in
    /// `adjust_period` to keep the octave-perturbed lookup inside
    /// FT2's 0–95 note range. Paired with `ft2_arpeggio_lut`.
    /// XM on. ft2_replayer.c:arpNote → `period2NotePeriod`.
    pub ft2_arpeggio_note_clamp: bool,

    // --- Envelopes / note triggering ---
    /// A note-off on a channel whose instrument has no volume
    /// envelope CUTS the note (quick anti-click ramp to zero)
    /// instead of FADING via `volume_fadeout`. XM on; IT off (IT
    /// always fades). ft2_replayer.c:`keyOff`. Canonical XM
    /// playback — not a "bug" per se.
    pub keyoff_cuts_without_vol_env: bool,

    /// `K00` (note-off effect with param 0) at tick 0 swallows
    /// the note trigger on the same row — the note column is
    /// ignored and the channel just receives a keyoff. Only
    /// applies to `K00` (param 0); `K0y` with `y > 0` plays the
    /// note normally and the keyoff fires at tick `y`. XM on.
    /// ft2_replayer.c:`getNewNote`, early-return before
    /// `triggerNote`.
    pub k00_eats_note: bool,

    // --- Vibrato ---
    /// A vol-column vibrato-depth slot (FT2 `Bx`) without a
    /// main-effect 4xy on the same row still ticks the vibrato
    /// LFO on every non-zero tick. FT2's `v_Vibrato` calls
    /// `doVibrato` unconditionally after updating the depth.
    /// Without this, modules that drive vibrato primarily from
    /// the vol column leave the LFO frozen at its last position.
    /// XM on.
    pub volcol_b_advances_vibrato: bool,

    // --- Pattern loop ---
    /// An `E60` / `SB0` (set loop start) also leaks its row
    /// number into the song-level break position, so when the
    /// pattern ends naturally the NEXT pattern starts at that
    /// row instead of row 0. FT2 bug that some XM modules rely
    /// on. XM on. ft2_replayer.c:`patternLoop` → `pBreakPos`
    /// side-effect.
    pub e60_leaks_to_next_pattern: bool,

    /// A pattern loop that completes (`SBx` / `E6x` after `x`
    /// iterations) updates its origin to `current_row + 1`, so
    /// a subsequent loop in the same pattern resumes *after*
    /// the previous loop's end instead of re-using the original
    /// origin. S3M on. digcmd.c:s_patloop — `song.patloopstart
    /// = song.np_row + 1` at exit.
    pub pattern_loop_resumes: bool,

    // --- Tremor ---
    /// The tremor effect (I / T) uses a persistent state machine
    /// whose on/off counter carries across rows — consecutive
    /// rows of tremor form a single continuous cycle. Off = FT2
    /// per-row modular formula, which restarts the phase at
    /// every row. S3M on. digcmd.c:`s_tremor` (`atremor` +
    /// `atreon` both live on the channel struct, never reset
    /// at row load).
    pub tremor_state_persists: bool,

    // --- IT "old effects" (flags bit 4) ---
    /// IT modules carry a file-level "Old Effects" bit (ITTECH,
    /// Flags bit 4). When ON, several effects revert to their
    /// ST3-ish behaviour:
    ///   * Hxy/Uxy vibrato depth is doubled.
    ///   * Hxy/Uxy vibrato updates only on non-row ticks (like
    ///     FT2) instead of every tick.
    ///   * Ixy/Tremor `on_time` / `off_time` are effectively `+1`.
    ///   * Oxx past sample end plays from the END of the sample
    ///     instead of being ignored.
    ///
    /// IT importer sets this from the header flag; non-IT formats
    /// leave it `false`. The replayer consults it on every
    /// tick-zero effect-resolution step.
    pub it_old_effects: bool,

    /// IT flag bit 5: link Gxx (tone portamento) memory with Exx/Fxx
    /// (pitch slides) memory. When ON, the three effects share a
    /// single "last slide value" register per channel; also, `Gxx`
    /// when a new note is present retriggers the envelopes.
    /// IT importer sets this from the header.
    pub it_link_gxx_memory: bool,

    /// What to do with the channel's pan when a note retriggers.
    /// Each tracker generation made a different choice; see
    /// [`PanResetPolicy`] for the three options. Set by the
    /// importer to match the source tracker.
    pub pan_reset_policy: PanResetPolicy,

    /// IT 2.14+ in non-old-effects mode advances the vibrato LFO
    /// every tick, including tick 0 of a row. XM/MOD/S3M (and IT
    /// with old-effects on) only tick on non-row ticks. Read in
    /// conjunction with [`Self::it_old_effects`]: when the latter
    /// is on, this flag is meaningless because the IT old-effects
    /// path takes precedence. IT-only — set by `it214()` /
    /// `it215()`; off elsewhere.
    pub it_vibrato_ticks_at_row_zero: bool,

    /// `Sample.volume` (IT's "GvL", Global Volume per sample) stays
    /// a static per-sample gain applied on every mixer tick inside
    /// the voice's `get_volume` chain. For MOD/XM/S3M, `Sample.
    /// volume` is consumed ONCE at note-trigger time as the
    /// channel's initial volume — subsequent V-column / tremolo
    /// updates overwrite it and it must NOT re-scale the voice
    /// downstream. Without this flag the player would apply
    /// `Sample.volume` twice for non-IT formats (once at trigger,
    /// once per tick), squaring it and pulling every reduced-
    /// volume sample down by an extra few dB.
    /// IT on; MOD/XM/S3M off. schism `sndmix.c` keeps GvL in the
    /// running gain chain; ft2_replayer.c / Protracker consume
    /// `vol` at `triggerNote` only.
    pub sample_volume_is_static_gain: bool,

    /// `Fxx` with `xx == 0` is the historical ProTracker / MOD
    /// "stop song" marker — the engine halts playback when it
    /// hits this row. XM reuses the same `Fxx` encoding and
    /// although strict FT2 actually freezes on `F00` (it sets
    /// `song.speed = 0` and the main loop stops advancing),
    /// every modern XM player (OpenMPT, MilkyTracker, XMPlay,
    /// Schism) treats it as end-of-song — matching the
    /// composer's intent when the marker is placed at the end
    /// of the order table. S3M and IT route speed and BPM
    /// through *separate* effects (`Axx` / `Txx`), and
    /// `Axx` with `xx == 0` is documented as "ignored" in both
    /// ScreamTracker 3 and Impulse Tracker — there's no
    /// end-of-song convention to honour there.
    ///
    /// When this quirk is ON, a `GlobalEffect::Speed(0)` on a
    /// row signals end-of-song to the player (the row plays
    /// through its natural tick run, then `SongEnd` fires
    /// before the next row would start) and to the
    /// [`crate::duration`] estimator (the simulator breaks out
    /// of its order-walk loop at the same point).
    ///
    /// MOD on (`pt`), XM on (`ft2`), S3M off (`st3`), IT off
    /// (`it214` / `it215`), modern off (`modern`). The MOD-
    /// format reference is ProTracker's `mt_fxx` (set_speed) —
    /// when `xx == 0`, PT's playback flag is cleared and the
    /// song is considered finished.
    pub speed_zero_ends_song: bool,
}

/// Per-format policy for the channel's pan when a note retriggers.
///
/// The three trackers we model made three different choices:
///
/// - **XM/MOD** (`Always`): the channel pan is reset to the sample's
///   `default_pan` on every retrigger. Pxx slides and pan envelopes
///   are wiped clean each note.
/// - **IT** (`OnInstrumentChange`): the pan resets only when the
///   cell carries an instrument-column change. Pure note retriggers
///   (ghost notes) inherit the channel's current pan, so in-flight
///   Pxx slides and pan envelopes survive.
/// - **S3M** (`Never`): the pan is pure channel state. Note
///   retriggers leave it alone — the channel's pan was set by the
///   header's `channel_settings` byte at song start, and only
///   `Xxx`/`Pxx` effects ever touch it. Schism's
///   `effects.c:249-253` only writes the instrument's pan when the
///   sample/instrument carries an explicit `CHN_PANNING` flag, which
///   in our model corresponds to never resetting from a plain note
///   retrigger.
#[derive(Default, Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
pub enum PanResetPolicy {
    /// Reset on every retrigger. XM/MOD/PT default.
    #[default]
    Always,
    /// Reset only when the cell has an instrument column. IT default.
    OnInstrumentChange,
    /// Never reset on retrigger. S3M default.
    Never,
}

/// Initial state of one channel, applied at song start before any
/// pattern row plays. Used by formats whose header carries
/// per-channel hints — IT (`initial_channel_pan` / `initial_channel
/// _volume`) and S3M (`channel_settings`). All fields default to
/// "no override": `None` for the optional ones, `false` for the
/// flags. The player applies each property only when the
/// corresponding field is set.
#[derive(Default, Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
pub struct ChannelDefault {
    /// Initial pan in `[0, 1]` (left..right) as Q1.15. `None`
    /// keeps the channel at its centre default.
    pub panning: Option<Panning>,

    /// Initial channel volume in `[0, 1]` as Q1.15. `None` keeps
    /// the channel at full volume. Mirrors IT's `Mxx` register
    /// state at song start (header byte
    /// `initial_channel_volume[ch]`, 0..64 normalised here).
    pub volume: Option<ChannelVolume>,

    /// Channel starts muted. S3M's `channel_settings & 0x80` and
    /// IT's `initial_channel_pan & 0x80` both set this. The player
    /// suppresses output for the channel until something un-mutes
    /// it (typically nothing in practice — disabled channels stay
    /// silent for the whole song).
    pub muted: bool,

    /// Channel starts in IT's "surround" mode (S91): the right
    /// output is phase-inverted at mix time, producing a
    /// pseudo-stereo effect on regular speaker pairs. Set when
    /// the IT header's `initial_channel_pan[ch]` byte equals 100
    /// (IT's surround sentinel). Toggled at runtime by S90/S91
    /// effects.
    pub surround: bool,
}

/// Pattern-grid display hint. Editors use these two periods to
/// draw row-highlight separators in the pattern view, so a user
/// can read beats and measures at a glance. Has no effect on
/// playback — purely a UI cue.
///
/// IT carries this in its file header; XM, S3M and MOD do not.
/// Defaulting to `(beat: 4, measure: 16)` means "4/4 time at 16th-
/// note resolution", which matches IT's own startup defaults and
/// what virtually every authored module assumes when the editor
/// presents an empty grid.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
pub struct PatternHighlight {
    /// Number of rows that make up one beat. The editor draws a
    /// subtle highlight at every multiple of this row index. Also
    /// known as "rows per beat" in IT/OpenMPT.
    pub beat: u8,
    /// Number of rows that make up one measure. The editor draws
    /// a stronger highlight at every multiple of this row index,
    /// typically `beat * time_signature_top`. Also known as "rows
    /// per measure" in IT/OpenMPT.
    pub measure: u8,
}

impl Default for PatternHighlight {
    fn default() -> Self {
        Self {
            beat: 4,
            measure: 16,
        }
    }
}

/// SoundTracker Module with Steroid
#[derive(Serialize, Deserialize, Debug)]
pub struct Module {
    pub name: String,
    pub comment: String,
    /// The format this module was authored in, plus the playback
    /// quirks that match its authoring tracker. See
    /// [`crate::compatibility_profile::CompatibilityProfile`] for
    /// the named constructors importers use; editor-authored
    /// modules typically leave this at
    /// [`CompatibilityProfile::modern`](crate::compatibility_profile::CompatibilityProfile::modern) for clean, quirk-free
    /// playback.
    pub profile: crate::compatibility_profile::CompatibilityProfile,
    pub frequency_type: FrequencyType,
    pub default_tempo: usize,
    pub default_bpm: usize,
    pub channel_names: Vec<String>,
    /// Per-channel initial state, applied at song start before any
    /// pattern row plays. Each entry bundles every property a
    /// format's header can pre-set on a channel: panning, channel
    /// volume, mute, surround. Empty means "use defaults for every
    /// channel" (centre pan, full volume, unmuted, no surround).
    ///
    /// Populated by formats whose header carries per-channel hints
    /// — currently S3M (`channel_settings`) and IT (initial channel
    /// pan/volume + surround sentinel). XM/MOD leave it empty:
    /// those formats centre every channel at song start, and any
    /// per-channel state that follows is encoded in the patterns.
    pub channel_defaults: Vec<ChannelDefault>,
    pub instrument: Vec<Instrument>,
    /// Optional MIDI-macro table. Populated by the IT importer when
    /// the source file carries an embedded-macros flag; `None` for
    /// non-IT formats and for IT files without macros. Consumed by
    /// the replayer's MIDI-macro interpreter (per-channel filter
    /// automation, MIDI-out, etc.).
    pub midi_macros: Option<MidiMacros>,
    /// Pattern-grid display hint (rows per beat / rows per measure).
    /// Populated from the IT header; XM/S3M/MOD inherit the
    /// `PatternHighlight::default()` 4/16 cadence.
    pub pattern_highlight: PatternHighlight,
    /// Optional IT-style mix-plugin table (OpenMPT extension).
    /// `None` for non-IT formats and for IT files without an
    /// embedded plugin section.
    pub mix_plugins: Option<MixPlugins>,
    /// MIDI pitch-wheel depth declared by the module author, in
    /// semitones. The IT header carries this byte (ITTECH:94, "PWD:
    /// Pitch wheel depth for MIDI controllers") so downstream MIDI-
    /// out code knows how to scale tracker pitch effects (Gxx/Fxx/
    /// Exx) to MIDI 14-bit pitch-bend values when forwarding notes
    /// played through `InstrMidi` / `InstrOpl` / `InstrSid`
    /// instruments.
    ///
    /// **Not consumed by the core replayer.** xmrsplayer renders
    /// only `InstrumentType::Default` (sampled) instruments
    /// natively; the synth / MIDI-out paths are the responsibility
    /// of code that wraps the player and observes its events. This
    /// field exists so such wrappers can read a single source of
    /// truth instead of carrying their own per-module config.
    ///
    /// Macro-driven pitch bend (`Zxx` / `SFx` macros encoding
    /// `En ll mm` bytes) is unaffected — the macro author writes
    /// the absolute 14-bit value directly, and xmrsplayer's
    /// [`MidiObserver`](https://docs.rs/xmrsplayer) emits it
    /// verbatim. PWD only matters when downstream code is
    /// *generating* pitch bend from a tracker semitone delta.
    ///
    /// IT importer copies the header byte. Other formats default
    /// to **2** semitones — the General MIDI default a receiver
    /// would assume in the absence of an explicit RPN setup.
    /// Range per ITTECH is 0..=15.
    pub pitch_wheel_depth: u8,
    /// Song-level mix volume scalar (0..1). IT-specific: each IT
    /// file carries a "mix volume" register (0..128, default 48)
    /// which is a constant mixer-level headroom applied on top of
    /// the Vxx-animated global volume. It is NOT part of the Vxx
    /// effect chain — authors set it once to reserve dynamic range
    /// for resonant-filter peaks and multi-voice summing.
    ///
    /// Mix master amplifier, Q1.15 in `[0, 1]`. Multiplies the
    /// final mixed audio. Was `f32` — see [`Volume`] for the
    /// conversion convention.
    ///
    /// IT-specific (the IT importer reads it from the file
    /// header). Non-IT formats leave this at [`Volume::FULL`]
    /// (identity). The player reads it once at construction
    /// and applies it as a final constant multiplier separate
    /// from both `global_volume` and user-facing
    /// `amplification`.
    pub mix_volume: Volume,

    // ---- DAW layer ----
    //
    // Filled by importers via
    // [`crate::daw::build_timeline::build_timeline_layer`] and consumed
    // by the player.
    /// Library of reusable tracks (DAW layer).
    #[serde(default)]
    pub tracks: Vec<Track>,

    /// Placement of tracks on the timeline. The
    /// [`crate::daw::sorted_clips::SortedClips`] wrapper keeps the
    /// `(song, target_channel, position_tick)` ascending invariant
    /// — every `(song, target_channel)` lane is a contiguous slice
    /// suitable for binary search.
    #[serde(default)]
    pub clips: SortedClips,

    /// Automation lanes. Empty at import; mutated only through the
    /// [`crate::edit`] API.
    #[serde(default)]
    pub automation: Vec<AutomationLane>,

    /// Linearised playback order: maps each visited `(song,
    /// pattern_idx, row_idx)` to its absolute tick + per-row speed
    /// and BPM. The DAW layer's authoritative bridge between the
    /// navigation coordinates effects refer to (`PositionJump`,
    /// `PatternBreak`) and the tick-aligned [`Clip`] timeline.
    #[serde(default)]
    pub timeline_map: TimelineMap,
}

/// A module's MIDI macro table. IT-specific in practice but the
/// type lives on `Module` so the replayer doesn't need to know
/// which format the macros came from.
///
/// Each macro is a 32-byte sequence of hex values. The byte `b'z'`
/// (0x7A) is a placeholder that the replayer substitutes with the
/// current `Zxx` parameter at interpretation time — that's how IT's
/// typical "F0 F0 00 z" macro (set filter cutoff to `z`) works.
///
/// Tables follow ITTECH layout:
/// * `global`      — 9 entries (global MIDI setup: port init, note
///   on/off mapping, etc.)
/// * `parametric`  — 16 entries, selected per-channel via `SF0..SFF`
///   and invoked by `Zxx` with `xx < 0x80`
/// * `fixed`       — 128 entries, addressed absolutely via `Zxx`
///   with `xx >= 0x80` (index = `xx - 0x80`)
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct MidiMacros {
    pub global: Vec<Vec<u8>>,
    pub parametric: Vec<Vec<u8>>,
    pub fixed: Vec<Vec<u8>>,
}

impl Default for Module {
    fn default() -> Self {
        Module {
            name: "".to_string(),
            comment: "".to_string(),
            profile: crate::compatibility_profile::CompatibilityProfile::default(),
            frequency_type: FrequencyType::LinearFrequencies,
            default_tempo: 6,
            default_bpm: 125,
            channel_names: vec![],
            channel_defaults: vec![],
            instrument: vec![],
            midi_macros: None,
            pattern_highlight: PatternHighlight::default(),
            mix_plugins: None,
            pitch_wheel_depth: 2,
            mix_volume: Volume::FULL,
            tracks: vec![],
            clips: SortedClips::new(),
            automation: vec![],
            timeline_map: TimelineMap::default(),
        }
    }
}

impl Module {
    /// Number of channels visible to the player: the smallest
    /// envelope that holds every clip's `target_channel`. Channels
    /// past the rightmost clip are silent by construction and
    /// don't need to be materialised.
    pub fn get_num_channels(&self) -> usize {
        // Max over every song — the player allocates one set of
        // voices that covers all sub-songs the module carries. The
        // sort groups by song first so we can't read this off the
        // last entry; a full pass is the simplest correct answer.
        self.clips
            .iter()
            .map(|c| c.target_channel as usize + 1)
            .max()
            .unwrap_or(0)
    }

    // ---- Derived accessors over the DAW layer ----
    //
    // Resolve queries about song shape (length, pattern index at
    // an order position, pattern length) from `timeline_map.entries`.
    // O(n) but called at most once per row by the sequencer — well
    // under the cost of the audio mixing loop.

    /// Number of order entries for `song`. Derived from the
    /// timeline_map.
    pub fn song_length(&self, song: usize) -> usize {
        self.timeline_map.order_count(song)
    }

    /// Pattern index referenced at `(song, order_idx)`. Returns `None`
    /// if out of range.
    pub fn order_pattern_idx(&self, song: usize, order_idx: usize) -> Option<usize> {
        self.timeline_map
            .find_order_entry(song, order_idx)
            .map(|e| e.pattern_idx as usize)
    }

    /// Maximum row index + 1 ever played for `pat_idx`, derived from
    /// the timeline_map entries that target this pattern.
    pub fn pattern_row_count(&self, pat_idx: usize) -> usize {
        self.timeline_map.row_count_in_pattern(pat_idx)
    }

    /// First clip whose `[position_tick, end_tick)` collides with
    /// `candidate`'s on its `(song, target_channel)` lane. Indices
    /// listed in `ignore` are skipped (typically the index of a clip
    /// being moved or resized in place).
    ///
    /// Operates on the contiguous lane slice rather than the full
    /// clip vector — `O(log N + lane_size)` instead of `O(N)`.
    pub fn find_overlapping_clip(&self, candidate: &Clip, ignore: &[u32]) -> Option<u32> {
        let range = self
            .clips
            .lane_range(candidate.song, candidate.target_channel);
        let lane_start = range.start;
        let cand_end = candidate.end_tick(self);
        for (offset, existing) in self.clips.as_slice()[range].iter().enumerate() {
            let global_idx = (lane_start + offset) as u32;
            if ignore.contains(&global_idx) {
                continue;
            }
            let existing_end = existing.end_tick(self);
            let disjoint =
                cand_end <= existing.position_tick || existing_end <= candidate.position_tick;
            if !disjoint {
                return Some(global_idx);
            }
        }
        None
    }

    /// Materialise one row of cells for playback, resolved through
    /// the DAW timeline. Returns a fresh `Vec<TrackUnit>` of length
    /// `num_channels`; channels with no active clip get
    /// `TrackUnit::default()`.
    ///
    /// # Per-channel resolution
    ///
    /// For each channel, find the active clip via binary search on
    /// `module.clips` (sorted by `(song, target_channel,
    /// position_tick)`), then map the source row to a track row
    /// via `row_in_track = row_idx - clip.source_start_row`.
    ///
    /// The active clip is the one with the greatest
    /// `position_tick ≤ abs_tick`. Its `[position_tick, end_tick)`
    /// containment is then checked — a clip that just ended at
    /// exactly `abs_tick` is *not* active and must not leak into
    /// the next pattern's first row.
    ///
    /// # Two dispatch paths
    ///
    /// 1. **Standard track** (`Track.instrument` references a
    ///    sample-based / wrapped instrument): the cell at
    ///    `track.rows[row_in_track]` is cloned into the output.
    ///
    /// 2. **Euclidean track** (`Track.instrument` references an
    ///    [`InstrumentType::Euclidean`](crate::instrument::InstrumentType::Euclidean)
    ///    wrapper): the track has been collapsed to a single
    ///    prototype cell at import; the per-row content is
    ///    *generated* from the wrapper's
    ///    `(events, steps, rotation)`. The prototype is emitted on
    ///    Bjorklund pulse positions, `Empty` elsewhere. The
    ///    rhythm's duration is bounded by the clip's
    ///    `[position_tick, end_tick)`, looping every `steps` rows
    ///    if the clip outlives a single cycle.
    ///
    /// # Complexity
    ///
    /// Per-channel cost is `O(log N_clips)` thanks to the
    /// canonical clip sort; the Bresenham Bjorklund recompute on
    /// the Euclidean path is `O(steps)` (≤ 255 in practice).
    pub fn row_at(
        &self,
        song: usize,
        pat_idx: usize,
        row_idx: usize,
    ) -> alloc::vec::Vec<TrackUnit> {
        let num_channels = self.get_num_channels();
        let mut out: alloc::vec::Vec<TrackUnit> =
            (0..num_channels).map(|_| TrackUnit::default()).collect();

        let abs_tick = match self.timeline_map.find_entry(song, pat_idx, row_idx) {
            Some(e) => e.tick,
            None => return out,
        };

        let song_u16 = song as u16;
        let row_u32 = row_idx as u32;
        for (ch_idx, out_cell) in out.iter_mut().enumerate() {
            let Some((_, clip)) = self.clips.active_at(song_u16, ch_idx as u8, abs_tick) else {
                continue;
            };
            // `active_at` returns the clip with the greatest
            // `position_tick ≤ abs_tick` on this lane; it can
            // legitimately have ended already, so the half-open
            // `[position_tick, end_tick)` containment must be
            // checked here. Without it, the cells of the clip that
            // *just ended* leak into the next pattern's first row.
            if abs_tick >= clip.end_tick {
                continue;
            }
            // Source-row-based index: independent of per-row speed,
            // so a `GlobalEffect::Speed` mid-clip can't alias two
            // source rows onto the same track index.
            if row_u32 < clip.source_start_row {
                continue;
            }
            let row_in_track = row_u32 - clip.source_start_row;
            if row_in_track < clip.track_row_offset {
                continue;
            }
            let track = match clip.track_in(self) {
                Some(t) => t,
                None => continue,
            };
            // Euclidean (generative) branch: the Track was collapsed
            // to a single prototype cell at conversion time; per-row
            // playback content is derived from the wrapper's
            // `(events, steps, rotation)`. Emit the prototype on
            // Bjorklund pulse positions, Empty elsewhere.
            if let Some(crate::instrument::InstrumentType::Euclidean(ekn)) =
                self.instrument.get(track.instrument).map(|i| &i.instr_type)
            {
                let steps = ekn.steps.max(1) as u32;
                let pos = (row_in_track) % steps;
                let rot = (ekn.rotation as u32) % steps;
                let bjork_idx = ((pos + steps - rot) % steps) as usize;
                let canonical = crate::daw::euclidean::euclidean_pattern(ekn.events, ekn.steps);
                if canonical.get(bjork_idx).copied().unwrap_or(false) {
                    if let Some(proto) = track.rows.first() {
                        *out_cell = proto.clone();
                    }
                }
                continue;
            }
            if (row_in_track as usize) >= track.rows.len() {
                continue;
            }
            *out_cell = track.rows[row_in_track as usize].clone();
        }
        out
    }

    /// Verify that the DAW layer (`tracks` / `clips` / `automation`
    /// / `timeline_map`) is internally consistent: clips sorted and
    /// non-overlapping per `(song, target_channel)`, automation
    /// values matched against their lane's target, timeline_map
    /// entries monotonic per song, tracks pointing at valid
    /// instruments. Used by importers and tests.
    pub fn verify_layers_consistent(&self) -> Result<(), LayerInconsistency> {
        // 1. clips sorted by (song, target_channel, position_tick).
        // `SortedClips` enforces this invariant internally, so this
        // pass is a sanity belt-and-braces against deserialisation
        // sinks that bypass the type's API.
        for w in self.clips.as_slice().windows(2) {
            let a = (w[0].song, w[0].target_channel, w[0].position_tick);
            let b = (w[1].song, w[1].target_channel, w[1].position_tick);
            if a > b {
                return Err(LayerInconsistency::ClipsUnsorted);
            }
        }

        // 2. clip.track must point inside `tracks`
        for (i, clip) in self.clips.iter().enumerate() {
            if clip.track as usize >= self.tracks.len() {
                return Err(LayerInconsistency::ClipTrackOutOfRange {
                    clip_idx: i,
                    track: clip.track,
                });
            }
        }

        // 3. No overlap on (song, target_channel)
        for i in 0..self.clips.len() {
            let ci = &self.clips[i];
            let end_i = ci.end_tick(self);
            for j in (i + 1)..self.clips.len() {
                let cj = &self.clips[j];
                if cj.song != ci.song || cj.target_channel != ci.target_channel {
                    continue;
                }
                if cj.position_tick >= end_i {
                    // No further overlap possible with i on this
                    // (song, channel) — clips are sorted by
                    // position_tick. break out of inner loop.
                    break;
                }
                return Err(LayerInconsistency::ClipsOverlap {
                    clip_a: i,
                    clip_b: j,
                });
            }
        }

        // 4. tracks: instrument index in range. The
        // `EFFECT_ONLY_INSTRUMENT` sentinel marks a track whose
        // cells modify a voice inherited from a prior pattern; it
        // intentionally points at no real instrument.
        for (i, t) in self.tracks.iter().enumerate() {
            if t.instrument == crate::daw::build_timeline::EFFECT_ONLY_INSTRUMENT {
                // Effect-only track: cells must all have
                // `cell.instrument = None` (they don't trigger any
                // sample).
                for (r, cell) in t.rows.iter().enumerate() {
                    if cell.instrument.is_some() {
                        return Err(LayerInconsistency::TrackInstrumentMismatch {
                            track_idx: i,
                            row: r,
                        });
                    }
                }
                continue;
            }
            if t.instrument >= self.instrument.len() && !self.instrument.is_empty() {
                return Err(LayerInconsistency::TrackInstrumentMismatch {
                    track_idx: i,
                    row: 0,
                });
            }
            // Each non-Empty cell that carries an explicit instrument
            // must match the track's instrument (or have None,
            // inheriting it).
            for (r, cell) in t.rows.iter().enumerate() {
                if let Some(instr) = cell.instrument {
                    if instr != t.instrument {
                        return Err(LayerInconsistency::TrackInstrumentMismatch {
                            track_idx: i,
                            row: r,
                        });
                    }
                }
            }
        }

        // 5. Automation lanes: typed values + sorted points
        for (i, lane) in self.automation.iter().enumerate() {
            let mut last_tick: Option<u32> = None;
            for (j, p) in lane.points.iter().enumerate() {
                if !p.value.is_compatible_with(lane.target) {
                    return Err(LayerInconsistency::AutomationTypeMismatch {
                        lane_idx: i,
                        point_idx: j,
                    });
                }
                if let Some(lt) = last_tick {
                    if p.tick < lt {
                        return Err(LayerInconsistency::AutomationPointsUnsorted { lane_idx: i });
                    }
                }
                last_tick = Some(p.tick);
            }
        }

        // 6. timeline_map: entries are sorted by (song, tick) within
        // each song. They are produced in this order by the builder.
        let mut last_song: u16 = 0;
        let mut last_tick: u32 = 0;
        let mut first = true;
        for (i, e) in self.timeline_map.entries.iter().enumerate() {
            if first || e.song != last_song {
                first = false;
                last_song = e.song;
                last_tick = e.tick;
                continue;
            }
            if e.tick < last_tick {
                return Err(LayerInconsistency::TimelineMapMismatch { entry_idx: i });
            }
            last_tick = e.tick;
        }

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LayerInconsistency {
    ClipsUnsorted,
    ClipTrackOutOfRange { clip_idx: usize, track: u32 },
    ClipsOverlap { clip_a: usize, clip_b: usize },
    TimelineMapMismatch { entry_idx: usize },
    AutomationTypeMismatch { lane_idx: usize, point_idx: usize },
    AutomationPointsUnsorted { lane_idx: usize },
    TrackInstrumentMismatch { track_idx: usize, row: usize },
}