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
//! 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
//! (`GlobalEffect::Volume`, `GlobalEffect::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::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::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
/// [`Voices::process_row`] / [`Voices::process_tick`].
pub struct Voices<'a> {
sample_rate: f32,
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). Mutated by `GlobalEffect::Volume` and by
/// accumulating `GlobalEffect::VolumeSlide`. Applied as a final gain in
/// [`Voices::mix`].
global_volume: f32,
/// Extra amplification applied after `global_volume` — caller-controlled,
/// defaults to 1.0. Raise above 1.0 at your own clipping risk; lower to
/// 0.25 on busy modules (see README).
amplification: f32,
/// Non-fine volume-slide speed latched on the last row that carried a
/// `GlobalEffect::VolumeSlide { fine: false }`. Applied once per tick as
/// long as `row_has_global_volume_slide` stays true.
volume_slide_speed: f32,
/// 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 during
/// `apply_row_global_effects` and drained by the facade, which
/// dispatches to any registered [`MidiObserver`]. The buffer is
/// re-used across rows — cleared on entry to each `process_row`.
pending_midi_events: Vec<(usize, MidiEvent)>,
/// Final-mix scalar applied once per output sample. Folds two
/// things at construction time:
/// - the format's headroom request (read from the IT header
/// `mv` byte, hard-coded to 48/128 for XM/MOD per schism's
/// `fmt/xm.c:885`, read from the master-volume byte for S3M);
/// - the engine's own attenuation (the float-domain equivalent
/// of schism's `MIXING_ATTENUATION = 5` shift), which gives
/// the mix bus enough headroom for stacked NNA voices not
/// to clip.
///
/// See the construction site for the derivation. The value is
/// kept separate from `global_volume` (which Vxx animates each
/// tick) and `amplification` (which the user controls) so the
/// three concerns stay readable.
mix_volume: f32,
}
impl<'a> Voices<'a> {
pub(crate) fn new_with_voice_pool_capacity(
module: &'a Module,
sample_rate: f32,
initial_tempo: usize,
voice_pool_capacity: usize,
) -> Self {
let num_channels = module.get_num_channels();
let mut channels = vec![Channel::new(module, sample_rate, 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);
}
// Engine-side attenuation: schism applies `MIXING_ATTENUATION
// = 5` (`include/player/cmixer.h:8`) as a final >> 5 shift on
// every voice's contribution before summing. That's eight
// bits of headroom the mixer reserves so dozens of voices can
// stack without overflowing the i32 mix bus.
//
// Two of those five bits are already absorbed in our chain:
// schism reads `mixing_volume` then does `<< 2` to widen the
// domain (`sndmix.c:1101`), whereas we read `mix_volume`
// already pre-divided by 128 — that's a `>> 7` on the same
// bus, so the relative shift between the two pipelines is
// `5 - 2 = 3` more bits of attenuation we owe to the voice
// bus.
//
// 3 bits = factor 1/8. Apply it once at load so the mixer's
// hot path stays a plain multiply.
const MIXER_HEADROOM_DIV: f32 = 8.0;
Self {
sample_rate,
channel: channels,
pool: VoicePool::new(voice_pool_capacity),
global_volume: 1.0,
amplification: 1.0,
volume_slide_speed: 0.0,
volume_slide_fine: true,
row_has_global_volume_slide: false,
pending_midi_events: Vec::new(),
// `module.mix_volume` is the format-specific headroom
// (IT reads the header, XM/MOD/S3M align on schism's
// 48/128 default — see the importers in the `xmrs`
// crate). We fold the engine's MIXER_HEADROOM_DIV in
// here so the mix loop only multiplies once.
mix_volume: module.mix_volume.clamp(0.0, 1.0) / MIXER_HEADROOM_DIV,
}
}
// --- Accessors / mutators (used by the facade to expose public API) ---
pub fn global_volume(&self) -> f32 {
self.global_volume
}
pub fn set_global_volume(&mut self, v: f32) {
self.global_volume = v.clamp(0.0, 1.0);
}
pub fn amplification(&self) -> f32 {
self.amplification
}
pub fn set_amplification(&mut self, a: f32) {
self.amplification = a;
}
pub fn sample_rate(&self) -> f32 {
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 = 1.0;
// 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.
///
/// Cell count is expected to match `self.channel.len()` — any extra
/// cells are ignored, any missing cells are skipped (defensive against
/// malformed modules).
pub(crate) fn process_row(&mut self, cells: &[TrackUnit]) {
// First, cache whether this row carries any global volume slide
// (fine or not). Used by `process_tick` to decide whether to keep
// sliding on subsequent ticks.
self.row_has_global_volume_slide = cells.iter().any(|cell| cell.has_global_volume_slide());
// 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 in 0..n {
let cell = &cells[i];
self.channel[i].tick0(cell, &mut self.pool);
self.apply_row_global_effects(i, cell);
}
}
/// Consume the channel-routed entries of `cell.global_effects` for
/// a single channel. Covers:
/// * `Volume` / `VolumeSlide` — mix-level gain control
/// * `MidiMacro` — filter automation (per-channel, despite the
/// `GlobalEffect` typing — see `Channel::apply_midi_macro`)
///
/// The navigation-side arms (`Bpm`, `BpmSlide`, `PatternBreak`,
/// `PatternLoop`, `PatternDelay`) are owned by the sequencer and
/// skipped here.
fn apply_row_global_effects(&mut self, ch_index: usize, cell: &TrackUnit) {
// Iterate by reference. Pre-fix this was `for gfx in
// cell.global_effects.clone()` — a wholesale `Vec<GlobalEffect>`
// clone on every channel of every row, even though the only
// arm that genuinely needs an owned value is `MidiMacro` (it
// moves `macro_type` into `apply_midi_macro`). The other arms
// (`Volume`, `VolumeSlide`, navigation arms) only read scalar
// fields. Cloning is now confined to the MidiMacro path,
// which is rare in practice — most cells have no global
// effects at all.
for gfx in &cell.global_effects {
match gfx {
GlobalEffect::Volume(volume) => {
self.global_volume = volume.clamp(0.0, 1.0);
}
GlobalEffect::VolumeSlide { speed: s, fine: f } => {
if *f {
// Fine slide: apply once at tick 0.
self.global_volume = (self.global_volume + *s).clamp(0.0, 1.0);
}
// Latch the speed so non-fine slides apply on subsequent ticks.
self.volume_slide_speed = *s;
self.volume_slide_fine = *f;
}
GlobalEffect::MidiMacro(macro_type) => {
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,
);
}
}
// Everything else is owned by the sequencer.
_ => {}
}
}
}
/// 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 [`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 + self.volume_slide_speed).clamp(0.0, 1.0);
}
}
// --- 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 a `(f32, f32)` accumulator and
/// never allocates. At 48 kHz stereo this is the function that runs
/// 48 000 times a second.
///
/// When `per_channel_out` is `Some(buffer)`, each channel's post-mute
/// `(left, right)` pair is also written into the buffer at its channel
/// index — used by the facade to feed `ChannelsObserver`s without a
/// second pass over the channel list. The buffer length must be at
/// least `self.channel.len()`; any trailing entries are left untouched.
/// Pass `None` to skip the capture (the common path, when no channels
/// observer is registered).
pub(crate) fn mix(
&mut self,
apply_volume: bool,
per_channel_out: Option<&mut [(f32, f32)]>,
) -> (f32, f32) {
let (mut left, mut right) = (0.0f32, 0.0f32);
// Split the capture path from the plain path so the no-capture case
// keeps its tight loop without a per-iteration `Option` check.
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() {
left += l;
right += r;
}
}
// `None` from a channel (no active instrument) contributes
// zero; muted channels are advanced (so position tracking
// stays correct when they unmute) but their output is
// discarded.
}
}
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() => {
left += l;
right += r;
(l, r)
}
_ => (0.0, 0.0),
};
// Index is bounded by self.channel.len(); the facade
// guarantees the buffer was sized to match.
if idx < buf.len() {
buf[idx] = val;
}
}
}
}
if apply_volume {
// `mix_volume` is an IT-specific constant headroom
// multiplier (see field doc). For non-IT modules it's
// 1.0 so this is free.
//
// Hard clip on the way out: schism, OpenMPT and the
// wider tracker family all do this — saturation in the
// last mix stage with no shaping. If the gain chain is
// properly calibrated the clamp never fires; if it
// does, the audible distortion points us at the
// miscalibration instead of masking it under a soft
// curve.
let g = self.global_volume * self.amplification * self.mix_volume;
((left * g).clamp(-1.0, 1.0), (right * g).clamp(-1.0, 1.0))
} else {
// Capture path for per-channel observers — leave the
// signal untouched so observers see the linear pre-clip
// signal. The final mix still goes through the
// `apply_volume = true` branch and is clamped on its
// way out.
(left, right)
}
}
/// Return one `(left, right)` sample per channel, pre-mix, pre-gain.
/// Allocates a `Vec`; used by the rarely-hit
/// `XmrsPlayer::samples_from_channels` API for per-channel graphic
/// effects. Kept for compatibility with pre-refactor callers.
pub(crate) fn samples_from_channels(&mut self) -> Vec<(f32, f32)> {
let pool = &mut self.pool;
self.channel
.iter_mut()
.map(|ch| match ch.next_sample(pool) {
Some(fval) => {
if ch.is_muted() {
(0.0, 0.0)
} else {
fval
}
}
None => (0.0, 0.0),
})
.collect()
}
}