oxisynth 0.1.0

Rust soundfont synthesizer
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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
mod dsp_float;
mod envelope;

pub use envelope::EnvelopeStep;
use envelope::{Envelope, EnvelopePortion};

use crate::{
    core::{
        channel_pool::Channel,
        conv::{
            act2hz, atten2amp, cb2amp, ct2hz, ct2hz_real, pan, tc2sec, tc2sec_attack, tc2sec_delay,
            tc2sec_release,
        },
        soundfont::{
            generator::{Generator, GeneratorList, GeneratorType},
            modulator::Mod,
            Sample,
        },
        write::FxBuf,
        InterpolationMethod, BUFSIZE, BUFSIZE_F32,
    },
    midi_event::ControlFunction,
};

use soundfont::raw::{ControllerPalette, GeneralPalette};

type Phase = u64;

const GEN_ABS_NRPN: u32 = 2;
const GEN_SET: u32 = 1;

bitflags::bitflags! {
    /// Flags for marking samples for sanity checks
    #[derive(Clone)]
    struct SampleSanity: u32 {
        const CHECK = 1 << 0;
        const STARTUP = 1 << 1;
    }
}

#[derive(Clone, Copy, PartialEq)]
pub enum VoiceAddMode {
    Overwrite = 0,
    Add = 1,
    Default = 2,
}

#[derive(PartialEq, Clone)]
enum VoiceStatus {
    Clean,
    On,
    Sustained,
    Off,
}

/// This enumerator indicates a value which gives a variety of Boolean flags describing
/// the sample for the current instrument zone. The sampleModes should only appear in
/// the IGEN sub-chunk, and should not appear in the global zone. The two LS bits of
/// the value indicate the type of loop in the sample: 0 indicates a sound reproduced with
/// no loop, 1 indicates a sound which loops continuously, 2 is unused but should be
/// interpreted as indicating no loop, and 3 indicates a sound which loops for the
/// duration of key depression then proceeds to play the remainder of the sample.
#[derive(PartialEq, Eq, Clone, Copy)]
enum SampleMode {
    UnLooped = 0,
    DuringRelease = 1,
    // _Unused = 2,
    UntilRelease = 3,
}

impl SampleMode {
    pub fn from_val(v: f64) -> Self {
        if v == Self::UnLooped.as_f64() {
            Self::UnLooped
        } else if v == Self::DuringRelease.as_f64() {
            Self::DuringRelease
        } else if v == Self::UntilRelease.as_f64() {
            Self::UntilRelease
        } else {
            Self::UnLooped
        }
    }

    pub fn as_f64(&self) -> f64 {
        *self as u32 as f64
    }

    pub fn is_looping(&self, volenv_section: EnvelopeStep) -> bool {
        if self.is_during_release() {
            return true;
        }

        self.is_until_release() && volenv_section < EnvelopeStep::Release
    }

    pub fn is_during_release(&self) -> bool {
        *self == Self::DuringRelease
    }

    pub fn is_until_release(&self) -> bool {
        *self == Self::UntilRelease
    }
}

#[derive(Clone, Copy)]
pub enum ModulateCtrl {
    CC(ControlFunction),
    SF(GeneralPalette),
}

pub struct VoiceDescriptor<'a> {
    pub sample: Sample,
    pub channel: &'a Channel,
    pub key: u8,
    pub vel: u8,
    pub start_time: usize,
    pub gain: f32,
}

#[derive(Clone)]
pub(crate) struct Voice {
    note_id: usize,

    channel_id: usize,

    key: u8,
    vel: u8,

    interp_method: InterpolationMethod,
    mod_count: usize,

    sample: Sample,
    start_time: usize,

    ticks: usize,
    noteoff_ticks: usize,

    has_looped: bool,

    filter_startup: bool,

    volenv_count: u32,
    volenv_section: EnvelopeStep,
    volenv_val: f32,

    amp: f32,
    modenv_count: u32,
    modenv_section: EnvelopeStep,
    modenv_val: f32,

    modlfo_val: f32,
    viblfo_val: f32,

    hist1: f32,
    hist2: f32,

    gen: GeneratorList,
    synth_gain: f32,

    amplitude_that_reaches_noise_floor_nonloop: f32,
    amplitude_that_reaches_noise_floor_loop: f32,

    status: VoiceStatus,
    check_sample_sanity_flag: SampleSanity,
    min_attenuation_c_b: f32,

    last_fres: f32,

    // GenParams
    pan: f32,
    amp_left: f32,
    amp_right: f32,

    attenuation: f32,
    pitch: f32,

    reverb_send: f32,
    amp_reverb: f32,
    chorus_send: f32,
    amp_chorus: f32,

    root_pitch: f32,
    fres: f32,

    q_lin: f32,
    filter_gain: f32,

    modlfo_to_pitch: f32,
    modlfo_to_vol: f32,
    modlfo_to_fc: f32,
    modlfo_delay: usize,
    modlfo_incr: f32,

    viblfo_incr: f32,
    viblfo_delay: usize,
    viblfo_to_pitch: f32,

    modenv_to_pitch: f32,
    modenv_to_fc: f32,

    start: u32,
    end: u32,
    loopstart: u32,
    loopend: u32,

    volenv_data: Envelope,
    modenv_data: Envelope,
    mod_0: [Mod; 64],

    output_rate: f32,

    phase: Phase,

    filter_coeff_incr_count: usize,

    a1: f32,
    a2: f32,
    b02: f32,
    b1: f32,

    a1_incr: f32,
    a2_incr: f32,
    b02_incr: f32,
    b1_incr: f32,
}

impl Voice {
    pub(super) fn new(output_rate: f32, desc: VoiceDescriptor, note_id: usize) -> Voice {
        let mut volenv_data = Envelope::default();

        volenv_data[EnvelopeStep::Sustain] = EnvelopePortion {
            count: 0xffffffff,
            coeff: 1.0,
            incr: 0.0,
            min: -1.0,
            max: 2.0,
        };

        volenv_data[EnvelopeStep::Finished] = EnvelopePortion {
            count: 0xffffffff,
            coeff: 0.0,
            incr: 0.0,
            min: -1.0,
            max: 1.0,
        };

        let mut modenv_data = Envelope::default();

        modenv_data[EnvelopeStep::Sustain] = EnvelopePortion {
            count: 0xffffffff,
            coeff: 1.0,
            incr: 0.0,
            min: -1.0,
            max: 2.0,
        };

        modenv_data[EnvelopeStep::Finished] = EnvelopePortion {
            count: 0xffffffff,
            coeff: 0.0,
            incr: 0.0,
            min: -1.0,
            max: 1.0,
        };

        let synth_gain = if desc.gain < 0.0000001 {
            0.0000001
        } else {
            desc.gain
        };

        Voice {
            note_id,
            channel_id: desc.channel.id(),

            key: desc.key,
            vel: desc.vel,

            interp_method: desc.channel.interp_method(),
            mod_count: 0,

            sample: desc.sample,
            start_time: desc.start_time,

            ticks: 0,
            noteoff_ticks: 0,

            has_looped: false,

            last_fres: -1.0,
            filter_startup: true,

            volenv_count: 0,
            volenv_section: EnvelopeStep::Delay,
            volenv_val: 0.0,

            amp: 0.0,
            modenv_count: 0,
            modenv_section: EnvelopeStep::Delay,
            modenv_val: 0.0,

            modlfo_val: 0.0,
            viblfo_val: 0.0,

            hist1: 0.0,
            hist2: 0.0,

            gen: GeneratorList::new(desc.channel),
            synth_gain,

            amplitude_that_reaches_noise_floor_nonloop: 0.00003 / synth_gain,
            amplitude_that_reaches_noise_floor_loop: 0.00003 / synth_gain,

            status: VoiceStatus::Clean,
            mod_0: [Mod::default(); 64],
            check_sample_sanity_flag: SampleSanity::empty(),
            output_rate,
            phase: 0,
            pitch: 0.0,
            attenuation: 0.0,
            min_attenuation_c_b: 0.0,
            root_pitch: 0.0,
            start: 0,
            end: 0,
            loopstart: 0,
            loopend: 0,
            volenv_data,
            modenv_data,
            modenv_to_fc: 0.0,
            modenv_to_pitch: 0.0,
            modlfo_delay: 0,
            modlfo_incr: 0.0,
            modlfo_to_fc: 0.0,
            modlfo_to_pitch: 0.0,
            modlfo_to_vol: 0.0,
            viblfo_delay: 0,
            viblfo_incr: 0.0,
            viblfo_to_pitch: 0.0,
            fres: 0.0,
            q_lin: 0.0,
            filter_gain: 0.0,
            b02: 0.0,
            b1: 0.0,
            a1: 0.0,
            a2: 0.0,
            b02_incr: 0.0,
            b1_incr: 0.0,
            a1_incr: 0.0,
            a2_incr: 0.0,
            filter_coeff_incr_count: 0,
            pan: 0.0,
            amp_left: 0.0,
            amp_right: 0.0,
            reverb_send: 0.0,
            amp_reverb: 0.0,
            chorus_send: 0.0,
            amp_chorus: 0.0,
        }
    }

