xmrsplayer 0.14.4

Safe, no_std SoundTracker music player — plays MOD/XM/S3M/IT/DW with cycle-accurate SID and OPL/AdLib FM synthesis.
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
//! AutomationLane queries + LFO arming / advancing + per-tick
//! Slide / Glide application from the DAW timeline.

use xmrs::core::daw::automation::{AutomationTarget, GlideState, LfoState, SlideState};
use xmrs::core::fixed::fixed::Q15;
use xmrs::core::fixed::units::{Period, PitchDelta};
use xmrs::core::waveform::WaveformState;
use xmrs::prelude::Waveform;

use crate::effect_vibrato_tremolo::EffectVibratoTremolo;

use super::Channel;

/// RFC §1B — reconcile a channel's **extra** (stacked) LFO oscillators
/// with the additional lanes a DAW author placed on a parameter. The
/// primary lane is handled by the unchanged arm code in
/// [`Channel::arm_lfos_from_lanes`]; `states` here are the
/// *2nd..Nth* LFO states for the same `(target, kind)` (`.skip(1)`),
/// so for every tracker import it is empty and `extras` stays empty —
/// the fold then reduces to the primary and is bit-identical.
///
/// The Vec is resized to track the stacked-lane count (preserving the
/// phase of surviving oscillators). When `require_arm` is `false`
/// (the Panbrello "row carries no main effect" case) the params are
/// left untouched, mirroring how the primary keeps its last-armed
/// state until a row re-arms it.
fn sync_lfo_extras(
    extras: &mut alloc::vec::Vec<EffectVibratoTremolo>,
    states: &[LfoState],
    double_depth: bool,
    require_arm: bool,
    retrig_on_arm: bool,
) {
    if extras.len() != states.len() {
        extras.resize(
            states.len(),
            EffectVibratoTremolo::new(Waveform::BipolarSine),
        );
    }
    if !require_arm {
        return;
    }
    for (osc, st) in extras.iter_mut().zip(states) {
        if st.armed {
            osc.data.speed = st.speed;
            osc.data.depth = if double_depth {
                st.depth.raw().saturating_mul(2)
            } else {
                st.depth.raw()
            };
            osc.data.waveform = WaveformState::new(st.waveform);
            if retrig_on_arm {
                osc.retrigger_q();
            }
        }
    }
}

