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
use soundfont::raw::GeneralPalette;
use crate::core::channel_pool::Channel;
use crate::core::font_bank::FontBank;
use crate::core::soundfont::modulator::Mod;
use crate::core::soundfont::{
generator::{gen_scale_nrpn, GeneratorType},
InstrumentZone, PresetZone,
};
use crate::core::voice_pool::{ModulateCtrl, Voice, VoiceAddMode, VoiceDescriptor, VoicePool};
use crate::midi_event::ControlFunction;
use crate::{MidiEvent, OxiError};
use super::Core;
pub(crate) fn handle_event(synth: &mut Core, event: MidiEvent) -> Result<(), OxiError> {
match event.check()? {
MidiEvent::NoteOn { channel, key, vel } => {
self::noteon(
synth.channels.get(channel as usize)?,
&mut synth.voices,
synth.ticks,
synth.settings.min_note_length_ticks,
synth.settings.gain,
key,
vel,
)?;
}
MidiEvent::NoteOff { channel, key } => {
synth.voices.noteoff(
synth.channels.get(channel as usize)?,
synth.settings.min_note_length_ticks,
key,
);
}
MidiEvent::ControlChange {
channel,
ctrl,
value,
} => {
self::cc(
synth.channels.get_mut(channel as usize)?,
&mut synth.voices,
synth.settings.min_note_length_ticks,
synth.settings.drums_channel_active,
ctrl,
value,
);
}
MidiEvent::AllNotesOff { channel } => {
synth.voices.all_notes_off(
synth.channels.get_mut(channel as usize)?,
synth.settings.min_note_length_ticks,
);
}
MidiEvent::AllSoundOff { channel } => {
synth.voices.all_sounds_off(channel as usize);
}
MidiEvent::PitchBend { channel, value } => {
let channel = synth.channels.get_mut(channel as usize)?;
channel.set_pitch_bend(value);
synth
.voices
.modulate_voices(channel, ModulateCtrl::SF(GeneralPalette::PitchWheel));
}
MidiEvent::ProgramChange {
channel,
program_id,
} => {
self::program_change(
synth.channels.get_mut(channel as usize)?,
&synth.font_bank,
program_id,
synth.settings.drums_channel_active,
);
}
MidiEvent::ChannelPressure { channel, value } => {
let channel = synth.channels.get_mut(channel as usize)?;
channel.set_channel_pressure(value);
synth
.voices
.modulate_voices(channel, ModulateCtrl::SF(GeneralPalette::ChannelPressure));
}
MidiEvent::PolyphonicKeyPressure {
channel,
key,
value,
} => {
let channel = synth.channels.get_mut(channel as usize)?;
channel.set_key_pressure(key as usize, value as i8);
synth.voices.key_pressure(channel, key);
}
MidiEvent::SystemReset => {
synth.voices.system_reset();
let preset = synth.font_bank.find_preset(0, 0).map(|p| p.1);
for channel in synth.channels.iter_mut() {
channel.init(preset.clone());
channel.init_ctrl(false);
}
synth.chorus.reset();
synth.reverb.reset();
}
};
Ok(())
}
type MidiControlChange = u32;
const RPN_MSB: MidiControlChange = 101;
const RPN_LSB: MidiControlChange = 100;
const NRPN_MSB: MidiControlChange = 99;
const NRPN_LSB: MidiControlChange = 98;
const DATA_ENTRY_LSB: MidiControlChange = 38;
/// Change the value of a generator. This function allows to control
/// all synthesis parameters in real-time. The changes are additive,
/// i.e. they add up to the existing parameter value. This function is
/// similar to sending an NRPN message to the synthesizer. The
/// function accepts a float as the value of the parameter. The
/// parameter numbers and ranges are described in the SoundFont 2.01
/// specification, paragraph 8.1.3, page 48.
pub(crate) fn set_gen(
channel: &mut Channel,
voices: &mut VoicePool,
param: GeneratorType,
value: f32,
) {
channel.set_gen(param, value);
channel.set_gen_abs(param, 0);
voices.set_gen(channel.id(), param, value);
}
/// Send a noteon message.
fn noteon(
channel: &Channel,
voices: &mut VoicePool,
start_time: usize,
min_note_length_ticks: usize,
gain: f32,
key: u8,
vel: u8,
) -> Result<(), OxiError> {
if vel == 0 {
voices.noteoff(channel, min_note_length_ticks, key);
Ok(())
} else if channel.preset().is_none() {
Err(OxiError::ChannelHasNoPreset)
} else {
voices.release_voice_on_same_note(channel, key, min_note_length_ticks);
voices.noteid_add();
inner_noteon(channel, voices, start_time, gain, key, vel);
Ok(())
}
}
fn inner_noteon(
channel: &Channel,
voices: &mut VoicePool,
start_time: usize,
gain: f32,
key: u8,
vel: u8,
) {
fn preset_zone_inside_range(zone: &PresetZone, key: u8, vel: u8) -> bool {
zone.key_low <= key && zone.key_high >= key && zone.vel_low <= vel && zone.vel_high >= vel
}
fn inst_zone_inside_range(zone: &InstrumentZone, key: u8, vel: u8) -> bool {
zone.key_low <= key && zone.key_high >= key && zone.vel_low <= vel && zone.vel_high >= vel
}
let preset = &channel.preset().unwrap();
// list for 'sorting' preset modulators
let mod_list_new: Vec<Option<&Mod>> = (0..64).map(|_| None).collect();
let mut mod_list: [Option<&Mod>; 64] = mod_list_new.try_into().unwrap();
let mut global_preset_zone = preset.global_zone();
// run thru all the zones of this preset
for preset_zone in preset.zones().iter() {
// check if the note falls into the key and velocity range of this preset
if !preset_zone_inside_range(preset_zone, key, vel) {
continue;
}
let Some(inst) = preset_zone.inst.as_ref() else {
log::error!("Instrument for zone: {:?} is missing", preset_zone.name);
continue;
};
let mut global_inst_zone = &inst.global_zone();
// run thru all the zones of this instrument
for inst_zone in inst.zones().iter() {
let Some(sample) = inst_zone.sample.as_ref() else {
continue;
};
if sample.sample_type().is_rom() {
continue;
}
// check if the note falls into the key and velocity range of this instrument
if !inst_zone_inside_range(inst_zone, key, vel) {
continue;
}
// this is a good zone. allocate a new synthesis process and initialize it
// Initialize Voice
let init = |voice: &mut Voice| {
voice.add_default_mods();
// Instrument level, generators
for gen in GeneratorType::iter() {
// SF 2.01 section 9.4 'bullet' 4:
//
// A generator in a local instrument zone supersedes a
// global instrument zone generator. Both cases supersede
// the default generator -> voice_gen_set
if inst_zone.gen[gen].flags != 0 {
voice.gen_set(gen, inst_zone.gen[gen].val);
} else if let Some(global_inst_zone) = &global_inst_zone {
if global_inst_zone.gen[gen].flags as i32 != 0 {
voice.gen_set(gen, global_inst_zone.gen[gen].val);
}
} else {
// The generator has not been defined in this instrument.
// Do nothing, leave it at the default.
}
}
// global instrument zone, modulators: Put them all into a
// list.
let mut mod_list_count = 0;
if let Some(global_inst_zone) = &mut global_inst_zone {
for m in global_inst_zone.mods.iter() {
mod_list[mod_list_count] = Some(m);
mod_list_count += 1;
}
}
// local instrument zone, modulators.
// Replace modulators with the same definition in the list:
// SF 2.01 page 69, 'bullet' 8
for m in inst_zone.mods.iter() {
// 'Identical' modulators will be deleted by setting their
// list entry to None. The list length is known, None
// entries will be ignored later. SF2.01 section 9.5.1
// page 69, 'bullet' 3 defines 'identical'.
mod_list
.iter_mut()
.take(mod_list_count)
.filter(|modulator| {
modulator
.as_ref()
.map(|modulator| m.test_identity(modulator))
.unwrap_or(false)
})
.for_each(|modulator| {
*modulator = None;
});
// Finally add the new modulator to to the list.
mod_list[mod_list_count] = Some(m);
mod_list_count += 1;
}
// Add instrument modulators (global / local) to the voice.
mod_list
.iter()
.take(mod_list_count)
.flatten()
.for_each(|modulator| {
// disabled modulators CANNOT be skipped.
// Instrument modulators -supersede- existing (default)
// modulators. SF 2.01 page 69, 'bullet' 6
voice.add_mod(modulator, VoiceAddMode::Overwrite);
});
// Preset level, generators
for gen in GeneratorType::iter() {
// SF 2.01 section 8.5 page 58: If some generators are
// encountered at preset level, they should be ignored
if matches!(
gen,
GeneratorType::StartAddrOfs
| GeneratorType::EndAddrOfs
| GeneratorType::StartLoopAddrOfs
| GeneratorType::EndLoopAddrOfs
| GeneratorType::StartAddrCoarseOfs
| GeneratorType::EndAddrCoarseOfs
| GeneratorType::StartLoopAddrCoarseOfs
| GeneratorType::KeyNum
| GeneratorType::Velocity
| GeneratorType::EndLoopAddrCoarseOfs
| GeneratorType::SampleMode
| GeneratorType::ExclusiveClass
| GeneratorType::OverrideRootKey
) {
continue;
}
// SF 2.01 section 9.4 'bullet' 9: A generator in a
// local preset zone supersedes a global preset zone
// generator. The effect is -added- to the destination
// summing node -> voice_gen_incr
if preset_zone.gen[gen].flags != 0 {
voice.gen_incr(gen, preset_zone.gen[gen].val);
} else if let Some(global_preset_zone) = &global_preset_zone {
if global_preset_zone.gen[gen].flags != 0 {
voice.gen_incr(gen, global_preset_zone.gen[gen].val);
}
} else {
// The generator has not been defined in this preset
// Do nothing, leave it unchanged.
}
}
// Global preset zone, modulators: put them all into a list.
let mut mod_list_count = 0;
if let Some(global_preset_zone) = &mut global_preset_zone {
for m in global_preset_zone.mods.iter() {
mod_list[mod_list_count] = Some(m);
mod_list_count += 1;
}
}
// Process the modulators of the local preset zone. Kick
// out all identical modulators from the global preset zone
// (SF 2.01 page 69, second-last bullet)
for m in preset_zone.mods.iter() {
mod_list
.iter_mut()
.take(mod_list_count)
.filter(|modulator| {
modulator
.as_ref()
.map(|modulator| m.test_identity(modulator))
.unwrap_or(false)
})
.for_each(|modulator| {
*modulator = None;
});
// Finally add the new modulator to the list.
mod_list[mod_list_count] = Some(m);
mod_list_count += 1;
}
// Add preset modulators (global / local) to the voice.
mod_list
.iter()
.take(mod_list_count)
.flatten()
// disabled modulators can be skipped.
.filter(|m| m.amount != 0.0)
.for_each(|m| {
// Preset modulators -add- to existing instrument
// default modulators. SF2.01 page 70 first bullet on
// page
voice.add_mod(m, VoiceAddMode::Add);
});
// Store the ID of the first voice that was created by this noteon event.
// Exclusive class may only terminate older voices.
// That avoids killing voices, which have just been created.
// (a noteon event can create several voice processes with the same exclusive
// class - for example when using stereo samples)
};
let desc = VoiceDescriptor {
sample: sample.clone(),
channel,
key,
vel,
start_time,
gain,
};
let voice_id = voices.request_new_voice(desc, init);
if voice_id.is_ok() {
log::trace!(
"noteon\t{}\t{}\t{}\t\t{}",
channel.id(),
key,
vel,
start_time as f32 / 44100.0,
);
} else {
log::warn!(
"Failed to allocate a synthesis process. (chan={},key={})",
channel.id(),
key
);
}
}
}
}
/// Send a control change message.
fn cc(
channel: &mut Channel,
voices: &mut VoicePool,
min_note_length_ticks: usize,
drums_channel_active: bool,
num: u8,
value: u8,
) {
let Some(num) = ControlFunction::const_try_from(num) else {
return;
};
*channel.cc_mut(num as usize) = value;
use ControlFunction::*;
match num {
// Sustain
DamperPedal => {
if value < 64 {
// sustain off
voices.damp_voices(channel, min_note_length_ticks)
} else {
// sustain on
}
}
BankSelect => {
if channel.id() == 9 && drums_channel_active {
// ignored
return;
}
channel.set_bank_msb(value & 0x7f);
// I fixed the handling of a MIDI bank select controller 0,
// e.g., bank select MSB (or "coarse" bank select according to
// my spec). Prior to this fix a channel's bank number was only
// changed upon reception of MIDI bank select controller 32,
// e.g, bank select LSB (or "fine" bank-select according to my
// spec). [KLE]
// FIXME: is this correct? [PH]
channel.set_banknum((value & 0x7f) as u32);
}
BankSelectLsb => {
if channel.id() == 9 && drums_channel_active {
// ignored
return;
}
// FIXME: according to the Downloadable Sounds II specification,
// bit 31 should be set when we receive the message on channel
// 10 (drum channel)
channel
.set_banknum((value as u32 & 0x7f).wrapping_add((channel.bank_msb() as u32) << 7));
}
AllNotesOff => {
voices.all_notes_off(channel, min_note_length_ticks);
}
AllSoundOff => {
voices.all_notes_off(channel, min_note_length_ticks);
}
ResetAllControllers => {
channel.init_ctrl(true);
voices.modulate_voices_all(channel);
}
DataEntryMsb => {
let data: i32 = ((value as i32) << 7) + channel.cc(DATA_ENTRY_LSB as usize) as i32;
if channel.nrpn_active() != 0 {
let (nrpn_select, nrpn_msb, nrpn_lsb) = (
channel.nrpn_select(),
channel.cc(NRPN_MSB as usize),
channel.cc(NRPN_LSB as usize),
);
// SontFont 2.01 NRPN Message (Sect. 9.6, p. 74)
if nrpn_msb == 120 && nrpn_lsb < 100 {
if (nrpn_select as i32) < GeneratorType::last() as i32 {
let scale_nrpn: f32 = gen_scale_nrpn(nrpn_select, data);
let param = GeneratorType::try_from(nrpn_select as u8).unwrap();
set_gen(channel, voices, param, scale_nrpn)
}
channel.set_nrpn_select(0); // Reset to 0
}
}
// RPN is active: MSB = 0?
else if channel.cc(RPN_MSB as usize) == 0 {
match channel.cc(RPN_LSB as usize) {
// RPN_PITCH_BEND_RANGE
0 => pitch_wheel_sens(channel, voices, value),
// RPN_CHANNEL_FINE_TUNE
1 => {
// Fine tune is 14 bit over +/-1 semitone (+/- 100 cents, 8192 = center)
set_gen(
channel,
voices,
GeneratorType::FineTune,
((data - 8192) as f64 / 8192.0f64 * 100.0f64) as f32,
);
}
// RPN_CHANNEL_COARSE_TUNE
2 => {
// Coarse tune is 7 bit and in semitones (64 is center)
set_gen(
channel,
voices,
GeneratorType::CoarseTune,
(value - 64) as f32,
);
}
// TODO: This is fishy, for some reason those are missing from FluidLite, but
// are present in Fluidsynth
// https://github.com/FluidSynth/fluidsynth/blob/fa5173cbaefed60121db057bad7be7686165f7cc/src/synth/fluid_synth.c#L1857
// RPN_TUNING_PROGRAM_CHANGE | RPN_TUNING_BANK_SELECT | RPN_MODULATION_DEPTH_RANGE
// 3 | 4 | 5 => {}
_ => {}
}
}
}
NonRegisteredParameterNumberMsb => {
*channel.cc_mut(NRPN_LSB as usize) = 0;
channel.set_nrpn_select(0);
channel.set_nrpn_active(1);
}
NonRegisteredParameterNumberLsb => {
// SontFont 2.01 NRPN Message (Sect. 9.6, p. 74)
if channel.cc(NRPN_MSB as usize) == 120 {
if value == 100 {
channel.set_nrpn_select(channel.nrpn_select() + 100);
} else if value == 101 {
channel.set_nrpn_select(channel.nrpn_select() + 1000);
} else if value == 102 {
channel.set_nrpn_select(channel.nrpn_select() + 10000);
} else if value < 100 {
channel.set_nrpn_select(channel.nrpn_select() + value as i16);
}
}
channel.set_nrpn_active(1);
}
RegisteredParameterNumberMsb | RegisteredParameterNumberLsb => channel.set_nrpn_active(0),
_ => voices.modulate_voices(channel, ModulateCtrl::CC(num)),
}
}
/// Set the pitch wheel sensitivity.
pub(crate) fn pitch_wheel_sens(channel: &mut Channel, voices: &mut VoicePool, val: u8) {
channel.set_pitch_wheel_sensitivity(val);
voices.modulate_voices(
channel,
ModulateCtrl::SF(GeneralPalette::PitchWheelSensitivity),
);
}
/// Send a program change message.
pub(crate) fn program_change(
channel: &mut Channel,
font_bank: &FontBank,
program_id: u8,
drums_channel_active: bool,
) {
let banknum = channel.banknum();
channel.set_prognum(program_id);
let mut preset = if channel.id() == 9 && drums_channel_active {
font_bank.find_preset(128, program_id)
} else {
font_bank.find_preset(banknum, program_id)
};
if preset.is_none() {
let mut subst_bank = banknum as i32;
let mut subst_prog = program_id;
if banknum != 128 {
subst_bank = 0;
preset = font_bank.find_preset(0, program_id);
if preset.is_none() && program_id != 0 {
preset = font_bank.find_preset(0, 0);
subst_prog = 0;
}
} else {
preset = font_bank.find_preset(128, 0);
subst_prog = 0;
}
if preset.is_none() {
log::warn!(
"Instrument not found on channel {} [bank={} prog={}], substituted [bank={} prog={}]",
channel.id(), banknum, program_id,
subst_bank, subst_prog);
}
}
channel.set_sfontnum(preset.as_ref().map(|p| p.0));
channel.set_preset(preset.map(|p| p.1));
}