    /// Adds a modulator to the voice.  "mode" indicates, what to do, if
    /// an identical modulator exists already.
    ///
    /// mode == FLUID_VOICE_ADD: Identical modulators on preset level are added
    /// mode == FLUID_VOICE_OVERWRITE: Identical modulators on instrument level are overwritten
    /// mode == FLUID_VOICE_DEFAULT: This is a default modulator, there can be no identical modulator.
    ///                             Don't check.
    pub fn add_mod(&mut self, mod_0: &Mod, mode: VoiceAddMode) {
        // Some soundfonts come with a huge number of non-standard
        // controllers, because they have been designed for one particular
        // sound card.  Discard them, maybe print a warning.
        if let ControllerPalette::General(g) = &mod_0.src.controller_palette {
            match g {
                GeneralPalette::Unknown(_) | GeneralPalette::Link => {
                    log::warn!("Ignoring invalid controller, using non-CC source {:?}.", g);
                    return;
                }
                _ => {}
            }
        }

        if mode == VoiceAddMode::Add {
            // if identical modulator exists, add them
            for m in self.mod_0.iter_mut().take(self.mod_count) {
                if m.test_identity(mod_0) {
                    m.amount += mod_0.amount;
                    return;
                }
            }
        } else if mode == VoiceAddMode::Overwrite {
            // if identical modulator exists, replace it (only the amount has to be changed)
            for m in self.mod_0.iter_mut().take(self.mod_count) {
                if m.test_identity(mod_0) {
                    m.amount = mod_0.amount;
                    return;
                }
            }
        }

        // Add a new modulator (No existing modulator to add / overwrite).
        // Also, default modulators (VOICE_DEFAULT) are added without
        // checking, if the same modulator already exists.
        if self.mod_count < 64 {
            self.mod_0[self.mod_count] = *mod_0;
            self.mod_count += 1;
        };
    }

    pub fn add_default_mods(&mut self) {
        use crate::core::soundfont::modulator::default::*;
        self.add_mod(&DEFAULT_VEL2ATT_MOD, VoiceAddMode::Default);
        self.add_mod(&DEFAULT_VEL2FILTER_MOD, VoiceAddMode::Default);
        self.add_mod(&DEFAULT_AT2VIBLFO_MOD, VoiceAddMode::Default);
        self.add_mod(&DEFAULT_MOD2VIBLFO_MOD, VoiceAddMode::Default);
        self.add_mod(&DEFAULT_ATT_MOD, VoiceAddMode::Default);
        self.add_mod(&DEFAULT_PAN_MOD, VoiceAddMode::Default);
        self.add_mod(&DEFAULT_EXPR_MOD, VoiceAddMode::Default);
        self.add_mod(&DEFAULT_REVERB_MOD, VoiceAddMode::Default);
        self.add_mod(&DEFAULT_CHORUS_MOD, VoiceAddMode::Default);
        self.add_mod(&DEFAULT_PITCH_BEND_MOD, VoiceAddMode::Default);
    }

    pub fn gen_incr(&mut self, i: GeneratorType, val: f64) {
        self.gen[i].val += val;
        self.gen[i].flags = GEN_SET as u8;
    }

    pub fn gen_set(&mut self, i: GeneratorType, val: f64) {
        self.gen[i].val = val;
        self.gen[i].flags = GEN_SET as u8;
    }

    /// Percussion sounds can be mutually exclusive: for example, a 'closed
    /// hihat' sound will terminate an 'open hihat' sound ringing at the
    /// same time. This behaviour is modeled using 'exclusive classes',
    /// turning on a voice with an exclusive class other than 0 will kill
    /// all other voices having that exclusive class within the same preset
    /// or channel.  fluid_voice_kill_excl gets called, when 'voice' is to
    /// be killed for that reason.
    pub(super) fn kill_excl(&mut self) {
        if !self.is_playing() {
            return;
        }

        // Turn off the exclusive class information for this voice,
        // so that it doesn't get killed twice
        self.gen_set(GeneratorType::ExclusiveClass, 0.0);

        // If the voice is not yet in release state, put it into release state
        if self.volenv_section != EnvelopeStep::Release {
            self.volenv_section = EnvelopeStep::Release;
            self.volenv_count = 0;
            self.modenv_section = EnvelopeStep::Release;
            self.modenv_count = 0;
        }

        // Speed up the volume envelope
        // The value was found through listening tests with hi-hat samples.
        self.gen_set(GeneratorType::VolEnvRelease, -200.0);
        self.update_param(GeneratorType::VolEnvRelease);

        // Speed up the modulation envelope
        self.gen_set(GeneratorType::ModEnvRelease, -200.0);
        self.update_param(GeneratorType::ModEnvRelease);
    }

    pub(super) fn start(&mut self, channel: &Channel) {
        // The maximum volume of the loop is calculated and cached once for each
        // sample with its nominal loop settings. This happens, when the sample is used
        // for the first time.
        self.calculate_runtime_synthesis_parameters(channel);

        // Force setting of the phase at the first DSP loop run
        // This cannot be done earlier, because it depends on modulators.
        self.check_sample_sanity_flag = SampleSanity::STARTUP;
        self.status = VoiceStatus::On;
    }

    pub(super) fn noteoff(&mut self, channel: &Channel, min_note_length_ticks: usize) {
        if min_note_length_ticks > self.ticks {
            // Delay noteoff
            self.noteoff_ticks = min_note_length_ticks;
            return;
        }

        let sustained = {
            const SUSTAIN_SWITCH: usize = 64;
            // check is channel is sustained
            channel.cc(SUSTAIN_SWITCH) >= 64
        };

        if sustained {
            self.status = VoiceStatus::Sustained;
        } else {
            if self.volenv_section == EnvelopeStep::Attack {
                // A voice is turned off during the attack section of the volume
                // envelope.  The attack section ramps up linearly with
                // amplitude. The other sections use logarithmic scaling. Calculate new
                // volenv_val to achieve equivalent amplitude during the release phase
                // for seamless volume transition.
                if self.volenv_val > 0.0 {
                    let lfo: f32 = self.modlfo_val * -self.modlfo_to_vol;
                    let amp: f32 = self.volenv_val * f32::powf(10.0, lfo / -200.0);
                    let env_value = -((-200.0 * amp.ln() / f32::ln(10.0) - lfo) / 960.0 - 1.0);
                    self.volenv_val = env_value.clamp(0.0, 1.0);
                }
            }
            self.volenv_section = EnvelopeStep::Release;
            self.volenv_count = 0;
            self.modenv_section = EnvelopeStep::Release;
            self.modenv_count = 0;
        }
    }

    pub(super) fn modulate(&mut self, channel: &Channel, ctrl: ModulateCtrl) {
        let ctrl = match ctrl {
            ModulateCtrl::CC(control_function) => ControllerPalette::Midi(control_function as u8),
            ModulateCtrl::SF(v) => ControllerPalette::General(v),
        };

        #[inline(always)]
        fn mod_has_source(m: &Mod, ctrl: ControllerPalette) -> bool {
            m.src.controller_palette == ctrl || m.src2.controller_palette == ctrl
        }

        let mut i = 0;
        while i < self.mod_count {
            let mod_0 = &mut self.mod_0[i];

            if mod_has_source(mod_0, ctrl) {
                let gen = mod_0.get_dest();
                let mut modval = 0.0;

                let mut k = 0;
                while k < self.mod_count {
                    if self.mod_0[k].dest == gen {
                        modval += self.mod_0[k].get_value(channel, self);
                    }
                    k += 1
                }
                self.gen[gen].mod_0 = modval as f64;
                self.update_param(gen);
            }
            i += 1
        }
    }