impl<'a> Channel<'a> {
    /// Arm the three per-Track LFO state machines (Vibrato,
    /// Tremolo, Panbrello) from their `AutomationLane`s. Called
    /// at every row-start tick (`Channel::tick0`) **before**
    /// `tickn_effects(0, pool)` so the cell-side arms see the
    /// already-armed `effect_*.data`. The cell-side arms no
    /// longer write the LFO params — they only drive the
    /// per-tick `.tick_q()` advance and the format-specific
    /// quirks (FT2 vol-col-B, IT old-effects depth doubling,
    /// IT 2.14 row-zero tick).
    ///
    /// Skipped on `NoteDelay` rows since the cell-side effects
    /// (and the LFO arm) wait for the delay tick.
    pub(super) fn arm_lfos_from_lanes(&mut self, abs_tick: u32, song: u16) {
        let Some(track_idx) = self.lookup_track_idx(abs_tick, song) else {
            return;
        };

        // ---- Vibrato (TrackPitch) ---------------------------------------
        if let Some(state) = self
            .module
            .lanes_for(
                AutomationTarget::TrackPitch(track_idx),
                self.current_song_idx,
            )
            .find_map(|l| l.lfo_state_at(abs_tick))
        {
            if state.armed {
                let depth = if self.module.quirks.it_old_effects {
                    state.depth.raw().saturating_mul(2)
                } else {
                    state.depth.raw()
                };
                self.effect_vibrato.data.speed = state.speed;
                self.effect_vibrato.data.depth = depth;
                self.effect_vibrato.data.waveform = WaveformState::new(state.waveform);
                self.vibrato_retrig_on_new_note = state.retrig;
            }
        }

        // ---- Tremolo (TrackVolume) --------------------------------------
        if let Some(state) = self
            .module
            .lanes_for(
                AutomationTarget::TrackVolume(track_idx),
                self.current_song_idx,
            )
            .find_map(|l| l.lfo_state_at(abs_tick))
        {
            if state.armed {
                self.effect_tremolo.data.speed = state.speed;
                self.effect_tremolo.data.depth = state.depth.raw();
                self.effect_tremolo.data.waveform = WaveformState::new(state.waveform);
                self.tremolo_retrig_on_new_note = state.retrig;
            }
        }

        // ---- Panbrello (TrackPanning) -----------------------------------
        // The "newly armed" gate avoids re-zeroing the phase on
        // every row where the lane stays armed (matches tracker
        // semantics where the cell arm only fires when the row
        // carries the main effect).
        if let Some(state) = self
            .module
            .lanes_for(
                AutomationTarget::TrackPanning(track_idx),
                self.current_song_idx,
            )
            .find_map(|l| l.lfo_state_at(abs_tick))
        {
            let row_has_main =
                self.lane_has_lfo_set_at(AutomationTarget::TrackPanning(track_idx), abs_tick);
            if state.armed && row_has_main {
                self.effect_panbrello.data.speed = state.speed;
                self.effect_panbrello.data.depth = state.depth.raw();
                self.effect_panbrello.data.waveform = WaveformState::new(state.waveform);
                self.effect_panbrello.retrigger_q();
            }
        }

        // ---- RFC §1B: stacked (extra) LFO lanes -------------------------
        // The primary blocks above are the whole story for tracker
        // imports (one LFO lane per (target, kind) → `.skip(1)` is
        // empty). A DAW author stacking a 2nd/3rd LFO on the same
        // parameter fills these; their outputs sum into the primary at
        // the consumer (`*_value_*` helpers below).
        let it_old = self.module.quirks.it_old_effects;
        let vib_extra: alloc::vec::Vec<LfoState> = self
            .module
            .lanes_for(
                AutomationTarget::TrackPitch(track_idx),
                self.current_song_idx,
            )
            .filter_map(|l| l.lfo_state_at(abs_tick))
            .skip(1)
            .collect();
        sync_lfo_extras(
            &mut self.effect_vibrato_extras,
            &vib_extra,
            it_old,
            true,
            false,
        );

        let trem_extra: alloc::vec::Vec<LfoState> = self
            .module
            .lanes_for(
                AutomationTarget::TrackVolume(track_idx),
                self.current_song_idx,
            )
            .filter_map(|l| l.lfo_state_at(abs_tick))
            .skip(1)
            .collect();
        sync_lfo_extras(
            &mut self.effect_tremolo_extras,
            &trem_extra,
            false,
            true,
            false,
        );

        let pan_row_has_main =
            self.lane_has_lfo_set_at(AutomationTarget::TrackPanning(track_idx), abs_tick);
        let pan_extra: alloc::vec::Vec<LfoState> = self
            .module
            .lanes_for(
                AutomationTarget::TrackPanning(track_idx),
                self.current_song_idx,
            )
            .filter_map(|l| l.lfo_state_at(abs_tick))
            .skip(1)
            .collect();
        sync_lfo_extras(
            &mut self.effect_panbrello_extras,
            &pan_extra,
            false,
            pan_row_has_main,
            true,
        );
    }

    /// Active-clip → Track index lookup. Used by
    /// [`Self::arm_lfos_from_lanes`].
    #[inline]
    pub(super) fn lookup_track_idx(&self, abs_tick: u32, song: u16) -> Option<u32> {
        self.module
            .clips
            .active_at(song, self.track_index as u8, abs_tick)
            .map(|(_, c)| c.track)
    }

    /// `lookup_track_idx` resolved at the row's cached
    /// `(abs_tick, song)`. Convenience for the `row_has_*` helpers.
    #[inline]
    fn current_track_idx(&self) -> Option<u32> {
        self.lookup_track_idx(self.current_abs_tick, self.current_song_idx)
    }

    /// RFC §2B — `true` when the active track carries any enabled
    /// modulation lane with [`ModScope::Voice`], i.e. the channel's
    /// per-tick bus must reach every voice (ghosts included), not just
    /// the live one. Always `false` for tracker imports (every lane is
    /// `Track`), so the ghost path stays bit-identical.
    pub(super) fn voice_scope_active(&self) -> bool {
        use xmrs::core::daw::automation::ModScope;
        let Some(t) = self.current_track_idx() else {
            return false;
        };
        [
            AutomationTarget::TrackPitch(t),
            AutomationTarget::TrackVolume(t),
            AutomationTarget::TrackPanning(t),
            AutomationTarget::TrackChannelVolume(t),
        ]
        .iter()
        .any(|tgt| {
            self.module
                .lanes_for(*tgt, self.current_song_idx)
                .any(|l| l.enabled && l.scope == ModScope::Voice)
        })
    }

