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
//! Audio-side rendering engine.
//!
//! `Voices` owns everything the sequencer does **not**: the per-channel
//! playback state, the global mixer gain, and the sample-generation hot
//! path. It consumes row/tick events (dispatched by the facade after the
//! [`crate::sequencer::Sequencer`] has advanced) and turns them into stereo
//! samples.
//!
//! In the observer model, `Voices` is the built-in row subscriber: the
//! facade always forwards row-start cells and sustained ticks here first,
//! then to any user-registered observers. The separation is purely
//! architectural — there is no `dyn` dispatch involved on the audio path.
//!
//! `Voices` also handles the two volume-side global effects
//! (`SongLevelEffect::Volume`, `SongLevelEffect::VolumeSlide`) — the sequencer
//! leaves those alone because they belong to the mixer, not to navigation.
use crate::channel::Channel;
use crate::midi_observer::MidiEvent;
use crate::triggerkeep::TRIGGER_KEEP_PERIOD;
use crate::voice_pool::VoicePool;
use alloc::{vec, vec::Vec};
use xmrs::core::fixed::fixed::Q15;
use xmrs::core::fixed::units::{Amplification, SampleRate, Volume};
use xmrs::prelude::*;
/// Default voice pool capacity. Mirrors schismtracker's
/// `MAX_VOICES = 256` (`include/player/sndfile.h:40`) — large
/// enough that even modules using NNA = Continue heavily on
/// multiple channels rarely hit the cap.
///
/// Exposed publicly so users can pass it to
/// [`crate::xmrsplayer::XmrsPlayer::new_with_voice_pool_capacity`] when they
/// want the default explicitly, or compare against it before
/// passing a custom value.
pub const DEFAULT_VOICE_POOL_CAPACITY: usize = 256;
/// The audio engine. Built once per player and driven via
/// `process_row` / `process_tick` (crate-private; the facade calls
/// them on each row/tick boundary).
pub struct Voices<'a> {
sample_rate: SampleRate,
/// Module reference, kept so the global-volume / global-volume-
/// slide lane lookups in [`Self::process_row`] can introspect
/// `module.automation` without the facade having to thread it
/// through every call. DAW migration Phase 3c.3.
module: &'a Module,
channel: Vec<Channel<'a>>,
/// Pool of voices, both live and NNA-detached. Channels
/// reference their voices by `VoiceId` — see
/// [`Channel::ghosts`] and [`Channel::live`]. The pool lives at
/// this level (rather than per-channel) so voice stealing
/// happens across the whole population, mirroring schism's
/// `csf_get_nna_channel`.
pool: VoicePool<'a>,
/// Global volume (0.0 ..= 1.0) Q1.15. Mutated by
/// `SongLevelEffect::Volume` and by accumulating
/// `SongLevelEffect::VolumeSlide`. Applied as a final gain in
/// [`Voices::mix`].
global_volume: Volume,
/// Extra amplification applied after `global_volume` —
/// caller-controlled, defaults to unity (`Q4.12 = 0x1000`).
/// Stored as `Amplification` (Q4.12) so it can express up
/// to 8× gain without leaving the i16 raw range.
amplification: Amplification,
/// Non-fine volume-slide speed latched on the last row that carried a
/// `SongLevelEffect::VolumeSlide { fine: false }`. Applied once per tick as
/// long as `row_has_global_volume_slide` stays true.
volume_slide_speed: Q15,
/// Whether the last latched slide was a fine one (fires once at tick 0
/// only). Tracked so we know whether to keep sliding on subsequent
/// ticks of this row.
volume_slide_fine: bool,
/// Cached at row-start: does any cell on the current row carry a global
/// volume slide (fine or not)? Set during `process_row`, read during
/// `process_tick` to decide whether to apply the rolling slide. The
/// fine/non-fine distinction is handled through `volume_slide_fine`.
row_has_global_volume_slide: bool,
/// MIDI events emitted by macros on the current row. Filled by
/// `apply_row_per_channel_effects` and drained by the facade,
/// which dispatches to any registered
/// [`crate::midi_observer::MidiObserver`]. The buffer is re-used
/// across rows — cleared on entry to each `process_row`.
pending_midi_events: Vec<(usize, MidiEvent)>,
/// Humanisation mode for `InstrumentType::Euclidean` pulses.
/// Default [`crate::humanize::HumanizeMode::Disabled`] keeps
/// playback strictly cycle-exact.
humanize_mode: crate::humanize::HumanizeMode,
}
impl<'a> Voices<'a> {
pub(crate) fn new_with_voice_pool_capacity(
module: &'a Module,
sample_rate: u32,
initial_tempo: usize,
voice_pool_capacity: usize,
) -> Self {
let num_channels = module.get_num_channels();
let sr = SampleRate::from_hz(sample_rate.max(1));
let mut channels = vec![Channel::new(module, sr, initial_tempo); num_channels];
// Apply per-channel defaults from the module header.
// Each entry can carry a pan, a volume override, a mute
// flag, and a surround flag — populated by importers whose
// format expresses these in its header (S3M's
// `channel_settings`, IT's `initial_channel_pan` /
// `initial_channel_volume`). XM/MOD leave the vector empty
// and every channel keeps its centre/full/unmuted/non-
// surround default.
for (i, ch) in channels.iter_mut().enumerate() {
if let Some(d) = module.channel_defaults.get(i) {
if let Some(p) = d.panning {
ch.set_initial_panning(p);
}
if let Some(v) = d.volume {
ch.set_initial_channel_volume(v);
}
if d.muted {
ch.set_initial_muted(true);
}
if d.surround {
ch.set_initial_surround(true);
}
}
}
// Deterministic per-channel seed so each channel has an
// independent IT-humanisation stream while the whole render
// stays bit-reproducible. High bits give us a non-zero base;
// low bits distinguish channels.
for (i, ch) in channels.iter_mut().enumerate() {
ch.reseed_rng(0xA5A5_0000 | (i as u32 + 1));
ch.set_track_index(i);
}
Self {
sample_rate: sr,
module,
channel: channels,
pool: VoicePool::new(voice_pool_capacity),
global_volume: Volume::FULL,
amplification: Amplification::UNITY,
volume_slide_speed: Q15::ZERO,
volume_slide_fine: true,
row_has_global_volume_slide: false,
pending_midi_events: Vec::new(),
humanize_mode: crate::humanize::HumanizeMode::default(),
}
}
pub(crate) fn set_humanize_mode(&mut self, mode: crate::humanize::HumanizeMode) {
self.humanize_mode = mode;
// Reseed per-channel humanize RNGs when a deterministic seed
// is requested. Live / Disabled keep the default per-channel
// seeds (deterministic across runs without explicit input).
if let crate::humanize::HumanizeMode::Deterministic(seed) = mode {
for (i, ch) in self.channel.iter_mut().enumerate() {
ch.humanize_ekn.reseed(seed.wrapping_add(i as u32 + 1));
}
}
}
/// Per-channel access for the humanisation scheduler. The
/// facade reads/writes `humanize_ekn` here to schedule fire-
/// early intents and apply the suppress flag.
pub(crate) fn channel_humanize_mut(
&mut self,
idx: usize,
) -> Option<&mut crate::state_humanize_ekn::StateHumanizeEkn> {
self.channel.get_mut(idx).map(|c| &mut c.humanize_ekn)
}
/// Trigger any fire-intent on each channel whose scheduled
/// tick matches `current_tick`. Called per-tick by the player
/// (Euclidean humanisation early-fire path).
///
/// `abs_tick` / `song` are threaded so the channel can resolve
/// its current Clip → Track and run the Phase 3c.1 dual-read
/// lane validation alongside the legacy cell-driven path.
pub(crate) fn fire_humanize_intents_at(&mut self, current_tick: u8, abs_tick: u32, song: u16) {
for ch in &mut self.channel {
if let Some((cell, track_instr)) = ch.humanize_ekn.take_fire_intent_at(current_tick) {
ch.tick0(&cell, track_instr, abs_tick, song, &mut self.pool);
}
}
}
// --- Accessors / mutators (used by the facade to expose public API) ---
/// Q1.15 song-driven master volume.
pub fn global_volume(&self) -> Volume {
self.global_volume
}
/// Set song-driven master volume.
pub fn set_global_volume(&mut self, v: Volume) {
self.global_volume = v;
}
/// Alias kept for the older `_q` naming convention.
#[doc(hidden)]
pub fn global_volume_q(&self) -> Volume {
self.global_volume
}
/// Alias kept for the older `_q` naming convention.
#[doc(hidden)]
#[allow(dead_code)]
pub fn set_global_volume_q(&mut self, v: Volume) {
self.global_volume = v;
}
/// Q4.12 user-driven amplification (up to 8×).
pub fn amplification(&self) -> Amplification {
self.amplification
}
/// Set user-driven amplification.
pub fn set_amplification(&mut self, a: Amplification) {
self.amplification = a;
}
/// Alias kept for the older `_q` naming convention.
#[doc(hidden)]
pub fn amplification_q(&self) -> Amplification {
self.amplification
}
/// Alias kept for the older `_q` naming convention.
#[doc(hidden)]
#[allow(dead_code)]
pub fn set_amplification_q(&mut self, a: Amplification) {
self.amplification = a;
}
/// Output sample-rate in Hz.
pub fn sample_rate(&self) -> SampleRate {
self.sample_rate
}
/// Alias kept for the older `_q` naming convention.
#[doc(hidden)]
#[allow(dead_code)]
pub fn sample_rate_q(&self) -> SampleRate {
self.sample_rate
}
pub fn num_channels(&self) -> usize {
self.channel.len()
}
pub fn set_mute_channel(&mut self, channel_num: usize, mute: bool) {
if channel_num < self.channel.len() {
self.channel[channel_num].muted = mute;
}
}
pub fn mute_all(&mut self, mute: bool) {
for c in &mut self.channel {
c.muted = mute;
}
}
/// Propagate a tempo change to each channel's arpeggio state. Called by
/// the facade whenever the sequencer's tempo has actually changed —
/// gating the N-channel loop on a real delta keeps the common case at a
/// single compare.
pub(crate) fn set_tempo(&mut self, tempo: usize) {
for ch in &mut self.channel {
ch.set_tempo(tempo);
}
}
/// Called by the facade on a `goto` (external seek) so each channel
/// clears what it safely can without touching pitch. Mirrors the
/// previous behaviour of the old `XmrsPlayer::goto` cleanup loop.
pub(crate) fn reset_for_goto(&mut self) {
self.global_volume = Volume::FULL;
// Split borrow: take `&mut self.channel` and `&mut self.pool`
// separately so the loop body can mutate both.
let pool = &mut self.pool;
for ch in &mut self.channel {
ch.clear_ghosts(pool);
ch.trigger_pitch(TRIGGER_KEEP_PERIOD, pool);
}
}
// --- Row / tick dispatch ---
/// Forward the cells of a newly loaded row to each channel, applying the
/// volume-side global effects as we go.
///
/// `abs_tick` is the playback's absolute song tick at row-start; `song`
/// is the current sub-song index. Channels use them to resolve their
/// active Clip + Track (and thence the extracted AutomationLanes) for
/// DAW migration Phase 3c.1's dual-read validation. The audio path
/// remains cell-driven in this phase — lanes are queried only for
/// validation under `cfg(debug_assertions)`.
pub(crate) fn process_row(
&mut self,
cells: &[(Cell, Option<usize>)],
abs_tick: u32,
song: u16,
) {
// Song-level global volume / volume slide come from the
// `GlobalVolume` AutomationLanes (DAW migration Phase 3c.3).
self.apply_global_volume_from_lane(abs_tick);
self.apply_global_volume_slide_from_lane(abs_tick);
// MIDI event buffer is per-row — the facade drains it after
// processing. Clearing here so leftovers from a previous row
// don't re-emit.
self.pending_midi_events.clear();
let n = self.channel.len().min(cells.len());
for (i, (cell, track_instr)) in cells.iter().enumerate().take(n) {
// Euclidean humanisation: if a fire-early already
// triggered this pulse, suppress the natural row-start
// trigger. Global effects on the row still apply.
if !self.channel[i].humanize_ekn.take_suppress() {
self.channel[i].tick0(cell, *track_instr, abs_tick, song, &mut self.pool);
}
self.apply_row_per_channel_effects(i, cell);
}
}
/// Per-channel cell effects that need to fire at row-start.
/// Currently only `TrackEffect::MidiMacro` — the macro byte stream
/// substitutes the channel's note / volume / pan / instrument
/// fields and may write through to the filter envelope or MIDI
/// output. Relocated from `TrackImportUnit::midi_macros` by Phase 3b's
/// mirror pass and consumed cell-side since Phase 3c.3.
fn apply_row_per_channel_effects(&mut self, ch_index: usize, cell: &Cell) {
for fx in &cell.effects {
if let TrackEffect::MidiMacro(macro_type) = fx {
if let Some(ch) = self.channel.get_mut(ch_index) {
ch.apply_midi_macro(
macro_type.clone(),
ch_index,
&mut self.pending_midi_events,
&mut self.pool,
);
}
}
}
}
/// Look up the song-level `GlobalVolume` `Points` lane and apply
/// the latest set whose tick falls *exactly* on `abs_tick`. A
/// `value_at` query would re-apply the latest stored point every
/// row, which would clobber any in-flight volume slide; the
/// strict-equality check matches the legacy "set only on the row
/// that carries the Volume effect" semantic.
fn apply_global_volume_from_lane(&mut self, abs_tick: u32) {
use xmrs::core::daw::automation::{AutomationTarget, AutomationValue, LaneEvent};
for lane in self.module.lanes_for(AutomationTarget::GlobalVolume) {
for ev in lane.events_in(abs_tick, abs_tick.saturating_add(1)) {
if let LaneEvent::Point(p) = ev {
if let AutomationValue::Normalized(q) = p.value {
self.global_volume = Volume::from_q15(q);
}
}
}
}
}
/// Look up the song-level `GlobalVolume` `Slide` lane and latch
/// the per-tick slide rate. Mirrors the sequencer's
/// `latch_bpm_slide_from_lane`: when armed, write `speed` / `fine`
/// and, for fine slides, apply once at tick 0; when unarmed,
/// clear the latch so `process_tick` stops sliding.
fn apply_global_volume_slide_from_lane(&mut self, abs_tick: u32) {
use xmrs::core::daw::automation::AutomationTarget;
let mut armed = false;
for lane in self.module.lanes_for(AutomationTarget::GlobalVolume) {
if let Some(state) = lane.slide_state_at(abs_tick) {
if state.armed {
if state.fine {
// Fine slide fires once at tick 0.
self.global_volume = self.global_volume.with_tremolo(state.rate);
}
self.volume_slide_speed = state.rate;
self.volume_slide_fine = state.fine;
armed = true;
}
}
}
self.row_has_global_volume_slide = armed;
if !armed {
self.volume_slide_speed = Q15::ZERO;
}
}
/// Drain all MIDI events emitted during the most recent row.
/// Returns an iterator yielding `(source_channel, event)` tuples.
/// The facade calls this after `process_row` and forwards each
/// event to every registered [`crate::midi_observer::MidiObserver`].
pub(crate) fn drain_midi_events(&mut self) -> alloc::vec::Drain<'_, (usize, MidiEvent)> {
self.pending_midi_events.drain(..)
}
/// Advance every channel by one sustained (non-row-start) tick.
/// `current_tick` is the sequencer's tick counter at the moment of
/// the call — guaranteed to be >= 1.
pub(crate) fn process_tick(&mut self, current_tick: usize) {
let pool = &mut self.pool;
for ch in &mut self.channel {
ch.tick(current_tick, pool);
}
// Apply rolling global volume slide, if the current row carries a
// non-fine one. Fine slides were already applied at row-start.
if self.row_has_global_volume_slide && !self.volume_slide_fine {
self.global_volume = self.global_volume.with_tremolo(self.volume_slide_speed);
}
}
// --- Sample generation ---
/// Fold each channel's sample into a single stereo output, applying the
/// final mixer gain (`global_volume * amplification`) when requested.
///
/// Hot path: walks channels once with an `i32` Q1.15
/// accumulator and never allocates. Returns the
/// **un-clamped** stereo pre-gain sum so the caller can
/// apply final gain (Volume × Amplification × MixVolume)
/// and clamp to `i16` in a single step without losing
/// headroom that the gain stage would have brought back
/// in range.
///
/// `per_channel_out`, when `Some`, is filled with each
/// channel's saturated `i16` pair (already clamped to the
/// Q1.15 range — observers don't get the un-saturated
/// accumulator; if a single channel ever saturates it's
/// the channel's own gain mistake, not a mix-bus stacking
/// issue).
pub(crate) fn mix(&mut self, per_channel_out: Option<&mut [(i16, i16)]>) -> (i32, i32) {
let mut left: i32 = 0;
let mut right: i32 = 0;
let pool = &mut self.pool;
match per_channel_out {
None => {
for ch in &mut self.channel {
if let Some((l, r)) = ch.next_sample(pool) {
if !ch.is_muted() {
l.accumulate_into(&mut left);
r.accumulate_into(&mut right);
}
}
}
}
Some(buf) => {
for (idx, ch) in self.channel.iter_mut().enumerate() {
let val = match ch.next_sample(pool) {
Some((l, r)) if !ch.is_muted() => {
l.accumulate_into(&mut left);
r.accumulate_into(&mut right);
(l.as_q15_i16(), r.as_q15_i16())
}
_ => (0, 0),
};
if idx < buf.len() {
buf[idx] = val;
}
}
}
}
(left, right)
}
/// Apply `global_volume × amplification` to a pre-gain
/// accumulator and saturate to `i16` Q1.15. Matches the OLD
/// f32 iterator path's gain composition: `mix_volume` is
/// kept in `self` for the rarely-used `voices.mix(true, _)`
/// path but is **NOT** folded in here, because the OLD
/// iterator path didn't apply it either — folding it now
/// would attenuate the output by `module.mix_volume / 8`
/// (≈ 21× quieter / −26 dB on XM modules where
/// `mix_volume = 48/128`).
pub(crate) fn apply_final_gain(&self, sum: (i32, i32)) -> (i16, i16) {
let gv = self.global_volume.as_q15_i32() as i64; // Q1.15
let amp = self.amplification.as_q4_12_i32() as i64; // Q4.12
// Q1.15 × Q4.12 = Q5.27. Apply to sample (i32 Q1.15) →
// Q6.42. Narrow `>> 27` round-half.
let g_q27 = gv.max(0) * amp.max(0); // Q5.27
let bias: i64 = 1 << 26;
let apply = |s: i32| -> i16 {
let prod: i64 = (s as i64).wrapping_mul(g_q27);
let r = if prod >= 0 {
(prod + bias) >> 27
} else {
-(((-prod) + bias) >> 27)
};
r.clamp(i16::MIN as i64, i16::MAX as i64) as i16
};
(apply(sum.0), apply(sum.1))
}
/// Saturate a pre-gain mix accumulator to Q1.15 `i16`
/// without applying gain. Used for the pre-gain observer
/// dispatch.
#[inline]
pub(crate) fn saturate_to_i16(sum: (i32, i32)) -> (i16, i16) {
(
sum.0.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
sum.1.clamp(i16::MIN as i32, i16::MAX as i32) as i16,
)
}
/// Return one `(left, right)` sample per channel, pre-mix,
/// pre-gain. Q1.15 `i16` PCM. Allocates a `Vec`; used by
/// the rarely-hit `XmrsPlayer::samples_from_channels` API
/// for per-channel graphic effects.
pub(crate) fn samples_from_channels(&mut self) -> Vec<(i16, i16)> {
let pool = &mut self.pool;
self.channel
.iter_mut()
.map(|ch| match ch.next_sample(pool) {
Some((l, r)) if !ch.is_muted() => (l.as_q15_i16(), r.as_q15_i16()),
_ => (0, 0),
})
.collect()
}
}