    pub(super) fn modulate_all(&mut self, channel: &Channel) {
        for i in 0..self.mod_count {
            let gen = self.mod_0[i].get_dest();

            let modval: f32 = self
                .mod_0
                .iter()
                .take(self.mod_count)
                .filter(|k| k.dest == gen)
                .map(|k| k.get_value(channel, self))
                .sum();

            self.gen[gen].mod_0 = modval as f64;
            self.update_param(gen);
        }
    }

    /// Turns off a voice, meaning that it is not processed
    /// anymore by the DSP loop.
    pub(super) fn off(&mut self) {
        self.channel_id = 0xff;
        self.volenv_section = EnvelopeStep::Finished;
        self.volenv_count = 0;
        self.modenv_section = EnvelopeStep::Finished;
        self.modenv_count = 0;
        self.status = VoiceStatus::Off;
    }

    pub(crate) fn channel_id(&self) -> usize {
        self.channel_id
    }

    pub(super) fn get_note_id(&self) -> usize {
        self.note_id
    }

    /// A lower boundary for the attenuation (as in 'the minimum
    /// attenuation of this voice, with volume pedals, modulators
    /// etc. resulting in minimum attenuation, cannot fall below x cB) is
    /// calculated.  This has to be called during fluid_voice_init, after
    /// all modulators have been run on the voice once.  Also,
    /// voice.attenuation has to be initialized.
    fn get_lower_boundary_for_attenuation(&mut self, channel: &Channel) -> f32 {
        const MOD_PITCHWHEEL: i32 = 14;

        let mut possible_att_reduction_c_b = 0.0;
        for i in 0..self.mod_count {
            let mod_0 = &self.mod_0[i];

            // Modulator has attenuation as target and can change over time?
            if mod_0.dest == GeneratorType::Attenuation && (mod_0.src.is_cc() || mod_0.src2.is_cc())
            {
                let current_val: f32 = mod_0.get_value(channel, self);
                let mut v = mod_0.amount.abs() as f32;

                if mod_0.src.index as i32 == MOD_PITCHWHEEL
                    || mod_0.src.is_bipolar()
                    || mod_0.src2.is_bipolar()
                    || mod_0.amount < 0.0
                {
                    // Can this modulator produce a negative contribution?
                    v *= -1.0;
                } else {
                    v = 0.0;
                }

                // For example:
                // - current_val=100
                // - min_val=-4000
                // - possible_att_reduction_cB += 4100
                if current_val > v {
                    possible_att_reduction_c_b += current_val - v
                }
            }
        }

        let mut lower_bound = self.attenuation - possible_att_reduction_c_b;

        // SF2.01 specs do not allow negative attenuation
        if lower_bound < 0.0 {
            lower_bound = 0.0;
        }

        lower_bound
    }

    fn calculate_runtime_synthesis_parameters(&mut self, channel: &Channel) {
        let list_of_generators_to_initialize: [GeneratorType; 34] = [
            GeneratorType::StartAddrOfs,
            GeneratorType::EndAddrOfs,
            GeneratorType::StartLoopAddrOfs,
            GeneratorType::EndLoopAddrOfs,
            GeneratorType::ModLfoToPitch,
            GeneratorType::VibLfoToPitch,
            GeneratorType::ModEnvToPitch,
            GeneratorType::FilterFc,
            GeneratorType::FilterQ,
            GeneratorType::ModLfoToFilterFc,
            GeneratorType::ModEnvToFilterFc,
            GeneratorType::ModLfoToVol,
            GeneratorType::ChorusSend,
            GeneratorType::ReverbSend,
            GeneratorType::Pan,
            GeneratorType::ModLfoDelay,
            GeneratorType::ModLfoFreq,
            GeneratorType::VibLfoDelay,
            GeneratorType::VibLfoFreq,
            GeneratorType::ModEnvDelay,
            GeneratorType::ModEnvAttack,
            GeneratorType::ModEnvHold,
            GeneratorType::ModEnvDecay,
            GeneratorType::ModEnvRelease,
            GeneratorType::VolEnvDelay,
            GeneratorType::VolEnvAttack,
            GeneratorType::VolEnvHold,
            GeneratorType::VolEnvDecay,
            GeneratorType::VolEnvRelease,
            GeneratorType::KeyNum,
            GeneratorType::Velocity,
            GeneratorType::Attenuation,
            GeneratorType::OverrideRootKey,
            GeneratorType::Pitch,
        ];

        let mut i = 0;
        while i < self.mod_count {
            let mod_0 = &self.mod_0[i];
            let modval: f32 = mod_0.get_value(channel, self);
            let dest_gen = &mut self.gen[mod_0.dest];
            dest_gen.mod_0 += modval as f64;
            i += 1
        }
        let tuning = channel.tuning();
        if let Some(tuning) = tuning {
            self.gen[GeneratorType::Pitch].val = tuning.pitch[60]
                + self.gen[GeneratorType::ScaleTune].val / 100.0f32 as f64
                    * (tuning.pitch[self.key as usize] - tuning.pitch[60])
        } else {
            self.gen[GeneratorType::Pitch].val = self.gen[GeneratorType::ScaleTune].val
                * (self.key as i32 as f32 - 60.0f32) as f64
                + (100.0f32 * 60.0f32) as f64
        }

        for gen in list_of_generators_to_initialize.iter() {
            self.update_param(*gen);
        }

        self.min_attenuation_c_b = self.get_lower_boundary_for_attenuation(channel);
    }

    /// Make sure, that sample start / end point and loop points are in
    /// proper order. When starting up, calculate the initial phase.
    fn check_sample_sanity(&mut self) {
        let min_index_nonloop = self.sample.start();
        let max_index_nonloop = self.sample.end();

        // make sure we have enough samples surrounding the loop
        let min_index_loop = self.sample.start();
        // 'end' is last valid sample, loopend can be + 1
        let max_index_loop = self.sample.end() + 1;

        if self.check_sample_sanity_flag.is_empty() {
            return;
        }

        // Keep the start point within the sample data
        if self.start < min_index_nonloop {
            self.start = min_index_nonloop
        } else if self.start > max_index_nonloop {
            self.start = max_index_nonloop
        }

        // Keep the end point within the sample data
        if self.end < min_index_nonloop {
            self.end = min_index_nonloop
        } else if self.end > max_index_nonloop {
            self.end = max_index_nonloop
        }

        // Keep start and end point in the right order
        if self.start > self.end {
            let start = self.start;
            let end = self.end;

            self.start = end;
            self.end = start;
        }

        // Zero length?
        if self.start == self.end {
            self.off();
            return;
        }

        let sample_mode = SampleMode::from_val(self.gen[GeneratorType::SampleMode].val);
        if sample_mode.is_until_release() || sample_mode.is_during_release() {
            // Keep the loop start point within the sample data
            if self.loopstart < min_index_loop {
                self.loopstart = min_index_loop
            } else if self.loopstart > max_index_loop {
                self.loopstart = max_index_loop
            }

            // Keep the loop end point within the sample data
            if self.loopend < min_index_loop {
                self.loopend = min_index_loop
            } else if self.loopend > max_index_loop {
                self.loopend = max_index_loop
            }

            // Keep loop start and end point in the right order
            if self.loopstart > self.loopend {
                let start = self.loopstart;
                let end = self.loopend;

                self.loopstart = end;
                self.loopend = start;
            }

            // Loop too short? Then don't loop.
            if self.loopend < self.loopstart + 2 {
                self.gen[GeneratorType::SampleMode].val = SampleMode::UnLooped.as_f64();
            }

            // The loop points may have changed. Obtain a new estimate for the loop volume.
            // Is the voice loop within the sample loop?
            if self.loopstart >= self.sample.loop_start() && self.loopend <= self.sample.loop_end()
            {
                // Is there a valid peak amplitude available for the loop?
                if let Some(amplitude_that_reaches_noise_floor) =
                    self.sample.amplitude_that_reaches_noise_floor()
                {
                    self.amplitude_that_reaches_noise_floor_loop =
                        (amplitude_that_reaches_noise_floor / self.synth_gain as f64) as f32
                } else {
                    // Worst case
                    self.amplitude_that_reaches_noise_floor_loop =
                        self.amplitude_that_reaches_noise_floor_nonloop
                }
            }
        }

        // Run startup specific code (only once, when the voice is started)
        if self
            .check_sample_sanity_flag
            .contains(SampleSanity::STARTUP)
        {
            if max_index_loop - min_index_loop < 2 {
                let sample_mode = &mut self.gen[GeneratorType::SampleMode];

                let mode = SampleMode::from_val(sample_mode.val);

                if mode.is_until_release() || mode.is_during_release() {
                    sample_mode.val = SampleMode::UnLooped.as_f64();
                }
            }

            // Set the initial phase of the voice (using the result from the
            // start offset modulators).
            self.phase = (self.start as u64) << 32i32
        }

        // Is this voice run in loop mode, or does it run straight to the
        // end of the waveform data?
        if SampleMode::from_val(self.gen[GeneratorType::SampleMode].val)
            .is_looping(self.volenv_section)
        {
            // Yes, it will loop as soon as it reaches the loop point.  In
            // this case we must prevent, that the playback pointer (phase)
            // happens to end up beyond the 2nd loop point, because the
            // point has moved.  The DSP algorithm is unable to cope with
            // that situation.  So if the phase is beyond the 2nd loop
            // point, set it to the start of the loop. No way to avoid some
            // noise here.  Note: If the sample pointer ends up -before the
            // first loop point- instead, then the DSP loop will just play
            // the sample, enter the loop and proceed as expected => no
            // actions required.
            let index_in_sample: i32 = (self.phase >> 32i32) as u32 as i32;
            if index_in_sample >= self.loopend as i32 {
                self.phase = (self.loopstart as u64) << 32i32
            }
        }

        // Sample sanity has been assured. Don't check again, until some
        // sample parameter is changed by modulation.
        self.check_sample_sanity_flag = SampleSanity::empty();
    }