    /// The active **held pitch offset** (semitones) from any
    /// `LaneKind::Points` lane on the current Track's `TrackPitch`
    /// target, evaluated at the current tick.
    ///
    /// `Points` lanes on `TrackPitch` carry an *absolute, latched*
    /// transpose ([`AutomationValue::Pitch`]) — as opposed to the
    /// relative `Lfo` (vibrato) / `Slide` / `Glide` modulations that
    /// also live on `TrackPitch`. [`AutomationLane::value_at`] holds
    /// the latest point's value forward, so a transpose set mid-song
    /// re-pitches even a sustained note every tick — the behaviour a
    /// per-note instrument pitch-envelope can't give (the curve is on
    /// the channel/Track timeline, not the note). The DW importer uses
    /// this for the replayer's global transpose (which it recomputes
    /// into every channel's base period each frame). Returns `ZERO`
    /// when no such lane/point exists, so it is a measured no-op for
    /// tracker formats (XM/IT/MOD never emit `Pitch` points).
    #[inline]
    pub(super) fn track_pitch_points_delta(&self) -> PitchDelta {
        use xmrs::core::daw::automation::AutomationValue;
        let Some(track_idx) = self.current_track_idx() else {
            return PitchDelta::ZERO;
        };
        // `Points` on `TrackPitch` (the DW per-frame arpeggio) can
        // change *within* a row, so evaluate at the absolute per-frame
        // tick = row start + within-row tick. (`current_abs_tick` alone
        // is the row's start and would freeze the arpeggio to row
        // resolution.) Other `TrackPitch` lanes are row-triggered and
        // unaffected — they don't use this helper.
        let abs_tick = self
            .current_abs_tick
            .saturating_add(self.current_tick_in_row as u32);
        let mut delta = PitchDelta::ZERO;
        for lane in self.module.lanes_for(
            AutomationTarget::TrackPitch(track_idx),
            self.current_song_idx,
        ) {
            if let Some(AutomationValue::Pitch(d)) = lane.value_at(abs_tick) {
                delta = delta + d;
            }
        }
        delta
    }

    /// `true` when an `AutomationLane` of `target` has an
    /// `LfoEvent::Set` whose tick exactly equals `tick`. The
    /// cell-side quirks that asked "does this row carry a main
    /// `Vibrato` / `Tremolo` / `Panbrello`?" delegate here.
    #[inline]
    fn lane_has_lfo_set_at(&self, target: AutomationTarget, tick: u32) -> bool {
        use xmrs::core::daw::automation::{LaneEvent, LfoEvent};
        self.module
            .lanes_for(target, self.current_song_idx)
            .any(|l| {
                l.events_in(tick, tick.saturating_add(1))
                    .iter()
                    .any(|e| matches!(e, LaneEvent::Lfo(LfoEvent::Set { .. })))
            })
    }

    /// `true` when an `AutomationLane` of `target` has an
    /// `LfoEvent::DepthOnly` whose tick exactly equals `tick`.
    /// Stand-in for the legacy "row carries a standalone
    /// `VibratoDepth`" check (FT2 vol-col-B quirk).
    #[inline]
    fn lane_has_lfo_depthonly_at(&self, target: AutomationTarget, tick: u32) -> bool {
        use xmrs::core::daw::automation::{LaneEvent, LfoEvent};
        self.module
            .lanes_for(target, self.current_song_idx)
            .any(|l| {
                l.events_in(tick, tick.saturating_add(1))
                    .iter()
                    .any(|e| matches!(e, LaneEvent::Lfo(LfoEvent::DepthOnly { .. })))
            })
    }

    /// `true` when an `AutomationLane` of `target` has a
    /// `SlideEvent::Set` whose tick exactly equals `tick`. Used
    /// for the FT2 `InstrReset` quirk (`has_volume_slide`-style)
    /// and similar row-carries-a-slide questions.
    #[inline]
    fn lane_has_slide_set_at(&self, target: AutomationTarget, tick: u32) -> bool {
        use xmrs::core::daw::automation::{LaneEvent, SlideEvent};
        self.module
            .lanes_for(target, self.current_song_idx)
            .any(|l| {
                l.events_in(tick, tick.saturating_add(1))
                    .iter()
                    .any(|e| matches!(e, LaneEvent::Slide(SlideEvent::Set { .. })))
            })
    }

