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
use std::fmt::Debug;
use four_cc::FourCC;
use crate::utils::dsp::lfo::LfoWaveform;
use super::processor::{
AhdsrModulationProcessor, KeytrackingModulationProcessor, LfoModulationProcessor,
ModulationProcessor, ModulationProcessorTarget, VelocityModulationProcessor,
MODULATION_PROCESSOR_BLOCK_SIZE,
};
// -------------------------------------------------------------------------------------------------
/// Container for a modulation processor with its target routings.
///
/// Processes modulation in blocks (up to [`MAX_MODULATION_BLOCK_SIZE`]),
/// caching results for efficient per-sample access. Used by [`ModulationMatrix`].
#[derive(Debug, Clone)]
pub struct ModulationMatrixSlot<P: ModulationProcessor> {
/// The modulation processor (LFO, envelope, velocity, keytracking)
pub processor: P,
/// List of parameter targets this source modulates
pub targets: Vec<ModulationProcessorTarget>,
/// Enabled state
pub enabled: bool,
/// Block buffer for processed modulation values (reused across calls)
/// Size matches MAX_BLOCK_SIZE
pub block_buffer: [f32; MODULATION_PROCESSOR_BLOCK_SIZE],
}
impl<S: ModulationProcessor> ModulationMatrixSlot<S> {
/// Create a new modulation slot with the given source.
pub fn new(source: S) -> Self {
/// Maximum expected targets connected to a modulation processor.
const MAX_TARGETS: usize = 4;
Self {
processor: source,
targets: Vec::with_capacity(MAX_TARGETS),
enabled: true,
block_buffer: [0.0; MODULATION_PROCESSOR_BLOCK_SIZE],
}
}
/// Add a modulation target.
pub fn add_target(&mut self, target: ModulationProcessorTarget) {
self.targets.push(target);
}
/// Remove all targets.
#[allow(unused)]
pub fn clear_targets(&mut self) {
self.targets.clear();
}
/// Update target amount for a specific parameter ID.
/// If target doesn't exist and amount is non-zero, adds it.
/// If target exists and amount is zero, removes it.
/// Otherwise updates the amount.
pub fn update_target(&mut self, parameter_id: FourCC, amount: f32, bipolar: bool) {
let threshold = 0.001;
if let Some(target) = self
.targets
.iter_mut()
.find(|t| t.parameter_id == parameter_id)
{
if amount.abs() < threshold {
// Remove target if amount is effectively zero
self.targets.retain(|t| t.parameter_id != parameter_id);
} else {
// Update existing target
target.amount = amount;
target.bipolar = bipolar;
}
} else if amount.abs() >= threshold {
// Add new target if amount is non-zero
self.add_target(ModulationProcessorTarget::new(
parameter_id,
amount,
bipolar,
));
}
}
/// Process modulation block (calls source's process_block) and memorizes its output.
pub fn process(&mut self, block_size: usize) {
assert!(
block_size <= MODULATION_PROCESSOR_BLOCK_SIZE,
"Invalid block size"
);
if self.enabled && self.processor.is_active() {
self.processor.process(&mut self.block_buffer[..block_size]);
} else {
// If disabled or inactive, fill with zeros
self.block_buffer[..block_size].fill(0.0);
}
}
}
// -------------------------------------------------------------------------------------------------
/// Per-voice modulation matrix containing all modulation sources and their routings.
///
/// Created from [`ModulationConfig`](crate::modulation::ModulationConfig). Processes all sources
/// in blocks, providing block or per-sample modulation output for all target parameters.
#[derive(Debug, Clone)]
pub struct ModulationMatrix {
/// LFO slots (typically 2 or 4 LFOs)
pub lfo_slots: Vec<ModulationMatrixSlot<LfoModulationProcessor>>,
/// Envelope slots (typically 1 or 2 AHDSR envelopes)
pub envelope_slots: Vec<ModulationMatrixSlot<AhdsrModulationProcessor>>,
/// Velocity slot (single instance, optional)
pub velocity_slot: Option<ModulationMatrixSlot<VelocityModulationProcessor>>,
/// Keytracking slot (single instance, optional)
pub keytracking_slot: Option<ModulationMatrixSlot<KeytrackingModulationProcessor>>,
/// Current block size: may be less than MAX_MODULATION_BLOCK_SIZE, but never more
current_output_size: usize,
}
#[allow(unused)]
impl ModulationMatrix {
/// Create a new empty modulation matrix.
pub fn new() -> Self {
// Prealloc for typical usage
Self {
lfo_slots: Vec::with_capacity(4),
envelope_slots: Vec::with_capacity(2),
velocity_slot: None,
keytracking_slot: None,
current_output_size: 0,
}
}
/// Add an LFO slot.
pub fn add_lfo_slot(&mut self, slot: ModulationMatrixSlot<LfoModulationProcessor>) {
self.lfo_slots.push(slot);
}
/// Add an envelope slot.
pub fn add_envelope_slot(&mut self, slot: ModulationMatrixSlot<AhdsrModulationProcessor>) {
self.envelope_slots.push(slot);
}
/// Set velocity slot.
pub fn set_velocity_slot(&mut self, slot: ModulationMatrixSlot<VelocityModulationProcessor>) {
self.velocity_slot = Some(slot);
}
/// Set keytracking slot.
pub fn set_keytracking_slot(
&mut self,
slot: ModulationMatrixSlot<KeytrackingModulationProcessor>,
) {
self.keytracking_slot = Some(slot);
}
/// Process all enabled modulation processors for the next chunk of samples.
///
/// # Arguments
/// * `chunk_size` - Number of samples to process (up to MAX_MODULATION_BLOCK_SIZE)
pub fn process(&mut self, chunk_size: usize) {
assert!(
chunk_size <= MODULATION_PROCESSOR_BLOCK_SIZE,
"Chunk must be < MAX_MODULATION_BLOCK_SIZE, but is: {chunk_size}"
);
// Process all enabled slots
for slot in &mut self.lfo_slots {
slot.process(chunk_size);
}
for slot in &mut self.envelope_slots {
slot.process(chunk_size);
}
if let Some(slot) = &mut self.velocity_slot {
slot.process(chunk_size);
}
if let Some(slot) = &mut self.keytracking_slot {
slot.process(chunk_size);
}
// Memorize valid size
self.current_output_size = chunk_size;
}
/// Last processed, valid modulation output value size.
pub fn output_size(&self) -> usize {
self.current_output_size
}
/// Get accumulated preprocessed modulation values for a single parameter.
///
/// Writes the sum of all modulation processors targeting the given parameter to the output buffer.
/// The output buffer must be at least `output_size` long.
pub fn output(&self, parameter_id: FourCC, output: &mut [f32]) {
let block_size = self.current_output_size;
debug_assert!(
output.len() >= block_size,
"Output buffer too small for block size"
);
let apply_unipolar_block =
|output: &mut [f32], input: &[f32], amount: f32, bipolar: bool| {
if bipolar {
// Transform unipolar [0.0, 1.0] to bipolar [-1.0, 1.0] target
for (out, &inp) in output.iter_mut().zip(input) {
let mod_value = (inp - 0.5) * 2.0;
*out += mod_value * amount;
}
} else {
// Use as-is
for (out, &inp) in output.iter_mut().zip(input) {
*out += inp * amount;
}
}
};
let apply_bipolar_block =
|output: &mut [f32], input: &[f32], amount: f32, bipolar: bool| {
if bipolar {
// Use as-is
for (o, &i) in output.iter_mut().zip(input) {
*o += i * amount;
}
} else {
// Transform bipolar [-1.0, 1.0] to unipolar [0.0, 1.0] target
for (o, &i) in output.iter_mut().zip(input) {
let mod_value = (i + 1.0) / 2.0;
*o += mod_value * amount;
}
}
};
// Initialize output with zeros
output[..block_size].fill(0.0);
// Accumulate modulation from all LFO slots
for slot in &self.lfo_slots {
if slot.enabled {
for target in &slot.targets {
if target.parameter_id == parameter_id {
// bipolar LFO to unipolar or bipolar target
apply_bipolar_block(
&mut output[..block_size],
&slot.block_buffer[..block_size],
target.amount,
target.bipolar,
);
}
}
}
}
// Accumulate modulation from all envelope slots
for slot in &self.envelope_slots {
if slot.enabled {
for target in &slot.targets {
if target.parameter_id == parameter_id {
// unipolar envelope to unipolar or bipolar target
apply_unipolar_block(
&mut output[..block_size],
&slot.block_buffer[..block_size],
target.amount,
target.bipolar,
);
}
}
}
}
// Accumulate modulation from velocity slot
if let Some(slot) = &self.velocity_slot {
if slot.enabled {
for target in &slot.targets {
if target.parameter_id == parameter_id {
// unipolar velocity to unipolar or bipolar target
apply_unipolar_block(
&mut output[..block_size],
&slot.block_buffer[..block_size],
target.amount,
target.bipolar,
);
}
}
}
}
// Accumulate modulation from keytracking slot
if let Some(slot) = &self.keytracking_slot {
if slot.enabled {
for target in &slot.targets {
if target.parameter_id == parameter_id {
// unipolar keytracking to unipolar or bipolar target
apply_unipolar_block(
&mut output[..block_size],
&slot.block_buffer[..block_size],
target.amount,
target.bipolar,
);
}
}
}
}
}
/// Get accumulated preprocessed modulation value for a parameter at a specific sample position.
///
/// Returns the sum of all modulation processors targeting the given parameter,
/// weighted by their amounts.
#[inline]
pub fn output_at(&self, parameter_id: FourCC, sample_index: usize) -> f32 {
debug_assert!(
sample_index < self.current_output_size,
"Sample index out of bounds"
);
let mut total = 0.0;
let apply_unipolar = |raw_value: f32, bipolar: bool| -> f32 {
if bipolar {
// Transform unipolar [0.0, 1.0] to bipolar [-1.0, 1.0] target
(raw_value - 0.5) * 2.0
} else {
// Use as-is
raw_value
}
};
let apply_bipolar = |raw_value: f32, bipolar: bool| -> f32 {
if bipolar {
// Use as-is
raw_value
} else {
// Transform bipolar [-1.0, 1.0] to unipolar [0.0, 1.0] target
(raw_value + 1.0) / 2.0
}
};
// Accumulate modulation from all LFO slots
for slot in &self.lfo_slots {
if slot.enabled {
for target in &slot.targets {
if target.parameter_id == parameter_id {
let raw_value = slot.block_buffer[sample_index];
let mod_value = apply_bipolar(raw_value, target.bipolar);
total += mod_value * target.amount;
}
}
}
}
// Accumulate modulation from all envelope slots
for slot in &self.envelope_slots {
if slot.enabled {
for target in &slot.targets {
if target.parameter_id == parameter_id {
let raw_value = slot.block_buffer[sample_index];
let mod_value = apply_unipolar(raw_value, target.bipolar);
total += mod_value * target.amount;
}
}
}
}
// Accumulate modulation from velocity slot
if let Some(slot) = &self.velocity_slot {
if slot.enabled {
for target in &slot.targets {
if target.parameter_id == parameter_id {
let raw_value = slot.block_buffer[sample_index];
let mod_value = apply_unipolar(raw_value, target.bipolar);
total += mod_value * target.amount;
}
}
}
}
// Accumulate modulation from keytracking slot
if let Some(slot) = &self.keytracking_slot {
if slot.enabled {
for target in &slot.targets {
if target.parameter_id == parameter_id {
let raw_value = slot.block_buffer[sample_index];
let mod_value = apply_unipolar(raw_value, target.bipolar);
total += mod_value * target.amount;
}
}
}
}
total
}
/// Reset & (Re)Trigger & all sources.
pub fn note_on(&mut self, note: u8, volume: f32) {
for slot in &mut self.lfo_slots {
slot.processor.reset();
}
for slot in &mut self.envelope_slots {
slot.processor.reset();
slot.processor.note_on(1.0); // 1.0 for full modulation depth
}
if let Some(slot) = &mut self.velocity_slot {
slot.processor.set_velocity(volume);
}
if let Some(slot) = &mut self.keytracking_slot {
slot.processor.set_midi_note(note as f32);
}
}
/// Trigger note-off for all envelope sources.
pub fn note_off(&mut self) {
for slot in &mut self.envelope_slots {
slot.processor.note_off();
}
}
/// Update LFO rate for a specific LFO slot.
pub fn update_lfo_rate(&mut self, lfo_index: usize, rate: f64) {
if let Some(slot) = self.lfo_slots.get_mut(lfo_index) {
slot.processor.set_rate(rate);
}
}
/// Update LFO waveform for a specific LFO slot.
pub fn update_lfo_waveform(&mut self, lfo_index: usize, waveform: LfoWaveform) {
if let Some(slot) = self.lfo_slots.get_mut(lfo_index) {
slot.processor.set_waveform(waveform);
}
}
/// Update LFO target amount for a specific LFO slot and parameter.
pub fn update_lfo_target(
&mut self,
lfo_index: usize,
parameter_id: FourCC,
amount: f32,
bipolar: bool,
) {
if let Some(slot) = self.lfo_slots.get_mut(lfo_index) {
slot.update_target(parameter_id, amount, bipolar);
}
}
/// Update envelope attack time for a specific envelope slot.
pub fn update_envelope_attack(&mut self, env_index: usize, attack: f32) {
if let Some(slot) = self.envelope_slots.get_mut(env_index) {
slot.processor.set_attack(attack);
}
}
/// Update envelope hold time for a specific envelope slot.
pub fn update_envelope_hold(&mut self, env_index: usize, hold: f32) {
if let Some(slot) = self.envelope_slots.get_mut(env_index) {
slot.processor.set_hold(hold);
}
}
/// Update envelope decay time for a specific envelope slot.
pub fn update_envelope_decay(&mut self, env_index: usize, decay: f32) {
if let Some(slot) = self.envelope_slots.get_mut(env_index) {
slot.processor.set_decay(decay);
}
}
/// Update envelope sustain level for a specific envelope slot.
pub fn update_envelope_sustain(&mut self, env_index: usize, sustain: f32) {
if let Some(slot) = self.envelope_slots.get_mut(env_index) {
slot.processor.set_sustain(sustain);
}
}
/// Update envelope release time for a specific envelope slot.
pub fn update_envelope_release(&mut self, env_index: usize, release: f32) {
if let Some(slot) = self.envelope_slots.get_mut(env_index) {
slot.processor.set_release(release);
}
}
/// Update envelope target amount for a specific envelope slot and parameter.
pub fn update_envelope_target(
&mut self,
env_index: usize,
parameter_id: FourCC,
amount: f32,
bipolar: bool,
) {
if let Some(slot) = self.envelope_slots.get_mut(env_index) {
slot.update_target(parameter_id, amount, bipolar);
}
}
/// Update velocity target amount for a specific parameter.
pub fn update_velocity_target(&mut self, parameter_id: FourCC, amount: f32, bipolar: bool) {
if let Some(slot) = &mut self.velocity_slot {
slot.update_target(parameter_id, amount, bipolar);
}
}
/// Update keytracking target amount for a specific parameter.
pub fn update_keytracking_target(&mut self, parameter_id: FourCC, amount: f32, bipolar: bool) {
if let Some(slot) = &mut self.keytracking_slot {
slot.update_target(parameter_id, amount, bipolar);
}
}
}
impl Default for ModulationMatrix {
fn default() -> Self {
Self::new()
}
}