    pub(super) fn set_param(&mut self, gen: GeneratorType, nrpn_value: f32, abs: i32) {
        self.gen[gen].nrpn = nrpn_value as f64;
        self.gen[gen].flags = if abs != 0 {
            GEN_ABS_NRPN as i32
        } else {
            GEN_SET as i32
        } as u8;
        self.update_param(gen);
    }

    pub(super) fn set_gain(&mut self, mut gain: f32) {
        // avoid division by zero
        if gain < 0.0000001 {
            gain = 0.0000001;
        }

        self.synth_gain = gain;
        self.amp_left = pan(self.pan, 1) * gain / 32768.0;
        self.amp_right = pan(self.pan, 0) * gain / 32768.0;
        self.amp_reverb = self.reverb_send * gain / 32768.0;
        self.amp_chorus = self.chorus_send * gain / 32768.0;
    }

    pub(crate) fn write(
        &mut self,
        channel: &Channel,
        min_note_length_ticks: usize,
        (dsp_left_buf, dsp_right_buf): (&mut [f32; 64], &mut [f32; 64]),
        fx_left_buf: &mut FxBuf,
        reverb_active: bool,
        chorus_active: bool,
    ) {
        let mut dsp_buf: [f32; 64] = [0.; 64];

        // make sure we're playing and that we have sample data
        if !self.is_playing() {
            return;
        }

        // sample
        if self.noteoff_ticks != 0 && self.ticks >= self.noteoff_ticks {
            self.noteoff(channel, min_note_length_ticks);
        }

        // Range checking for sample- and loop-related parameters
        // Initial phase is calculated here
        self.check_sample_sanity();

        // skip to the next section of the envelope if necessary
        let mut env_data = &self.volenv_data[self.volenv_section];
        while self.volenv_count >= env_data.count {
            // If we're switching envelope stages from decay to sustain, force the value to be the end value of the previous stage
            if self.volenv_section == EnvelopeStep::Decay {
                self.volenv_val = env_data.min * env_data.coeff
            }

            self.volenv_section.next();
            env_data = &self.volenv_data[self.volenv_section];
            self.volenv_count = 0;
        }

        // calculate the envelope value and check for valid range
        let mut x = env_data.coeff * self.volenv_val + env_data.incr;
        if x < env_data.min {
            x = env_data.min;
            self.volenv_section.next();
            self.volenv_count = 0;
        } else if x > env_data.max {
            x = env_data.max;
            self.volenv_section.next();
            self.volenv_count = 0;
        }

        self.volenv_val = x;
        self.volenv_count = self.volenv_count.wrapping_add(1);

        if self.volenv_section == EnvelopeStep::Finished {
            self.off();
            return;
        }

        // mod env

        let mut env_data = &self.modenv_data[self.modenv_section];

        // skip to the next section of the envelope if necessary
        while self.modenv_count >= env_data.count {
            self.modenv_section.next();
            env_data = &self.modenv_data[self.modenv_section];
            self.modenv_count = 0;
        }

        // calculate the envelope value and check for valid range
        let mut x = env_data.coeff * self.modenv_val + env_data.incr;

        if x < env_data.min {
            x = env_data.min;
            self.modenv_section.next();
            self.modenv_count = 0;
        } else if x > env_data.max {
            x = env_data.max;
            self.modenv_section.next();
            self.modenv_count = 0;
        }

        self.modenv_val = x;
        self.modenv_count = self.modenv_count.wrapping_add(1);

        // mod lfo

        if self.ticks >= self.modlfo_delay {
            self.modlfo_val += self.modlfo_incr;
            if self.modlfo_val > 1.0 {
                self.modlfo_incr = -self.modlfo_incr;
                self.modlfo_val = 2.0 - self.modlfo_val
            } else if self.modlfo_val < -1.0 {
                self.modlfo_incr = -self.modlfo_incr;
                self.modlfo_val = -2.0 - self.modlfo_val
            }
        }

        // vib lfo
        if self.ticks >= self.viblfo_delay {
            self.viblfo_val += self.viblfo_incr;
            if self.viblfo_val > 1.0 {
                self.viblfo_incr = -self.viblfo_incr;
                self.viblfo_val = 2.0 - self.viblfo_val
            } else if self.viblfo_val < -1.0 {
                self.viblfo_incr = -self.viblfo_incr;
                self.viblfo_val = -2.0 - self.viblfo_val
            }
        }

        // amplitude

        // calculate final amplitude
        // - initial gain
        // - amplitude envelope

        let target_amplitude = if self.volenv_section != EnvelopeStep::Delay {
            if self.volenv_section == EnvelopeStep::Attack {
                // the envelope is in the attack section: ramp linearly to max value.
                // A positive modlfo_to_vol should increase volume (negative attenuation).
                let target_amp = atten2amp(self.attenuation)
                    * cb2amp(self.modlfo_val * -self.modlfo_to_vol)
                    * self.volenv_val;

                Some(target_amp)
            } else {
                let target_amp = atten2amp(self.attenuation)
                    * cb2amp(
                        960.0 * (1.0 - self.volenv_val) + self.modlfo_val * -self.modlfo_to_vol,
                    );

                // We turn off a voice, if the volume has dropped low enough.

                // A voice can be turned off, when an estimate for the volume
                // (upper bound) falls below that volume, that will drop the
                // sample below the noise floor.

                // If the loop amplitude is known, we can use it if the voice loop is within
                // the sample loop

                // Is the playing pointer already in the loop?
                let amplitude_that_reaches_noise_floor = if self.has_looped {
                    self.amplitude_that_reaches_noise_floor_loop
                } else {
                    self.amplitude_that_reaches_noise_floor_nonloop
                };

                // voice->attenuation_min is a lower boundary for the attenuation
                // now and in the future (possibly 0 in the worst case).  Now the
                // amplitude of sample and volenv cannot exceed amp_max (since
                // volenv_val can only drop):
                let amp_max = atten2amp(self.min_attenuation_c_b) * self.volenv_val;

                // And if amp_max is already smaller than the known amplitude,
                // which will attenuate the sample below the noise floor, then we
                // can safely turn off the voice. Duh.
                if amp_max < amplitude_that_reaches_noise_floor {
                    self.off();
                    None
                } else {
                    Some(target_amp)
                }
            }
        } else {
            None
        };

        if let Some(target_amp) = target_amplitude {
            // Volume increment to go from voice->amp to target_amp in FLUID_BUFSIZE steps
            let amp_incr = (target_amp - self.amp) / BUFSIZE_F32;
            // no volume and not changing? - No need to process
            if !(self.amp == 0.0 && amp_incr == 0.0) {
                // Calculate the number of samples, that the DSP loop advances
                // through the original waveform with each step in the output
                // buffer. It is the ratio between the frequencies of original
                // waveform and output waveform.
                let mut phase_incr = ct2hz_real(
                    self.pitch
                        + self.modlfo_val * self.modlfo_to_pitch
                        + self.viblfo_val * self.viblfo_to_pitch
                        + self.modenv_val * self.modenv_to_pitch,
                ) / self.root_pitch;

                // if phase_incr is not advancing, set it to the minimum fraction value (prevent stuckage)
                if phase_incr == 0.0 {
                    phase_incr = 1.0;
                }

                // resonant filter

                // calculate the frequency of the resonant filter in Hz
                let fres = ct2hz(
                    self.fres
                        + self.modlfo_val * self.modlfo_to_fc
                        + self.modenv_val * self.modenv_to_fc,
                );

                // FIXME - Still potential for a click during turn on, can we interpolate
                // between 20khz cutoff and 0 Q?

                // I removed the optimization of turning the filter off when the
                // resonance frequencies is above the maximum frequency. Instead, the
                // filter frequency is set to a maximum of 0.45 times the sampling
                // rate. For a 44100 kHz sampling rate, this amounts to 19845
                // Hz. The reason is that there were problems with anti-aliasing when the
                // synthesizer was run at lower sampling rates. Thanks to Stephan
                // Tassart for pointing me to this bug. By turning the filter on and
                // clipping the maximum filter frequency at 0.45*srate, the filter
                // is used as an anti-aliasing filter.
                let fres = if fres > 0.45 * self.output_rate {
                    0.45 * self.output_rate
                } else if fres < 5.0 {
                    5.0
                } else {
                    fres
                };

                // if filter enabled and there is a significant frequency change..
                if (fres - self.last_fres).abs() > 0.01 {
                    // The filter coefficients have to be recalculated (filter
                    // parameters have changed). Recalculation for various reasons is
                    // forced by setting last_fres to -1.  The flag filter_startup
                    // indicates, that the DSP loop runs for the first time, in this
                    // case, the filter is set directly, instead of smoothly fading
                    // between old and new settings.
                    //
                    // Those equations from Robert Bristow-Johnson's `Cookbook
                    // formulae for audio EQ biquad filter coefficients', obtained
                    // from Harmony-central.com / Computer / Programming. They are
                    // the result of the bilinear transform on an analogue filter
                    // prototype. To quote, `BLT frequency warping has been taken
                    // into account for both significant frequency relocation and for
                    // bandwidth readjustment'.

                    let omega = 2.0 * std::f32::consts::PI * (fres / self.output_rate);
                    let sin_coeff = omega.sin();
                    let cos_coeff = omega.cos();
                    let alpha_coeff = sin_coeff / (2.0 * self.q_lin);
                    let a0_inv = 1.0 / (1.0 + alpha_coeff);

                    // Calculate the filter coefficients. All coefficients are
                    // normalized by a0. Think of `a1' as `a1/a0'.
                    //
                    // Here a couple of multiplications are saved by reusing common expressions.
                    // The original equations should be:
                    //  voice->b0=(1.-cos_coeff)*a0_inv*0.5*voice->filter_gain;
                    //  voice->b1=(1.-cos_coeff)*a0_inv*voice->filter_gain;
                    //  voice->b2=(1.-cos_coeff)*a0_inv*0.5*voice->filter_gain;
                    let a1_temp = -2.0 * cos_coeff * a0_inv;
                    let a2_temp = (1.0 - alpha_coeff) * a0_inv;
                    let b1_temp = (1.0 - cos_coeff) * a0_inv * (self).filter_gain;
                    // both b0 -and- b2
                    let b02_temp = b1_temp * 0.5;

                    if self.filter_startup {
                        // The filter is calculated, because the voice was started up.
                        // In this case set the filter coefficients without delay.
                        self.a1 = a1_temp;
                        self.a2 = a2_temp;
                        self.b02 = b02_temp;
                        self.b1 = b1_temp;
                        self.filter_coeff_incr_count = 0;
                        self.filter_startup = false;
                    } else {
                        // The filter frequency is changed.  Calculate an increment
                        // factor, so that the new setting is reached after one buffer
                        // length. x_incr is added to the current value FLUID_BUFSIZE
                        // times. The length is arbitrarily chosen. Longer than one
                        // buffer will sacrifice some performance, though.  Note: If
                        // the filter is still too 'grainy', then increase this number
                        // at will.
                        self.a1_incr = (a1_temp - self.a1) / BUFSIZE_F32;
                        self.a2_incr = (a2_temp - self.a2) / BUFSIZE_F32;
                        self.b02_incr = (b02_temp - self.b02) / BUFSIZE_F32;
                        self.b1_incr = (b1_temp - self.b1) / BUFSIZE_F32;

                        // Have to add the increments filter_coeff_incr_count times.
                        self.filter_coeff_incr_count = BUFSIZE;
                    }
                    self.last_fres = fres
                }

                let count = match self.interp_method {
                    InterpolationMethod::None => {
                        self.dsp_float_interpolate_none(&mut dsp_buf, amp_incr, phase_incr)
                    }
                    InterpolationMethod::Linear => {
                        self.dsp_float_interpolate_linear(&mut dsp_buf, amp_incr, phase_incr)
                    }
                    InterpolationMethod::FourthOrder => {
                        self.dsp_float_interpolate_4th_order(&mut dsp_buf, amp_incr, phase_incr)
                    }
                    InterpolationMethod::SeventhOrder => {
                        self.dsp_float_interpolate_7th_order(&mut dsp_buf, amp_incr, phase_incr)
                    }
                };

                if count > 0 {
                    self.effects(
                        &mut dsp_buf,
                        count,
                        (dsp_left_buf, dsp_right_buf),
                        fx_left_buf,
                        reverb_active,
                        chorus_active,
                    );
                }
                // turn off voice if short count (sample ended and not looping)
                if count < BUFSIZE {
                    self.off();
                }
            }
        }

        self.ticks += BUFSIZE;
    }