    /// `true` when an `AutomationLane` of `target` has a
    /// `GlideEvent::Set` whose tick exactly equals `tick`.
    /// Stand-in for the legacy "row carries TonePortamento" check.
    #[inline]
    fn lane_has_glide_set_at(&self, target: AutomationTarget, tick: u32) -> bool {
        use xmrs::core::daw::automation::{GlideEvent, LaneEvent};
        self.module
            .lanes_for(target, self.current_song_idx)
            .any(|l| {
                l.events_in(tick, tick.saturating_add(1))
                    .iter()
                    .any(|e| matches!(e, LaneEvent::Glide(GlideEvent::Set { .. })))
            })
    }

    /// Convenience: "row carries TonePortamento on the active
    /// Track's `TrackPitch` lane".
    #[inline]
    pub(super) fn row_has_tone_portamento_lane(&self) -> bool {
        self.current_track_idx().is_some_and(|t| {
            self.lane_has_glide_set_at(AutomationTarget::TrackPitch(t), self.current_abs_tick)
        })
    }

    /// Convenience: "row carries a main `Vibrato` on the active
    /// Track's `TrackPitch` lane".
    #[inline]
    pub(super) fn row_has_vibrato_lane(&self) -> bool {
        self.current_track_idx().is_some_and(|t| {
            self.lane_has_lfo_set_at(AutomationTarget::TrackPitch(t), self.current_abs_tick)
        })
    }

    /// Convenience: "row carries a standalone `VibratoDepth` on
    /// the active Track's `TrackPitch` lane" — XM vol-col B quirk.
    #[inline]
    pub(super) fn row_has_vibrato_depth_only_lane(&self) -> bool {
        self.current_track_idx().is_some_and(|t| {
            self.lane_has_lfo_depthonly_at(AutomationTarget::TrackPitch(t), self.current_abs_tick)
        })
    }

    /// Convenience: "row carries a `VolumeSlide` on the active
    /// Track's `TrackVolume` lane".
    #[inline]
    pub(super) fn row_has_volume_slide_lane(&self) -> bool {
        self.current_track_idx().is_some_and(|t| {
            self.lane_has_slide_set_at(AutomationTarget::TrackVolume(t), self.current_abs_tick)
        })
    }

    /// Advance the per-Track LFO state machines (Vibrato /
    /// Tremolo / Panbrello) on every tick where the corresponding
    /// lane is armed.
    ///
    /// Special cases honoured:
    /// * **Vibrato @ tick 0** advances only under the IT 2.14
    ///   `it_vibrato_ticks_at_row_zero` quirk (and only when
    ///   `it_old_effects` is off).
    /// * **FT2 vol-col-B** (`volcol_b_advances_vibrato`): a row
    ///   that carries a standalone `VibratoDepth` (no main
    ///   `Vibrato` Set) keeps the LFO advancing on `tick > 0`.
    pub(super) fn advance_lfos_from_lanes(&mut self, current_tick: usize) {
        let abs_tick = self.current_abs_tick;
        let song = self.current_song_idx;
        let Some(track_idx) = self.lookup_track_idx(abs_tick, song) else {
            return;
        };
        // ---- Vibrato (TrackPitch) ---------------------------------------
        let vib_state = self
            .module
            .lanes_for(
                AutomationTarget::TrackPitch(track_idx),
                self.current_song_idx,
            )
            .find_map(|l| l.lfo_state_at(abs_tick));
        if let Some(state) = vib_state {
            if state.armed {
                let row_has_main =
                    self.lane_has_lfo_set_at(AutomationTarget::TrackPitch(track_idx), abs_tick);
                let row_has_depth_only = self
                    .lane_has_lfo_depthonly_at(AutomationTarget::TrackPitch(track_idx), abs_tick);
                if current_tick == 0 {
                    if self.module.quirks.pitch_vibrato_ticks_continuously {
                        // DW: vibrato advances on every frame of the
                        // held note, including the row-start frame
                        // (1 frame = 1 tick). Without the tick-0 step
                        // the phase would lose one of every `speed`
                        // frames. Independent of `row_has_main`: once
                        // armed the LFO keeps running until stopped.
                        self.tick_vibrato_all();
                    } else if row_has_main
                        && self.module.quirks.it_vibrato_ticks_at_row_zero
                        && !self.module.quirks.it_old_effects
                    {
                        self.tick_vibrato_all();
                    }
                } else if row_has_main
                    || (row_has_depth_only && self.module.quirks.volcol_b_advances_vibrato)
                    || self.module.quirks.pitch_vibrato_ticks_continuously
                {
                    self.tick_vibrato_all();
                }
            }
        }
        // ---- Tremolo (TrackVolume) --------------------------------------
        if current_tick > 0 {
            let trem_state = self
                .module
                .lanes_for(
                    AutomationTarget::TrackVolume(track_idx),
                    self.current_song_idx,
                )
                .find_map(|l| l.lfo_state_at(abs_tick));
            if let Some(state) = trem_state {
                if state.armed
                    && self.lane_has_lfo_set_at(AutomationTarget::TrackVolume(track_idx), abs_tick)
                {
                    self.tick_tremolo_all();
                }
            }
            // ---- Panbrello (TrackPanning) ------------------------------
            let pan_state = self
                .module
                .lanes_for(
                    AutomationTarget::TrackPanning(track_idx),
                    self.current_song_idx,
                )
                .find_map(|l| l.lfo_state_at(abs_tick));
            if let Some(state) = pan_state {
                if state.armed
                    && self.lane_has_lfo_set_at(AutomationTarget::TrackPanning(track_idx), abs_tick)
                {
                    self.tick_panbrello_all();
                }
            }
        }
    }