    /// Purpose:
    ///
    /// - filters (applies a lowpass filter with variable cutoff frequency and quality factor)
    /// - mixes the processed sample to left and right output using the pan setting
    /// - sends the processed sample to chorus and reverb
    ///
    /// Variable description:
    /// - dsp_data: Pointer to the original waveform data
    /// - dsp_left_buf: The generated signal goes here, left channel
    /// - dsp_right_buf: right channel
    /// - dsp_reverb_buf: Send to reverb unit
    /// - dsp_chorus_buf: Send to chorus unit
    /// - dsp_a1: Coefficient for the filter
    /// - dsp_a2: same
    /// - dsp_b0: same
    /// - dsp_b1: same
    /// - dsp_b2: same
    /// - voice holds the voice structure
    ///
    /// A couple of variables are used internally, their results are discarded:
    /// - dsp_i: Index through the output buffer
    /// - dsp_phase_fractional: The fractional part of dsp_phase
    /// - dsp_coeff: A table of four coefficients, depending on the fractional phase.
    ///   Used to interpolate between samples.
    /// - dsp_process_buffer: Holds the processed signal between stages
    /// - dsp_centernode: delay line for the IIR filter
    /// - dsp_hist1: same
    /// - dsp_hist2: same
    #[inline]
    fn effects(
        &mut self,
        dsp_buf: &mut [f32; 64],
        count: usize,
        (dsp_left_buf, dsp_right_buf): (&mut [f32], &mut [f32]),
        fx_buf: &mut FxBuf,
        reverb_active: bool,
        chorus_active: bool,
    ) {
        // IIR filter sample history
        let mut dsp_hist1 = self.hist1;
        let mut dsp_hist2 = self.hist2;

        // IIR filter coefficients
        let mut dsp_a1 = self.a1;
        let mut dsp_a2 = self.a2;
        let mut dsp_b02 = self.b02;
        let mut dsp_b1 = self.b1;
        let mut dsp_filter_coeff_incr_count = self.filter_coeff_incr_count;

        let mut dsp_centernode;

        // filter (implement the voice filter according to SoundFont standard)

        // Check for denormal number (too close to zero).
        if dsp_hist1.abs() < 1e-20 {
            dsp_hist1 = 0.0; // FIXME JMG - Is this even needed?
        }

        // Two versions of the filter loop. One, while the filter is
        // changing towards its new setting. The other, if the filter
        // doesn't change.

        if dsp_filter_coeff_incr_count > 0 {
            // Increment is added to each filter coefficient filter_coeff_incr_count times.
            for dsp in dsp_buf.iter_mut().take(count) {
                // The filter is implemented in Direct-II form.
                dsp_centernode = *dsp - dsp_a1 * dsp_hist1 - dsp_a2 * dsp_hist2;
                *dsp = dsp_b02 * (dsp_centernode + dsp_hist2) + dsp_b1 * dsp_hist1;
                dsp_hist2 = dsp_hist1;
                dsp_hist1 = dsp_centernode;
                let fresh0 = dsp_filter_coeff_incr_count;
                dsp_filter_coeff_incr_count -= 1;

                if fresh0 > 0 {
                    dsp_a1 += self.a1_incr;
                    dsp_a2 += self.a2_incr;
                    dsp_b02 += self.b02_incr;
                    dsp_b1 += self.b1_incr;
                }
            }
        }
        // The filter parameters are constant.  This is duplicated to save time.
        else {
            // The filter is implemented in Direct-II form.
            for dsp in dsp_buf.iter_mut().take(count) {
                dsp_centernode = *dsp - dsp_a1 * dsp_hist1 - dsp_a2 * dsp_hist2;
                *dsp = dsp_b02 * (dsp_centernode + dsp_hist2) + dsp_b1 * dsp_hist1;
                dsp_hist2 = dsp_hist1;
                dsp_hist1 = dsp_centernode;
            }
        }

        // pan (Copy the signal to the left and right output buffer) The voice
        // panning generator has a range of -500 .. 500.  If it is centered,
        // it's close to 0.  voice->amp_left and voice->amp_right are then the
        // same, and we can save one multiplication per voice and sample.

        if self.pan > -0.5 && self.pan < 0.5 {
            for ((left, right), dsp) in dsp_left_buf
                .iter_mut()
                .zip(dsp_right_buf.iter_mut())
                .zip(dsp_buf.iter().copied())
                .take(count)
            {
                // The voice is centered. Use voice->amp_left twice.
                let v = self.amp_left * dsp;
                *left += v;
                *right += v;
            }
        }
        // The voice is not centered. Stereo samples have one side zero.
        else {
            if self.amp_left != 0.0 {
                for (left, dsp) in dsp_left_buf
                    .iter_mut()
                    .zip(dsp_buf.iter().copied())
                    .take(count)
                {
                    *left += self.amp_left * dsp;
                }
            }
            if self.amp_right != 0.0 {
                for (right, dsp) in dsp_right_buf
                    .iter_mut()
                    .zip(dsp_buf.iter().copied())
                    .take(count)
                {
                    *right += self.amp_right * dsp;
                }
            }
        }

        if reverb_active && self.amp_reverb != 0.0 {
            for (fx, dsp) in fx_buf
                .reverb
                .iter_mut()
                .zip(dsp_buf.iter().copied())
                .take(count)
            {
                *fx += self.amp_reverb * dsp;
            }
        }

        if chorus_active && self.amp_chorus != 0.0 {
            for (fx, dsp) in fx_buf
                .chorus
                .iter_mut()
                .zip(dsp_buf.iter().copied())
                .take(count)
            {
                *fx += self.amp_chorus * dsp;
            }
        }

        self.hist1 = dsp_hist1;
        self.hist2 = dsp_hist2;
        self.a1 = dsp_a1;
        self.a2 = dsp_a2;
        self.b02 = dsp_b02;
        self.b1 = dsp_b1;
        self.filter_coeff_incr_count = dsp_filter_coeff_incr_count;
    }

    fn calculate_hold_decay_buffers(
        &mut self,
        gen_base: GeneratorType,
        gen_key2base: GeneratorType,
        is_decay: i32,
    ) -> i32 {
        let mut timecents =
            (self.gen[gen_base].val + self.gen[gen_base].mod_0 + self.gen[gen_base].nrpn)
                + (self.gen[gen_key2base].val
                    + self.gen[gen_key2base].mod_0
                    + self.gen[gen_key2base].nrpn)
                    * (60.0 - self.key as f64);
        if is_decay != 0 {
            if timecents > 8000.0 {
                timecents = 8000.0;
            }
        } else {
            if timecents > 5000.0 {
                timecents = 5000.0;
            }
            if timecents <= -32768.0 {
                return 0;
            }
        }
        if timecents < -12000.0 {
            timecents = -12000.0;
        }
        let seconds = tc2sec(timecents);
        // buffers
        ((self.output_rate as f64 * seconds / BUFSIZE as f64) + 0.5) as i32
    }

    /// The value of a generator (gen) has changed.  (The different
    /// generators are listed in fluidlite.h, or in SF2.01 page 48-49)
    /// Now the dependent 'voice' parameters are calculated.
    ///
    /// fluid_voice_update_param can be called during the setup of the
    /// voice (to calculate the initial value for a voice parameter), or
    /// during its operation (a generator has been changed due to
    /// real-time parameter modifications like pitch-bend).
    ///
    /// Note: The generator holds three values: The base value .val, an
    /// offset caused by modulators .mod, and an offset caused by the
    /// NRPN system. _GEN(voice, generator_enumerator) returns the sum
    /// of all three.
    fn update_param(&mut self, gen: GeneratorType) {
        macro_rules! gen_sum {
            ($id: expr) => {{
                let Generator {
                    val, mod_0, nrpn, ..
                } = &self.gen[$id];

                (val + mod_0 + nrpn) as f32
            }};
        }

        match gen {
            GeneratorType::Pan => {
                // range checking is done in the fluid_pan function
                self.pan = gen_sum!(GeneratorType::Pan);

                self.amp_left = pan(self.pan, 1) * self.synth_gain / 32768.0;
                self.amp_right = pan(self.pan, 0) * self.synth_gain / 32768.0;
            }

            GeneratorType::Attenuation => {
                // Alternate attenuation scale used by EMU10K1 cards when setting the attenuation at the preset or instrument level within the SoundFont bank.
                static ALT_ATTENUATION_SCALE: f64 = 0.4;

                self.attenuation =
                    (self.gen[GeneratorType::Attenuation].val * ALT_ATTENUATION_SCALE
                        + self.gen[GeneratorType::Attenuation].mod_0
                        + self.gen[GeneratorType::Attenuation].nrpn) as f32;

                // Range: SF2.01 section 8.1.3 # 48
                // Motivation for range checking:
                // OHPiano.SF2 sets initial attenuation to a whooping -96 dB
                self.attenuation = self.attenuation.clamp(0.0, 1440.0);
            }
            // The pitch is calculated from three different generators.
            // Read comment in fluidlite.h about GEN_PITCH.
            GeneratorType::Pitch | GeneratorType::CoarseTune | GeneratorType::FineTune => {
                // The testing for allowed range is done in 'fluid_ct2hz'

                self.pitch = gen_sum!(GeneratorType::Pitch)
                    + 100.0 * gen_sum!(GeneratorType::CoarseTune)
                    + gen_sum!(GeneratorType::FineTune);
            }

            GeneratorType::ReverbSend => {
                // The generator unit is 'tenths of a percent'.
                self.reverb_send = gen_sum!(GeneratorType::ReverbSend) / 1000.0;

                self.reverb_send = self.reverb_send.clamp(0.0, 1.0);
                self.amp_reverb = self.reverb_send * self.synth_gain / 32768.0;
            }

            GeneratorType::ChorusSend => {
                // The generator unit is 'tenths of a percent'.
                self.chorus_send = gen_sum!(GeneratorType::ChorusSend) / 1000.0;

                self.chorus_send = self.chorus_send.clamp(0.0, 1.0);
                self.amp_chorus = self.chorus_send * self.synth_gain / 32768.0;
            }

            GeneratorType::OverrideRootKey => {
                // This is a non-realtime parameter. Therefore the .mod part of the generator
                // can be neglected.
                // NOTE: origpitch sets MIDI root note while pitchadj is a fine tuning amount
                // which offsets the original rate.  This means that the fine tuning is
                // inverted with respect to the root note (so subtract it, not add).

                // FIXME: use flag instead of -1
                if self.gen[GeneratorType::OverrideRootKey].val > -1.0 {
                    self.root_pitch = (self.gen[GeneratorType::OverrideRootKey].val * 100.0
                        - self.sample.pitchadj() as f64)
                        as f32
                } else {
                    self.root_pitch =
                        self.sample.origpitch() as f32 * 100.0 - self.sample.pitchadj() as f32
                }
                self.root_pitch = ct2hz(self.root_pitch);

                self.root_pitch *= self.output_rate / self.sample.sample_rate() as f32
            }

            GeneratorType::FilterFc => {
                // The resonance frequency is converted from absolute cents to
                // midicents .val and .mod are both used, this permits real-time
                // modulation.  The allowed range is tested in the 'fluid_ct2hz'
                // function [PH,20021214]

                self.fres = gen_sum!(GeneratorType::FilterFc);
                // The synthesis loop will have to recalculate the filter
                // coefficients.
                self.last_fres = -1.0;
            }

            GeneratorType::FilterQ => {
                // The generator contains 'centibels' (1/10 dB) => divide by 10 to
                // obtain dB
                let q_db = gen_sum!(GeneratorType::FilterQ) / 10.0;
                // Range: SF2.01 section 8.1.3 # 8 (convert from cB to dB => /10)
                let mut q_db = q_db.clamp(0.0, 96.0);

                // Short version: Modify the Q definition in a way, that a Q of 0
                // dB leads to no resonance hump in the freq. response.
                //
                // Long version: From SF2.01, page 39, item 9 (initialFilterQ):
                // "The gain at the cutoff frequency may be less than zero when
                // zero is specified".  Assume q_dB=0 / q_lin=1: If we would leave
                // q as it is, then this results in a 3 dB hump slightly below
                // fc. At fc, the gain is exactly the DC gain (0 dB).  What is
                // (probably) meant here is that the filter does not show a
                // resonance hump for q_dB=0. In this case, the corresponding
                // q_lin is 1/sqrt(2)=0.707.  The filter should have 3 dB of
                // attenuation at fc now.  In this case Q_dB is the height of the
                // resonance peak not over the DC gain, but over the frequency
                // response of a non-resonant filter.  This idea is implemented as
                // follows:
                q_db -= 3.01;

                // The 'sound font' Q is defined in dB. The filter needs a linear
                // q. Convert.
                self.q_lin = f32::powf(10.0, q_db / 20.0);
                // SF 2.01 page 59:
                //
                //  The SoundFont specs ask for a gain reduction equal to half the
                //  height of the resonance peak (Q).  For example, for a 10 dB
                //  resonance peak, the gain is reduced by 5 dB.  This is done by
                //  multiplying the total gain with sqrt(1/Q).  `Sqrt' divides dB
                //  by 2 (100 lin = 40 dB, 10 lin = 20 dB, 3.16 lin = 10 dB etc)
                //  The gain is later factored into the 'b' coefficients
                //  (numerator of the filter equation).  This gain factor depends
                //  only on Q, so this is the right place to calculate it.
                self.filter_gain = 1.0 / f32::sqrt(self.q_lin);

                // The synthesis loop will have to recalculate the filter coefficients.
                self.last_fres = -1.0;
            }

            GeneratorType::ModLfoToPitch => {
                self.modlfo_to_pitch = gen_sum!(GeneratorType::ModLfoToPitch);

                self.modlfo_to_pitch = self.modlfo_to_pitch.clamp(-12000.0, 12000.0);
            }

            GeneratorType::ModLfoToVol => {
                self.modlfo_to_vol = gen_sum!(GeneratorType::ModLfoToVol);

                self.modlfo_to_vol = self.modlfo_to_vol.clamp(-960.0, 960.0);
            }

            GeneratorType::ModLfoToFilterFc => {
                self.modlfo_to_fc = gen_sum!(GeneratorType::ModLfoToFilterFc);

                self.modlfo_to_fc = self.modlfo_to_fc.clamp(-12000.0, 12000.0);
            }

            GeneratorType::ModLfoDelay => {
                let val = gen_sum!(GeneratorType::ModLfoDelay);

                let val = val.clamp(-12000.0, 5000.0);
                self.modlfo_delay = (self.output_rate * tc2sec_delay(val)) as usize;
            }

            GeneratorType::ModLfoFreq => {
                // - the frequency is converted into a delta value, per buffer of FLUID_BUFSIZE samples
                // - the delay into a sample delay
                let val = gen_sum!(GeneratorType::ModLfoFreq);

                let val = val.clamp(-16000.0, 4500.0);
                self.modlfo_incr = 4.0 * BUFSIZE_F32 * act2hz(val) / self.output_rate;
            }

            GeneratorType::VibLfoFreq => {
                // vib lfo
                //
                // - the frequency is converted into a delta value, per buffer of FLUID_BUFSIZE samples
                // - the delay into a sample delay
                let freq = gen_sum!(GeneratorType::VibLfoFreq);

                let freq = freq.clamp(-16000.0, 4500.0);
                self.viblfo_incr = 4.0 * BUFSIZE_F32 * act2hz(freq) / self.output_rate;
            }

            GeneratorType::VibLfoDelay => {
                let val = gen_sum!(GeneratorType::VibLfoDelay);

                let val = val.clamp(-12000.0, 5000.0);
                self.viblfo_delay = (self.output_rate * tc2sec_delay(val)) as usize;
            }

            GeneratorType::VibLfoToPitch => {
                self.viblfo_to_pitch = gen_sum!(GeneratorType::VibLfoToPitch);

                self.viblfo_to_pitch = self.viblfo_to_pitch.clamp(-12000.0, 12000.0);
            }

            GeneratorType::KeyNum => {
                // GEN_KEYNUM: SF2.01 page 46, item 46
                //
                // If this generator is active, it forces the key number to its
                // value.  Non-realtime controller.
                //
                // There is a flag, which should indicate, whether a generator is
                // enabled or not.  But here we rely on the default value of -1.
                let val = gen_sum!(GeneratorType::KeyNum);

                if val >= 0.0 {
                    self.key = val as u8;
                }
            }

            GeneratorType::Velocity => {
                // GEN_VELOCITY: SF2.01 page 46, item 47
                //
                // If this generator is active, it forces the velocity to its
                // value. Non-realtime controller.
                //
                // There is a flag, which should indicate, whether a generator is
                // enabled or not. But here we rely on the default value of -1.
                let val = gen_sum!(GeneratorType::Velocity);
                if val > 0.0 {
                    self.vel = val as u8;
                }
            }

            GeneratorType::ModEnvToPitch => {
                self.modenv_to_pitch = gen_sum!(GeneratorType::ModEnvToPitch);

                self.modenv_to_pitch = self.modenv_to_pitch.clamp(-12000.0, 12000.0);
            }

            GeneratorType::ModEnvToFilterFc => {
                self.modenv_to_fc = gen_sum!(GeneratorType::ModEnvToFilterFc);

                // Range: SF2.01 section 8.1.3 # 1
                // Motivation for range checking:
                // Filter is reported to make funny noises now and then
                self.modenv_to_fc = self.modenv_to_fc.clamp(-12000.0, 12000.0);
            }

            // sample start and ends points
            //
            // Range checking is initiated via the
            // voice->check_sample_sanity flag,
            // because it is impossible to check here:
            // During the voice setup, all modulators are processed, while
            // the voice is inactive. Therefore, illegal settings may
            // occur during the setup (for example: First move the loop
            // end point ahead of the loop start point => invalid, then
            // move the loop start point forward => valid again.
            GeneratorType::StartAddrOfs | GeneratorType::StartAddrCoarseOfs => {
                self.start = self.sample.start();
                self.start += gen_sum!(GeneratorType::StartAddrOfs) as u32;
                self.start += 32768 * gen_sum!(GeneratorType::StartAddrCoarseOfs) as u32;

                self.check_sample_sanity_flag = SampleSanity::CHECK;
            }

            GeneratorType::EndAddrOfs | GeneratorType::EndAddrCoarseOfs => {
                self.end = self.sample.end();
                self.end += gen_sum!(GeneratorType::EndAddrCoarseOfs) as u32;
                self.end += 32768 * gen_sum!(GeneratorType::EndAddrCoarseOfs) as u32;

                self.check_sample_sanity_flag = SampleSanity::CHECK;
            }

            GeneratorType::StartLoopAddrOfs | GeneratorType::StartLoopAddrCoarseOfs => {
                self.loopstart = self.sample.loop_start();
                self.loopstart += gen_sum!(GeneratorType::StartLoopAddrOfs) as u32;
                self.loopstart += 32768 * gen_sum!(GeneratorType::StartLoopAddrCoarseOfs) as u32;

                self.check_sample_sanity_flag = SampleSanity::CHECK;
            }

            GeneratorType::EndLoopAddrOfs | GeneratorType::EndLoopAddrCoarseOfs => {
                self.loopend = self.sample.loop_end();
                self.loopend += gen_sum!(GeneratorType::EndLoopAddrOfs) as u32;
                self.loopend += 32768 * gen_sum!(GeneratorType::EndLoopAddrCoarseOfs) as u32;

                self.check_sample_sanity_flag = SampleSanity::CHECK;
            }

            // volume envelope
            //
            // - delay and hold times are converted to absolute number of samples
            // - sustain is converted to its absolute value
            // - attack, decay and release are converted to their increment per sample
            GeneratorType::VolEnvDelay => {
                let val = gen_sum!(GeneratorType::VolEnvDelay);

                let val = val.clamp(-12000.0, 5000.0);

                let count = (self.output_rate * tc2sec_delay(val) / BUFSIZE_F32) as u32;

                self.volenv_data[EnvelopeStep::Delay] = EnvelopePortion {
                    count,
                    coeff: 0.0,
                    incr: 0.0,
                    min: -1.0,
                    max: 1.0,
                };
            }

            GeneratorType::VolEnvAttack => {
                let val = gen_sum!(GeneratorType::VolEnvAttack);

                let val = val.clamp(-12000.0, 8000.0);

                let count =
                    1u32.wrapping_add((self.output_rate * tc2sec_attack(val) / BUFSIZE_F32) as u32);

                self.volenv_data[EnvelopeStep::Attack] = EnvelopePortion {
                    count,
                    coeff: 1.0,
                    incr: if count != 0 { 1.0 / count as f32 } else { 0.0 },
                    min: -1.0,
                    max: 1.0,
                };
            }

            GeneratorType::VolEnvHold | GeneratorType::KeyToVolEnvHold => {
                let count = self.calculate_hold_decay_buffers(
                    GeneratorType::VolEnvHold,
                    GeneratorType::KeyToVolEnvHold,
                    0,
                ) as u32;

                self.volenv_data[EnvelopeStep::Hold] = EnvelopePortion {
                    count,
                    coeff: 1.0,
                    incr: 0.0,
                    min: -1.0,
                    max: 2.0,
                };
            }

            GeneratorType::VolEnvDecay
            | GeneratorType::VolEnvSustain
            | GeneratorType::KeyToVolEnvDecay => {
                let y = 1.0 - 0.001 * gen_sum!(GeneratorType::VolEnvSustain);

                let y = y.clamp(0.0, 1.0);

                let count = self.calculate_hold_decay_buffers(
                    GeneratorType::VolEnvDecay,
                    GeneratorType::KeyToVolEnvDecay,
                    1,
                ) as u32;

                self.volenv_data[EnvelopeStep::Decay] = EnvelopePortion {
                    count,
                    coeff: 1.0,
                    incr: if count != 0 { -1.0 / count as f32 } else { 0.0 },
                    min: y,
                    max: 2.0,
                };
            }

            GeneratorType::VolEnvRelease => {
                let val = gen_sum!(GeneratorType::VolEnvRelease);

                let val = val.clamp(-7200.0, 8000.0);

                let count = 1u32
                    .wrapping_add((self.output_rate * tc2sec_release(val) / BUFSIZE_F32) as u32);

                self.volenv_data[EnvelopeStep::Release] = EnvelopePortion {
                    count,
                    coeff: 1.0,
                    incr: if count != 0 { -1.0 / count as f32 } else { 0.0 },
                    min: 0.0,
                    max: 1.0,
                };
            }

            GeneratorType::ModEnvDelay => {
                let val = gen_sum!(GeneratorType::ModEnvDelay);

                let val = val.clamp(-12000.0, 5000.0);

                self.modenv_data[EnvelopeStep::Delay] = EnvelopePortion {
                    count: (self.output_rate * tc2sec_delay(val) / BUFSIZE_F32) as u32,
                    coeff: 0.0,
                    incr: 0.0,
                    min: -1.0,
                    max: 1.0,
                };
            }

            GeneratorType::ModEnvAttack => {
                let val = gen_sum!(GeneratorType::ModEnvAttack);

                let val = val.clamp(-12000.0, 8000.0);

                let count =
                    1u32.wrapping_add((self.output_rate * tc2sec_attack(val) / BUFSIZE_F32) as u32);

                self.modenv_data[EnvelopeStep::Attack] = EnvelopePortion {
                    count,
                    coeff: 1.0,
                    incr: if count != 0 { 1.0 / count as f32 } else { 0.0 },
                    min: -1.0,
                    max: 1.0,
                };
            }

            GeneratorType::ModEnvHold | GeneratorType::KeyToModEnvHold => {
                let count = self.calculate_hold_decay_buffers(
                    GeneratorType::ModEnvHold,
                    GeneratorType::KeyToModEnvHold,
                    0,
                ) as u32;
                self.modenv_data[EnvelopeStep::Hold] = EnvelopePortion {
                    count,
                    coeff: 1.0,
                    incr: 0.0,
                    min: -1.0,
                    max: 2.0,
                };
            }

            GeneratorType::ModEnvDecay
            | GeneratorType::ModEnvSustain
            | GeneratorType::KeyToModEnvDecay => {
                let count = self.calculate_hold_decay_buffers(
                    GeneratorType::ModEnvDecay,
                    GeneratorType::KeyToModEnvDecay,
                    1,
                ) as u32;

                let y = 1.0 - 0.001 * gen_sum!(GeneratorType::ModEnvSustain);

                let y = y.clamp(0.0, 1.0);

                self.modenv_data[EnvelopeStep::Decay] = EnvelopePortion {
                    count,
                    coeff: 1.0,
                    incr: if count != 0 { -1.0 / count as f32 } else { 0.0 },
                    min: y,
                    max: 2.0,
                };
            }

            GeneratorType::ModEnvRelease => {
                let val = gen_sum!(GeneratorType::ModEnvRelease);

                let val = val.clamp(-12000.0, 8000.0);

                let count = 1u32
                    .wrapping_add((self.output_rate * tc2sec_release(val) / BUFSIZE_F32) as u32);

                self.modenv_data[EnvelopeStep::Release] = EnvelopePortion {
                    count,
                    coeff: 1.0,
                    incr: if count != 0 { -1.0 / count as f32 } else { 0.0 },
                    min: 0.0,
                    max: 2.0,
                };
            }
            _ => {}
        }
    }
}