    pub(super) fn apply_slides_from_lanes(&mut self, current_tick: usize) {
        let abs_tick = self.current_abs_tick;
        let song = self.current_song_idx;
        let Some(track_idx) = self.lookup_track_idx(abs_tick, song) else {
            return;
        };
        let is_tick0 = current_tick == 0;

        // RFC §1B — each slide/glide target folds **all** its lanes:
        // the primary (`find_map`, the single lane every tracker emits,
        // unchanged) plus any stacked lanes a DAW author added
        // (`.skip(1)`, empty for tracker imports → the apply is
        // bit-identical to first-match). The per-lane apply mutates the
        // persistent accumulator (`self.period` / `volume` / …), so
        // applying each lane in turn *is* the sum-of-deltas fold.

        // VolumeSlide on TrackVolume Slide lane.
        let tgt = AutomationTarget::TrackVolume(track_idx);
        if let Some(state) = self
            .module
            .lanes_for(tgt, self.current_song_idx)
            .find_map(|l| l.slide_state_at(abs_tick))
        {
            self.apply_volume_slide_state(state, is_tick0);
        }
        for state in self.collect_slide_extras(tgt, abs_tick) {
            self.apply_volume_slide_state(state, is_tick0);
        }

        // ChannelVolumeSlide on TrackChannelVolume Slide lane.
        let tgt = AutomationTarget::TrackChannelVolume(track_idx);
        if let Some(state) = self
            .module
            .lanes_for(tgt, self.current_song_idx)
            .find_map(|l| l.slide_state_at(abs_tick))
        {
            self.apply_channel_volume_slide_state(state, is_tick0);
        }
        for state in self.collect_slide_extras(tgt, abs_tick) {
            self.apply_channel_volume_slide_state(state, is_tick0);
        }

        // PanningSlide on TrackPanning Slide lane.
        let tgt = AutomationTarget::TrackPanning(track_idx);
        if let Some(state) = self
            .module
            .lanes_for(tgt, self.current_song_idx)
            .find_map(|l| l.slide_state_at(abs_tick))
        {
            self.apply_panning_slide_state(state, is_tick0);
        }
        for state in self.collect_slide_extras(tgt, abs_tick) {
            self.apply_panning_slide_state(state, is_tick0);
        }

        // TonePortamento on TrackPitch Glide lane.
        let tgt = AutomationTarget::TrackPitch(track_idx);
        if let Some(state) = self
            .module
            .lanes_for(tgt, self.current_song_idx)
            .find_map(|l| l.glide_state_at(abs_tick))
        {
            self.apply_tone_portamento_state(state, is_tick0);
        }
        for state in self.collect_glide_extras(tgt, abs_tick) {
            self.apply_tone_portamento_state(state, is_tick0);
        }

        // Portamento on TrackPitch Slide lane.
        if let Some(state) = self
            .module
            .lanes_for(tgt, self.current_song_idx)
            .find_map(|l| l.slide_state_at(abs_tick))
        {
            self.apply_pitch_slide_state(state, is_tick0);
        }
        for state in self.collect_slide_extras(tgt, abs_tick) {
            self.apply_pitch_slide_state(state, is_tick0);
        }
    }