impl Voice {
    #[inline(always)]
    pub(crate) fn key(&self) -> u8 {
        self.key
    }

    #[inline(always)]
    pub(crate) fn vel(&self) -> u8 {
        self.vel
    }

    #[inline(always)]
    pub(super) fn start_time(&self) -> usize {
        self.start_time
    }

    #[inline(always)]
    pub(super) fn ticks(&self) -> usize {
        self.ticks
    }

    #[inline(always)]
    pub(super) fn volenv_section(&self) -> EnvelopeStep {
        self.volenv_section
    }

    #[inline(always)]
    pub(super) fn volenv_val(&self) -> f32 {
        self.volenv_val
    }

    #[inline(always)]
    pub(super) fn exclusive_class_sum(&self) -> f64 {
        let class = &self.gen[GeneratorType::ExclusiveClass];
        class.val + class.mod_0 + class.nrpn
    }

    pub(super) fn is_available(&self) -> bool {
        matches!(self.status, VoiceStatus::Clean | VoiceStatus::Off)
    }

    pub(super) fn is_on(&self) -> bool {
        self.status == VoiceStatus::On && self.volenv_section < EnvelopeStep::Release
    }

    pub(crate) fn is_playing(&self) -> bool {
        matches!(self.status, VoiceStatus::On | VoiceStatus::Sustained)
    }

    #[inline(always)]
    pub(super) fn is_sustained(&self) -> bool {
        self.status == VoiceStatus::Sustained
    }
}