    /// Stacked (2nd..Nth) Slide-lane states for `target` at `abs_tick`
    /// — the primary (`find_map`) is applied separately. Empty for
    /// every tracker import (one Slide lane per target), so it returns
    /// a non-allocating empty `Vec`.
    #[inline]
    fn collect_slide_extras(
        &self,
        target: AutomationTarget,
        abs_tick: u32,
    ) -> alloc::vec::Vec<SlideState> {
        self.module
            .lanes_for(target, self.current_song_idx)
            .filter_map(|l| l.slide_state_at(abs_tick))
            .skip(1)
            .collect()
    }

    /// Stacked (2nd..Nth) Glide-lane states for `target` at `abs_tick`.
    #[inline]
    fn collect_glide_extras(
        &self,
        target: AutomationTarget,
        abs_tick: u32,
    ) -> alloc::vec::Vec<GlideState> {
        self.module
            .lanes_for(target, self.current_song_idx)
            .filter_map(|l| l.glide_state_at(abs_tick))
            .skip(1)
            .collect()
    }

    fn apply_volume_slide_state(&mut self, state: SlideState, is_tick0: bool) {
        if state.armed && state.fine == is_tick0 {
            self.volume = self.volume.with_tremolo(state.rate);
        }
    }

    fn apply_channel_volume_slide_state(&mut self, state: SlideState, is_tick0: bool) {
        if state.armed && state.fine == is_tick0 {
            self.channel_volume = self.channel_volume.shifted_by(state.rate);
        }
    }

    fn apply_panning_slide_state(&mut self, state: SlideState, is_tick0: bool) {
        if state.armed && state.fine == is_tick0 {
            self.panning = self.panning.shifted_by(state.rate);
        }
    }

    /// TonePortamento. At tick 0, recompute the slide goal from
    /// `self.note` (which `tick0_load_pitch` already updated to the
    /// cell's played pitch via `played_pitch_for` + finetune
    /// composition — drum-kit remaps included). At tick > 0, approach
    /// the goal by `state.rate`.
    fn apply_tone_portamento_state(&mut self, state: GlideState, is_tick0: bool) {
        if state.armed {
            if is_tick0 {
                self.effect_tone_portamento_goal = self.period_helper.note_to_period(self.note);
            } else if self.period != self.effect_tone_portamento_goal {
                self.period = self
                    .period
                    .slide_towards(self.effect_tone_portamento_goal, state.rate);
            }
        }
    }

    /// Portamento (pitch slide). Format-specific clamping (FT2
    /// signed-overflow, ST3 `period_clamp`, IT `allow_zero_period`) is
    /// preserved verbatim from the pre-substitution cell-side arm.
    fn apply_pitch_slide_state(&mut self, state: SlideState, is_tick0: bool) {
        // A coarse slide (`fine == false`) normally runs on the
        // `speed-1` non-row ticks. `pitch_slide_ticks_at_row_zero`
        // (DW) extends it to tick 0 too, so the ramp advances on
        // every frame of the held note — see the quirk doc.
        let runs_this_tick = state.fine == is_tick0
            || (is_tick0 && !state.fine && self.module.quirks.pitch_slide_ticks_at_row_zero);
        if state.armed && runs_this_tick {
            let speed_i16 = state.rate.raw();
            let new_period = self.period.saturating_add_signed(speed_i16);
            if self.module.quirks.ft2_pitch_slide_overflow && speed_i16 > 0 {
                // FT2 `pitchSlideDown` signed-overflow quirk
                // (`ft2_replayer.c:1914`): periods in `[32000, 32767]`
                // snap to 31999; periods ≥ 32768 wrap negative under
                // the int16 cast, the clamp silently fails, and the
                // slide freewheels. Some XM modules rely on this.
                let wrapped = new_period.raw() as i16;
                if (32000..=32767).contains(&(wrapped as i32)) {
                    self.period = Period::from_raw(31999);
                } else {
                    self.period = if new_period == Period::ZERO {
                        Period::from_raw(1)
                    } else {
                        new_period
                    };
                }
            } else if let Some((clamp_min, clamp_max)) = self.module.quirks.period_clamp {
                // ST3 `amigalimits` clamp.
                self.period = new_period.clamp(clamp_min, clamp_max);
            } else {
                // Conservative clamp; IT `allow_zero_period` opens the
                // low edge so a pitch slide can reach "infinitely high
                // note" — ST3 convention without amigalimits.
                let min_period = if self.module.quirks.allow_zero_period {
                    Period::ZERO
                } else {
                    Period::from_raw(1)
                };
                self.period = new_period.clamp(min_period, Period::from_raw(31999));
            }
        }
    }

    // ---- RFC §1B summed-output accessors (primary + stacked extras) ----
    // For tracker imports the extras Vecs are empty, so each accessor
    // returns the primary's value verbatim (the `is_empty` fast path),
    // keeping the render bit-identical.

    /// Vibrato output (raw period/semitone delta), summed across the
    /// primary and any stacked LFO lanes, clamped to `i16`.
    #[inline]
    pub(super) fn vibrato_value_raw(&self) -> i16 {
        if self.effect_vibrato_extras.is_empty() {
            return self.effect_vibrato.value_raw();
        }
        let mut v = self.effect_vibrato.value_raw() as i32;
        for e in &self.effect_vibrato_extras {
            v += e.value_raw() as i32;
        }
        v.clamp(i16::MIN as i32, i16::MAX as i32) as i16
    }

    /// Tremolo output (Q1.15 volume delta), summed across the primary
    /// and any stacked LFO lanes.
    #[inline]
    pub(super) fn tremolo_value_q15(&self) -> Q15 {
        if self.effect_tremolo_extras.is_empty() {
            return self.effect_tremolo.value_q15();
        }
        let mut v = self.effect_tremolo.value_q15().raw() as i32;
        for e in &self.effect_tremolo_extras {
            v += e.value_q15().raw() as i32;
        }
        Q15::from_raw(v.clamp(i16::MIN as i32, i16::MAX as i32) as i16)
    }

    /// Panbrello output (Q1.15 panning delta), summed across the
    /// primary and any stacked LFO lanes.
    #[inline]
    pub(super) fn panbrello_value_q15(&self) -> Q15 {
        if self.effect_panbrello_extras.is_empty() {
            return self.effect_panbrello.value_q15();
        }
        let mut v = self.effect_panbrello.value_q15().raw() as i32;
        for e in &self.effect_panbrello_extras {
            v += e.value_q15().raw() as i32;
        }
        Q15::from_raw(v.clamp(i16::MIN as i32, i16::MAX as i32) as i16)
    }

    #[inline]
    pub(super) fn retrigger_vibrato_all(&mut self) {
        self.effect_vibrato.retrigger_q();
        for e in &mut self.effect_vibrato_extras {
            e.retrigger_q();
        }
    }

    #[inline]
    pub(super) fn retrigger_tremolo_all(&mut self) {
        self.effect_tremolo.retrigger_q();
        for e in &mut self.effect_tremolo_extras {
            e.retrigger_q();
        }
    }

    #[inline]
    pub(super) fn tick_vibrato_all(&mut self) {
        self.effect_vibrato.tick_q();
        for e in &mut self.effect_vibrato_extras {
            e.tick_q();
        }
    }

    #[inline]
    pub(super) fn tick_tremolo_all(&mut self) {
        self.effect_tremolo.tick_q();
        for e in &mut self.effect_tremolo_extras {
            e.tick_q();
        }
    }

    #[inline]
    pub(super) fn tick_panbrello_all(&mut self) {
        self.effect_panbrello.tick_q();
        for e in &mut self.effect_panbrello_extras {
            e.tick_q();
        }
    }

    #[inline]
    pub(super) fn vibrato_any_in_progress(&self) -> bool {
        self.effect_vibrato.in_progress()
            || self.effect_vibrato_extras.iter().any(|e| e.in_progress())
    }

    #[inline]
    pub(super) fn vibrato_clear_output_all(&mut self) {
        self.effect_vibrato.clear_output();
        for e in &mut self.effect_vibrato_extras {
            e.clear_output();
        }
    }
}