1 /*
2 Copyright (c) 2003-2006 yuno
3 All rights reserved.
4 
5 Redistribution and use in source and binary forms, with or without
6 modification, are permitted provided that the following conditions are met:
7 1. Redistributions of source code must retain the above copyright notice,
8    this list of conditions and the following disclaimer.
9 2. Redistributions in binary form must reproduce the above copyright notice,
10    this list of conditions and the following disclaimer in the documentation
11    and/or other materials provided with the distribution.
12 3. Neither the name of copyright holders nor the names of its contributors
13    may be used to endorse or promote products derived from this software
14    without specific prior written permission.
15 
16 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS''
17 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE
20 FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23 CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27 
28 #include "system.h"
29 
30 #ifdef WANT_FMMIDI
31 
32 // MIDI software synthesizer.
33 #include "midisynth.h"
34 
35 #include <algorithm>
36 #include <cassert>
37 #include <cmath>
38 #include <cstring>
39 #include <utility>
40 
41 #ifdef __BORLANDC__
42 #include <fastmath.h>
43 namespace std{
44     using ::_fm_sin;
45     using ::_fm_cos;
46     using ::_fm_log10;
47 }
48 #endif
49 
50 #ifndef M_PI
51 #define M_PI 3.14159265358979323846
52 #endif
53 
54 namespace midisynth{
55     // Channel constructor.
channel(note_factory * factory_,int bank)56     channel::channel(note_factory* factory_, int bank):
57         factory(factory_), default_bank(bank)
58     {
59         notes.reserve(16);
60         reset_all_parameters();
61     }
62     // Channel destructor.
~channel()63     channel::~channel()
64     {
65         all_sound_off_immediately();
66     }
67     // Synthesizes sound notes.
synthesize(int_least32_t * out,std::size_t samples,float rate,int_least32_t master_volume,int master_balance)68     int channel::synthesize(int_least32_t* out, std::size_t samples, float rate, int_least32_t master_volume, int master_balance)
69     {
70         double volume = mute ? 0.0 : std::pow(static_cast<double>(master_volume) * this->volume * expression / (16383.0 * 16383.0 * 16383.0), 2) * 16383.0;
71         int num_notes = 0;
72         std::vector<NOTE>::iterator i = notes.begin();
73         while(i != notes.end()){
74             class note* note = i->note;
75             int_least32_t panpot = note->get_panpot();
76             if(this->panpot <= 8192){
77                 panpot = panpot * this->panpot / 8192;
78             }else{
79                 panpot = panpot * (16384 - this->panpot) / 8192 + (this->panpot - 8192) * 2;
80             }
81             if(master_balance <= 8192){
82                 panpot = panpot * master_balance / 8192;
83             }else{
84                 panpot = panpot * (16384 - master_balance) / 8192 + (master_balance - 8192) * 2;
85             }
86             int_least32_t left = static_cast<int_least32_t>(volume * std::cos(std::max(0, panpot - 1) * (M_PI / 2 / 16382)));
87             int_least32_t right = static_cast<int_least32_t>(volume * std::sin(std::max(0, panpot - 1) * (M_PI / 2 / 16382)));
88             bool ret = note->synthesize(out, samples, rate, left, right);
89             if(ret){
90                 ++i;
91             }else{
92                 i = notes.erase(i);
93                 delete note;
94             }
95             ++num_notes;
96         }
97         return num_notes;
98     }
99     // Returns all parameters to the initial state.
reset_all_parameters()100     void channel::reset_all_parameters()
101     {
102         program = default_bank * 128;
103         bank = default_bank;
104         panpot = 8192;
105         volume = 12800;
106         fine_tuning = 8192;
107         coarse_tuning = 8192;
108         tremolo_frequency = 3;
109         vibrato_frequency = 3;
110         master_frequency_multiplier = 1;
111         mono = false;
112         mute = false;
113         system_mode = system_mode_default;
114         reset_all_controller();
115     }
116     // Returns all controllers to the initial state.
reset_all_controller()117     void channel::reset_all_controller()
118     {
119         expression = 16383;
120         pressure = 0;
121         channel_pressure(0);
122         pitch_bend = 8192;
123         pitch_bend_sensitivity = 256;
124         frequency_multiplier = 0.0f;
125         update_frequency_multiplier();
126         modulation_depth = 0;
127         modulation_depth_range = 64;
128         update_modulation();
129         damper = 0;
130         set_damper(0);
131         set_sostenute(0);
132         freeze = 0;
133         set_freeze(0);
134         RPN = 0x3FFF;
135         NRPN = 0x3FFF;
136     }
137     // Turns off all notes.
all_note_off()138     void channel::all_note_off()
139     {
140         for(std::vector<NOTE>::iterator i = notes.begin(); i != notes.end(); ++i){
141             if(i->status == NOTE::NOTEON){
142                 i->status = NOTE::NOTEOFF;
143                 i->note->note_off(64);
144             }
145         }
146     }
147     // Turns off all sounds.
all_sound_off()148     void channel::all_sound_off()
149     {
150         for(std::vector<NOTE>::iterator i = notes.begin(); i != notes.end(); ++i){
151             if(i->status != NOTE::SOUNDOFF){
152                 i->status = NOTE::SOUNDOFF;
153                 i->note->sound_off();
154             }
155         }
156     }
157     // Mutes immediately.
all_sound_off_immediately()158     void channel::all_sound_off_immediately()
159     {
160         for(std::vector<NOTE>::iterator i = notes.begin(); i != notes.end(); ++i){
161             delete i->note;
162         }
163         notes.clear();
164     }
165     // Note on. Sound output.
note_on(int note,int velocity)166     void channel::note_on(int note, int velocity)
167     {
168         assert(note >= 0 && note < NUM_NOTES);
169         assert(velocity >= 0 && velocity <= 127);
170 
171         note_off(note, 64);
172         if(velocity){
173             if(mono){
174                 all_sound_off();
175             }
176             class note* p = factory->note_on(program, note, velocity, frequency_multiplier);
177             if(p){
178                 int assign = p->get_assign();
179                 if(assign){
180                     for(std::vector<NOTE>::iterator i = notes.begin(); i != notes.end(); ++i){
181                         if(i->note->get_assign() == assign){
182                             i->note->sound_off();
183                         }
184                     }
185                 }
186                 if(freeze){
187                     p->set_freeze(freeze);
188                 }
189                 if(damper){
190                     p->set_damper(damper);
191                 }
192                 if(modulation_depth){
193                     float depth = static_cast<double>(modulation_depth) * modulation_depth_range / (16383.0 * 128.0);
194                     p->set_vibrato(depth, vibrato_frequency);
195                 }
196                 if(pressure){
197                     p->set_tremolo(pressure, tremolo_frequency);
198                 }
199                 notes.push_back(NOTE(p, note));
200             }
201         }
202     }
203     // Note off. Sound gets into the release step.
note_off(int note,int velocity)204     void channel::note_off(int note, int velocity)
205     {
206         assert(note >= 0 && note < NUM_NOTES);
207         assert(velocity >= 0 && velocity <= 127);
208         for(std::vector<NOTE>::iterator i = notes.begin(); i != notes.end(); ++i){
209             if(i->key == note && i->status == NOTE::NOTEON){
210                 i->status = NOTE::NOTEOFF;
211                 i->note->note_off(velocity);
212             }
213         }
214     }
215     // Polyphonic key pressure.
polyphonic_key_pressure(int note,int value)216     void channel::polyphonic_key_pressure(int note, int value)
217     {
218         assert(note >= 0 && note < NUM_NOTES);
219         assert(value >= 0 && value <= 127);
220         for(std::vector<NOTE>::iterator i = notes.begin(); i != notes.end(); ++i){
221             if(i->key == note && i->status == NOTE::NOTEON){
222                 i->note->set_tremolo(value, tremolo_frequency);
223             }
224         }
225     }
226     // Channel Pressure.
channel_pressure(int value)227     void channel::channel_pressure(int value)
228     {
229         assert(value >= 0 && value <= 127);
230         if(pressure != value){
231             pressure = value;
232             for(std::vector<NOTE>::iterator i = notes.begin(); i != notes.end(); ++i){
233                 if(i->status == NOTE::NOTEON){
234                     i->note->set_tremolo(value, tremolo_frequency);
235                 }
236             }
237         }
238     }
239     // Control Change.
control_change(int control,int value)240     void channel::control_change(int control, int value)
241     {
242         assert(value >= 0 && value <= 0x7F);
243         switch(control){
244         case 0x00:
245             bank_select((bank & 0x7F) | (value << 7));
246             break;
247         case 0x01:
248             set_modulation_depth((modulation_depth & 0x7F) | (value << 7));
249             break;
250         case 0x06:
251             set_registered_parameter((get_registered_parameter() & 0x7F) | (value << 7));
252             break;
253         case 0x07:
254             volume = (volume & 0x7F) | (value << 7);
255             break;
256         case 0x0A:
257             panpot = (panpot & 0x7F) | (value << 7);
258             break;
259         case 0x0B:
260             expression = (expression & 0x7F) | (value << 7);
261             break;
262         case 0x20:
263             bank_select((bank & 0x7F) | (value << 7));
264             break;
265         case 0x21:
266             set_modulation_depth((modulation_depth & ~0x7F) | value);
267             break;
268         case 0x26:
269             set_registered_parameter((get_registered_parameter() & ~0x7F) | value);
270             break;
271         case 0x27:
272             volume = (volume & ~0x7F) | value;
273             break;
274         case 0x2A:
275             panpot = (panpot & ~0x7F) | value;
276             break;
277         case 0x2B:
278             expression = (expression & ~0x7F) | value;
279             break;
280         case 0x40:
281             set_damper(value);
282             break;
283         case 0x42:
284             set_sostenute(value);
285             break;
286         case 0x45:
287             set_freeze(value);
288             break;
289         case 0x60:
290             set_registered_parameter(std::min(0x3FFF, get_registered_parameter() + 1));
291             break;
292         case 0x61:
293             set_registered_parameter(std::max(0, get_registered_parameter() - 1));
294             break;
295         case 0x62:
296             set_NRPN((NRPN & ~0x7F) | value);
297             break;
298         case 0x63:
299             set_NRPN((NRPN & 0x7F) | (value << 7));
300             break;
301         case 0x64:
302             set_RPN((RPN & ~0x7F) | value);
303             break;
304         case 0x65:
305             set_RPN((RPN & 0x7F) | (value << 7));
306             break;
307         case 0x78:
308             all_sound_off();
309             break;
310         case 0x79:
311             reset_all_controller();
312             break;
313         case 0x7B:
314         case 0x7C:
315         case 0x7D:
316             all_note_off();
317             break;
318         case 0x7E:
319             mono_mode_on();
320             break;
321         case 0x7F:
322             poly_mode_on();
323             break;
324         }
325     }
326     // Bank select.
bank_select(int value)327     void channel::bank_select(int value)
328     {
329         switch(system_mode){
330         case system_mode_gm:
331             break;
332         case system_mode_gs:
333             if(((bank & 0x3F80) == 0x3C00) == ((value & 0x3F80) == 0x3C00)){
334                 set_bank(value);
335             }
336             break;
337         case system_mode_xg:
338             if(default_bank == 0x3C00){
339                 set_bank(0x3C00 | (value & 0x7F));
340             }else if((value & 0x3F80) == 0x3F80){
341                 set_bank(0x3C00 | (value & 0x7F));
342             }else{
343                 set_bank(value);
344             }
345             break;
346         default:
347             if(default_bank == 0x3C00){
348                 set_bank(0x3C00 | (value & 0x7F));
349             }else{
350                 set_bank(value);
351             }
352             break;
353         }
354     }
355     // Damper effect.
set_damper(int value)356     void channel::set_damper(int value)
357     {
358         if(damper != value){
359             damper = value;
360             for(std::vector<NOTE>::iterator i = notes.begin(); i != notes.end(); ++i){
361                 i->note->set_damper(value);
362             }
363         }
364     }
365     // Sostenuto effect.
set_sostenute(int value)366     void channel::set_sostenute(int value)
367     {
368         sostenute = value;
369         for(std::vector<NOTE>::iterator i = notes.begin(); i != notes.end(); ++i){
370             i->note->set_sostenute(value);
371         }
372     }
373     // Freeze effect.
set_freeze(int value)374     void channel::set_freeze(int value)
375     {
376         if(freeze != value){
377             freeze = value;
378             for(std::vector<NOTE>::iterator i = notes.begin(); i != notes.end(); ++i){
379                 i->note->set_freeze(value);
380             }
381         }
382     }
383     // Gets RPN.
get_registered_parameter()384     int channel::get_registered_parameter()
385     {
386         switch(RPN){
387         case 0x0000:
388             return pitch_bend_sensitivity;
389         case 0x0001:
390             return fine_tuning;
391         case 0x0002:
392             return coarse_tuning;
393         case 0x0005:
394             return modulation_depth_range;
395         default:
396             return 0;
397         }
398     }
399     // Sets RPN.
set_registered_parameter(int value)400     void channel::set_registered_parameter(int value)
401     {
402         switch(RPN){
403         case 0x0000:
404             set_pitch_bend_sensitivity(value);
405             break;
406         case 0x0001:
407             set_fine_tuning(value);
408             break;
409         case 0x0002:
410             set_coarse_tuning(value);
411             break;
412         case 0x0005:
413             set_modulation_depth_range(value);
414             break;
415         default:
416             break;
417         }
418     }
419     // Recalculates and updates the frequency multiplier.
update_frequency_multiplier()420     void channel::update_frequency_multiplier()
421     {
422         float value = master_frequency_multiplier
423                     * std::pow(2, (coarse_tuning - 8192) / (128.0 * 100.0 * 12.0)
424                                 + (fine_tuning - 8192) / (8192.0 * 100.0 * 12.0)
425                                 + static_cast<double>(pitch_bend - 8192) * pitch_bend_sensitivity / (8192.0 * 128.0 * 12.0));
426         if(frequency_multiplier != value){
427             frequency_multiplier = value;
428             for(std::vector<NOTE>::iterator i = notes.begin(); i != notes.end(); ++i){
429                 i->note->set_frequency_multiplier(value);
430             }
431         }
432     }
433     // Updates the modulation depth effect.
update_modulation()434     void channel::update_modulation()
435     {
436         float depth = static_cast<double>(modulation_depth) * modulation_depth_range / (16383.0 * 128.0);
437         for(std::vector<NOTE>::iterator i = notes.begin(); i != notes.end(); ++i){
438             i->note->set_vibrato(depth, vibrato_frequency);
439         }
440     }
441 
442     // Synthesizer constructor.
synthesizer(note_factory * factory)443     synthesizer::synthesizer(note_factory* factory)
444     {
445         for(int i = 0; i < 16; ++i){
446             channels[i].reset(new channel(factory, i == 9 ? 0x3C00 : 0x3C80));
447         }
448         reset_all_parameters();
449     }
450     // Gets channel.
get_channel(int ch)451     channel* synthesizer::get_channel(int ch)
452     {
453         assert(ch >= 0 && ch < NUM_CHANNELS);
454         return channels[ch].get();
455     }
456     // Sound synthesis. Returns the number of notes.
synthesize(int_least16_t * output,std::size_t samples,float rate)457     int synthesizer::synthesize(int_least16_t* output, std::size_t samples, float rate)
458     {
459         std::size_t n = samples * 2;
460         std::vector<int_least32_t> buf(n);
461         int num_notes = synthesize_mixing(&buf[0], samples, rate);
462         if(num_notes){
463             for(std::size_t i = 0; i < n; ++i){
464                 int_least32_t x = buf[i];
465                 if(x < -32767){
466                     output[i] = -32767;
467                 }else if(x > 32767){
468                     output[i] = 32767;
469                 }else{
470                     output[i] = static_cast<int_least16_t>(x);
471                 }
472             }
473         }else{
474             std::memset(output, 0, sizeof(int_least16_t) * n);
475         }
476         return num_notes;
477     }
synthesize_mixing(int_least32_t * output,std::size_t samples,float rate)478     int synthesizer::synthesize_mixing(int_least32_t* output, std::size_t samples, float rate)
479     {
480         if(active_sensing == 0){
481             all_sound_off();
482             active_sensing = -1;
483         }else if(active_sensing > 0){
484             active_sensing = std::max(0.0f, active_sensing - samples / rate);
485         }
486         int_least32_t volume = static_cast<int_least32_t>(main_volume) * master_volume / 16384;
487         int num_notes = 0;
488         for(int i = 0; i < NUM_CHANNELS; ++i){
489             num_notes += channels[i]->synthesize(output, samples, rate, volume, master_balance);
490         }
491         return num_notes;
492     }
493     // Resets the synthesizer completely.
reset()494     void synthesizer::reset()
495     {
496         all_sound_off_immediately();
497         reset_all_parameters();
498     }
499     // Returns all parameters to the initial state.
reset_all_parameters()500     void synthesizer::reset_all_parameters()
501     {
502         active_sensing = -1;
503         main_volume = 8192;
504         master_volume = 16383;
505         master_balance = 8192;
506         master_fine_tuning = 8192;
507         master_coarse_tuning = 8192;
508         master_frequency_multiplier = 1;
509         system_mode = system_mode_default;
510         for(int i = 0; i < NUM_CHANNELS; ++i){
511             channels[i]->reset_all_parameters();
512         }
513     }
514     // Returns all controllers to the initial state.
reset_all_controller()515     void synthesizer::reset_all_controller()
516     {
517         for(int i = 0; i < NUM_CHANNELS; ++i){
518             channels[i]->reset_all_controller();
519         }
520     }
521     // All notes off. Turns off all notes.
all_note_off()522     void synthesizer::all_note_off()
523     {
524         for(int i = 0; i < NUM_CHANNELS; ++i){
525             channels[i]->all_note_off();
526         }
527     }
528     // All sounds off. Turns off all sounds.
all_sound_off()529     void synthesizer::all_sound_off()
530     {
531         for(int i = 0; i < NUM_CHANNELS; ++i){
532             channels[i]->all_sound_off();
533         }
534     }
535     // Instant silence.
all_sound_off_immediately()536     void synthesizer::all_sound_off_immediately()
537     {
538         for(int i = 0; i < NUM_CHANNELS; ++i){
539             channels[i]->all_sound_off_immediately();
540         }
541     }
542     // Sets and execututes system exclusive messages.
sysex_message(const void * pvdata,std::size_t size)543     void synthesizer::sysex_message(const void* pvdata, std::size_t size)
544     {
545         const unsigned char* data = reinterpret_cast<const unsigned char*>(pvdata);
546         if(size == 6 && std::memcmp(data, "\xF0\x7E\x7F\x09\x01\xF7", 6) == 0){
547             /* GM system on */
548             set_system_mode(system_mode_gm);
549         }else if(size == 6 && std::memcmp(data, "\xF0\x7E\x7F\x09\x02\xF7", 6) == 0){
550             /* GM system off */
551             set_system_mode(system_mode_gm2);
552         }else if(size == 6 && std::memcmp(data, "\xF0\x7E\x7F\x09\x03\xF7", 6) == 0){
553             /* GM2 system on */
554             set_system_mode(system_mode_gm2);
555         }else if(size == 11 && std::memcmp(data, "\xF0\x41", 2) == 0 && std::memcmp(data + 3, "\x42\x12\x40\x00\x7F\x00\x41\xF7", 8) == 0){
556             /* GS reset */
557             set_system_mode(system_mode_gs);
558         }else if(size == 9 && std::memcmp(data, "\xF0\x43", 2) == 0 && (data[2] & 0xF0) == 0x10 && std::memcmp(data + 3, "\x4C\x00\x00\x7E\x00\xF7", 6) == 0){
559             /* XG system on */
560             set_system_mode(system_mode_xg);
561         }else if(size == 8 && std::memcmp(data, "\xF0\x7F\x7F\x04\x01", 5) == 0 && data[7] == 0xF7){
562             /* master volume */
563             set_master_volume((data[5] & 0x7F) | ((data[6] & 0x7F) << 7));
564         }else if(size == 8 && std::memcmp(data, "\xF0\x7F\x7F\x04\x02", 5) == 0 && data[7] == 0xF7){
565             /* master balance */
566             set_master_balance((data[5] & 0x7F) | ((data[6] & 0x7F) << 7));
567         }else if(size == 8 && std::memcmp(data, "\xF0\x7F\x7F\x04\x03", 5) == 0 && data[7] == 0xF7){
568             /* master fine tuning */
569             set_master_fine_tuning((data[5] & 0x7F) | ((data[6] & 0x7F) << 7));
570         }else if(size == 8 && std::memcmp(data, "\xF0\x7F\x7F\x04\x04", 5) == 0 && data[7] == 0xF7){
571             /* master coarse tuning */
572             set_master_coarse_tuning((data[5] & 0x7F) | ((data[6] & 0x7F) << 7));
573         }else if(size == 11 && std::memcmp(data, "\xF0\x41", 2) == 0 && (data[2] & 0xF0) == 0x10 && std::memcmp(data + 3, "\x42\x12\x40", 3) == 0 && (data[6] & 0xF0) == 0x10 && data[7] == 0x15 && data[10] == 0xF7){
574             /* use for rhythm part */
575             int channel = data[6] & 0x0F;
576             int map = data[8];
577             if(map == 0){
578                 channels[channel]->set_bank(0x3C80);
579             }else{
580                 channels[channel]->set_bank(0x3C00);
581             }
582             channels[channel]->program_change(0);
583         }
584     }
585     // Sets and executes MIDI events.
midi_event(int event,int param1,int param2)586     void synthesizer::midi_event(int event, int param1, int param2)
587     {
588         if(event == 0xFE)
589             active_sensing = 0.33f;
590         else if (event == 0xFF) {
591             all_sound_off();
592             reset_all_parameters();
593         }else{
594             switch(event & 0xF0){
595             case 0x80:
596                 note_off(event & 0x0F, param1 & 0x7F, param2 & 0x7F);
597                 break;
598             case 0x90:
599                 note_on(event & 0x0F, param1 & 0x7F, param2 & 0x7F);
600                 break;
601             case 0xA0:
602                 polyphonic_key_pressure(event & 0x0F, param1 & 0x7F, param2 & 0x7F);
603                 break;
604             case 0xB0:
605                 control_change(event & 0x0F, param1 & 0x7F, param2 & 0x7F);
606                 break;
607             case 0xC0:
608                 program_change(event & 0x0F, param1 & 0x7F);
609                 break;
610             case 0xD0:
611                 channel_pressure(event & 0x0F, param1 & 0x7F);
612                 break;
613             case 0xE0:
614                 pitch_bend_change(event & 0x0F, ((param2 & 0x7F) << 7) | (param1 & 0x7F));
615                 break;
616             default:
617                 break;
618             }
619         }
620     }
621     // Changes the system mode.
set_system_mode(system_mode_t mode)622     void synthesizer::set_system_mode(system_mode_t mode)
623     {
624         all_sound_off();
625         reset_all_parameters();
626         system_mode = mode;
627         for(int i = 0; i < NUM_CHANNELS; ++i){
628             channels[i]->set_system_mode(mode);
629         }
630     }
631     // Recalculates and updates the master frequency multiploer (tuning).
update_master_frequency_multiplier()632     void synthesizer::update_master_frequency_multiplier()
633     {
634         float value = std::pow(2, (master_coarse_tuning - 8192) / (128.0 * 100.0 * 12.0)
635                                 + (master_fine_tuning - 8192) / (8192.0 * 100.0 * 12.0));
636         if(master_frequency_multiplier != value){
637             master_frequency_multiplier = value;
638             for(int i = 0; i < NUM_CHANNELS; ++i){
639                 channels[i]->set_master_frequency_multiplier(value);
640             }
641         }
642     }
643 
644     // Sine table. For sine wave generators.
645     namespace{
646         class sine_table{
647         public:
648             enum{ DIVISION = 4096 };
649             sine_table();
get(int n) const650             int_least16_t get(int n)const{ return data[n]; }
651         private:
652             int_least16_t data[DIVISION];
653         }sine_table;
654 
sine_table()655         sine_table::sine_table()
656         {
657             for(int i = 0; i < DIVISION; ++i){
658                 data[i] = static_cast<int_least16_t>(32767 * std::sin(i * 2 * M_PI / DIVISION));
659             }
660         }
661     }
662     // Sine table. Sine wave generator.
sine_wave_generator()663     inline sine_wave_generator::sine_wave_generator():
664         position(0), step(0)
665     {
666     }
sine_wave_generator(float cycle)667     inline sine_wave_generator::sine_wave_generator(float cycle):
668         position(0)
669     {
670         set_cycle(cycle);
671     }
672     // changes the period of the sine wave.
set_cycle(float cycle)673     void sine_wave_generator::set_cycle(float cycle)
674     {
675         if(cycle){
676             step = static_cast<uint_least32_t>(sine_table::DIVISION * 32768.0 / cycle);
677         }else{
678             step = 0;
679         }
680     }
681     // Adds modulation.
add_modulation(int_least32_t x)682     void sine_wave_generator::add_modulation(int_least32_t x)
683     {
684         position += static_cast<int_least32_t>(static_cast<int_least64_t>(step) * x >> 16);
685     }
686     // Gets the next sample.
get_next()687     inline int sine_wave_generator::get_next()
688     {
689         return sine_table.get((position += step) / 32768 % sine_table::DIVISION);
690     }
691     // Gets the next sample (with frequency modulation).
get_next(int_least32_t modulation)692     inline int sine_wave_generator::get_next(int_least32_t modulation)
693     {
694         uint_least32_t m = modulation * sine_table::DIVISION / 65536;
695         uint_least32_t p = ((position += step) / 32768 + m) % sine_table::DIVISION;
696         return sine_table.get(p);
697     }
698 
699     // Logarithmic conversion table. Use in the subsequent decay of the envelope generator.
700     namespace{
701         #define LOG10_32767 4.5154366811416989472479934140484
702         #define LOGTABLE_SIZE 4096
703         #define LOGTABLE_FACTOR (LOGTABLE_SIZE / LOG10_32767)
704         class log_table{
705         public:
706             log_table();
get(int x) const707             uint_least16_t get(int x)const{ return x >= LOGTABLE_SIZE ? data[LOGTABLE_SIZE - 1] : data[x]; }
708         private:
709             uint_least16_t data[LOGTABLE_SIZE];
710         }log_table;
log_table()711         log_table::log_table()
712         {
713             for(int i = 0; i < LOGTABLE_SIZE; ++i){
714                 data[i] = static_cast<uint_least16_t>(std::pow(10, static_cast<double>(i) / LOGTABLE_FACTOR));
715             }
716         }
717     }
718 
719     // Envelope table. Calculates and processes AR, DR, SR and RR rates.
720     namespace{
721         struct envelope_table{
722             envelope_table();
723             uint_least32_t TL[128];
724             uint_least32_t SL[16][128];
725             double AR[64][128];
726             double RR[64][128];
727         }const envelope_table;
728 
envelope_table()729         envelope_table::envelope_table()
730         {
731             for(int t = 0; t < 128; ++t){
732                 double fTL = 32767 * std::pow(10, t * -0.75 / 10);
733                 TL[t] = static_cast<uint_least32_t>(fTL);
734                 if(TL[t] == 0){
735                     TL[t] = 1;
736                 }
737                 for(int s = 0; s < 16; ++s){
738                     double x = fTL * std::pow(10, s * -3.0 / 10);
739                     if(x <= 1){
740                         SL[s][t] = 0;
741                     }else{
742                         SL[s][t] = static_cast<uint_least32_t>(65536 * LOGTABLE_FACTOR * std::log10(x));
743                     }
744                 }
745             }
746             for(int x = 0; x < 64; ++x){
747                 double attack_time = 15.3262 * std::pow(10, x * -0.75 / 10);
748                 double release_time = 211.84 * std::pow(10, x * -0.75 / 10);
749                 for(int t = 0; t < 128; ++t){
750                     AR[x][t] = TL[t] / attack_time;
751                     RR[x][t] = 65536 * LOGTABLE_FACTOR * 48.0 / 10 * TL[t] / 32767 / release_time;
752                 }
753             }
754         }
755     }
756 
757     // Envelope generator constructor.
envelope_generator(int AR_,int DR_,int SR_,int RR_,int SL,int TL_)758     envelope_generator::envelope_generator(int AR_, int DR_, int SR_, int RR_, int SL, int TL_):
759         state(ATTACK), AR(AR_), DR(DR_), SR(SR_), RR(RR_), TL(TL_),
760         current(0), rate(1), hold(0), freeze(0)
761     {
762         if(AR >= 63) AR = 63;
763         if(DR >= 63) DR = 63;
764         if(SR >= 63) SR = 63;
765         if(RR >= 63) RR = 63;
766         assert(AR >= 0);
767         assert(DR >= 0);
768         assert(SR >= 0);
769         assert(RR >= 0);
770         assert(SL >= 0 && SL <= 15);
771         assert(TL >= 0 && TL <= 127);
772 
773         fTL = envelope_table.TL[TL];
774         fSS = fSL = envelope_table.SL[SL][TL];
775         fAR = 0;
776         fDR = 0;
777         fSR = 0;
778         fRR = 0;
779         fOR = 0;
780         fDRR = 0;
781         fDSS = 0;
782     }
783     // Set the playback rate.
set_rate(float rate)784     inline void envelope_generator::set_rate(float rate)
785     {
786         this->rate = rate ? rate : 1;
787         update_parameters();
788     }
789     // Sets the hold (damper and sostenuto).
set_hold(float hold)790     void envelope_generator::set_hold(float hold)
791     {
792         if(this->hold > hold || state <= SASTAIN || current >= fSL){
793             this->hold = hold;
794             update_parameters();
795         }
796     }
797     // Sets the freeze.
set_freeze(float freeze)798     void envelope_generator::set_freeze(float freeze)
799     {
800         if(this->freeze > freeze || state <= SASTAIN || current >= fSL){
801             this->freeze = freeze;
802             update_parameters();
803         }
804     }
805     // Updates ADSR parameters.
update_parameters()806     void envelope_generator::update_parameters()
807     {
808         double fAR = envelope_table.AR[AR][TL] / rate;
809         double fDR = envelope_table.RR[DR][TL] / rate;
810         double fSR = envelope_table.RR[SR][TL] / rate;
811         double fRR = envelope_table.RR[RR][TL] / rate;
812 
813         if(fRR < 1){
814             fRR = 1;
815         }
816         if(hold > 0){
817             fRR = fSR * hold + fRR * (1 - hold);
818         }
819         if(freeze > 0){
820             fDR *= (1 - freeze);
821             fSR *= (1 - freeze);
822             fRR *= (1 - freeze);
823         }
824         if(fAR < 1){
825             fAR = 1;
826         }
827         this->fAR = static_cast<uint_least32_t>(fAR);
828         this->fDR = static_cast<uint_least32_t>(fDR);
829         this->fSR = static_cast<uint_least32_t>(fSR);
830         this->fRR = static_cast<uint_least32_t>(fRR);
831         this->fOR = static_cast<uint_least32_t>(envelope_table.RR[63][0] / rate);
832         this->fSS = std::max(this->fDR, fSL);
833         this->fDRR = std::max(this->fDR, this->fRR);
834         this->fDSS = std::max(this->fDRR, this->fSS);
835     }
836     // Key-off. Gets into release step.
key_off()837     void envelope_generator::key_off()
838     {
839         switch(state){
840         case ATTACK:
841             state = ATTACK_RELEASE;
842             break;
843         case DECAY:
844             state = DECAY_RELEASE;
845             break;
846         case SASTAIN:
847             state = RELEASE;
848             break;
849         default:
850             break;
851         }
852     }
853     // Sound off. Enters rapidly in mute mode.
sound_off()854     void envelope_generator::sound_off()
855     {
856         switch(state){
857         case ATTACK:
858         case ATTACK_RELEASE:
859             if(current){
860                 current = static_cast<uint_least32_t>(65536 * LOGTABLE_FACTOR * std::log10(static_cast<double>(current)));
861             }
862             break;
863         default:
864             break;
865         }
866         state = SOUNDOFF;
867     }
868     // Level moving from release to sound off.
869     // Because releasing a long note forever is a CPU power waste it must be cut where appropiate.
870     // Attenuation is a logarithm, so infinite time is needed for the volume to become true in a zero.
871     // In fact it gets muted when lesser than 1 as it is rounded to an integer actually.
872     // A higher value may sound not natural but improves performance
873     #define SOUNDOFF_LEVEL 1024
874     // Gets the next sample.
get_next()875     int envelope_generator::get_next()
876     {
877         uint_least32_t current = this->current;
878         switch(state){
879         case ATTACK:
880             if(current < fTL){
881                 return this->current = current + fAR;
882             }
883             this->current = static_cast<uint_least32_t>(65536 * LOGTABLE_FACTOR * std::log10(static_cast<double>(fTL)));
884             state = DECAY;
885             return fTL;
886         case DECAY:
887             if(current > fSS){
888                 this->current = current -= fDR;
889                 return log_table.get(current / 65536);
890             }
891             this->current = current = fSL;
892             state = SASTAIN;
893             return log_table.get(current / 65536);
894         case SASTAIN:
895             if(current > fSR){
896                 this->current = current -= fSR;
897                 int n = log_table.get(current / 65536);
898                 if(n > 1){
899                     return n;
900                 }
901             }
902             state = FINISHED;
903             return 0;
904         case ATTACK_RELEASE:
905             if(current < fTL){
906                 return this->current = current + fAR;
907             }
908             this->current = static_cast<uint_least32_t>(65536 * LOGTABLE_FACTOR * std::log10(static_cast<double>(fTL)));
909             state = DECAY_RELEASE;
910             return fTL;
911         case DECAY_RELEASE:
912             if(current > fDSS){
913                 this->current = current -= fDRR;
914                 return log_table.get(current / 65536);
915             }
916             this->current = current = fSL;
917             state = RELEASE;
918             return log_table.get(current / 65536);
919         case RELEASE:
920             if(current > fRR){
921                 this->current = current -= fRR;
922                 int n = log_table.get(current / 65536);
923                 if(n > SOUNDOFF_LEVEL){
924                     return n;
925                 }
926                 state = SOUNDOFF;
927                 return n;
928             }
929             state = FINISHED;
930             return 0;
931         case SOUNDOFF:
932             if(current > fOR){
933                 this->current = current -= fOR;
934                 int n = log_table.get(current / 65536);
935                 if(n > 1){
936                     return n;
937                 }
938             }
939             state = FINISHED;
940             return 0;
941         default:
942             return 0;
943         }
944     }
945 
946     namespace{
947         // Key scaling table
948         const int keyscale_table[4][128] = {
949             {
950                  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
951                  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
952                  0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
953                  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2,
954                  2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
955                  2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
956                  3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
957                  3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3
958             }, {
959                  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
960                  0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1,
961                  1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
962                  3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4,
963                  4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
964                  5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
965                  7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
966                  7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7
967             }, {
968                  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
969                  0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2,
970                  2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5,
971                  6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8,
972                  8, 8, 8, 8, 8, 9, 9, 9,10,10,10,10,10,10,10,10,
973                 10,11,11,11,12,12,12,12,12,12,12,12,12,13,13,13,
974                 14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,
975                 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15
976             }, {
977                  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
978                  0, 0, 0, 1, 1, 2, 2, 3, 4, 4, 4, 4, 4, 4, 4, 5,
979                  5, 6, 6, 7, 8, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
980                 12,12,12,12,12,12,12,13,13,14,14,15,16,16,16,16,
981                 16,16,16,17,17,18,18,19,20,20,20,20,20,20,20,21,
982                 21,22,22,23,24,24,24,24,24,24,24,25,25,26,26,27,
983                 28,28,28,28,28,28,28,29,29,30,30,31,31,31,31,31,
984                 31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31
985             }
986         };
987         // Detune table
988         const float detune_table[4][128] = {
989             { 0 },
990             {
991                 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000,
992                 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000,
993                 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000,
994                 0.053, 0.053, 0.053, 0.053, 0.053, 0.053, 0.053, 0.053,
995                 0.053, 0.053, 0.053, 0.053, 0.053, 0.053, 0.053, 0.053,
996                 0.053, 0.053, 0.053, 0.053, 0.053, 0.053, 0.053, 0.053,
997                 0.106, 0.106, 0.106, 0.106, 0.106, 0.106, 0.106, 0.106,
998                 0.106, 0.106, 0.106, 0.106, 0.106, 0.106, 0.106, 0.106,
999                 0.106, 0.106, 0.106, 0.159, 0.159, 0.159, 0.159, 0.159,
1000                 0.212, 0.212, 0.212, 0.212, 0.212, 0.212, 0.212, 0.212,
1001                 0.212, 0.212, 0.212, 0.264, 0.264, 0.264, 0.264, 0.264,
1002                 0.264, 0.264, 0.264, 0.317, 0.317, 0.317, 0.317, 0.370,
1003                 0.423, 0.423, 0.423, 0.423, 0.423, 0.423, 0.423, 0.423,
1004                 0.423, 0.423, 0.423, 0.423, 0.423, 0.423, 0.423, 0.423,
1005                 0.423, 0.423, 0.423, 0.423, 0.423, 0.423, 0.423, 0.423,
1006                 0.423, 0.423, 0.423, 0.423, 0.423, 0.423, 0.423, 0.423
1007             }, {
1008                 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000,
1009                 0.000, 0.000, 0.000, 0.000, 0.000, 0.053, 0.053, 0.053,
1010                 0.053, 0.053, 0.053, 0.053, 0.053, 0.053, 0.053, 0.053,
1011                 0.106, 0.106, 0.106, 0.106, 0.106, 0.106, 0.106, 0.106,
1012                 0.106, 0.106, 0.106, 0.106, 0.106, 0.106, 0.106, 0.106,
1013                 0.106, 0.106, 0.106, 0.106 ,0.106, 0.159, 0.159, 0.159,
1014                 0.212, 0.212, 0.212, 0.212, 0.212, 0.212, 0.212 ,0.212,
1015                 0.212, 0.212, 0.212, 0.264, 0.264, 0.264, 0.264, 0.264,
1016                 0.264, 0.264, 0.264, 0.317, 0.317, 0.317, 0.317, 0.370,
1017                 0.423, 0.423, 0.423, 0.423, 0.423, 0.423, 0.423, 0.423,
1018                 0.423, 0.476, 0.476, 0.529, 0.582, 0.582, 0.582, 0.582,
1019                 0.582, 0.582 ,0.582, 0.635, 0.635, 0.688, 0.688, 0.741,
1020                 0.846, 0.846, 0.846, 0.846, 0.846, 0.846, 0.846 ,0.846,
1021                 0.846, 0.846, 0.846, 0.846, 0.846, 0.846, 0.846, 0.846,
1022                 0.846, 0.846, 0.846, 0.846, 0.846, 0.846, 0.846, 0.846
1023             }, {
1024                 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000, 0.000,
1025                 0.000, 0.000, 0.000, 0.000, 0.000, 0.106, 0.106, 0.106,
1026                 0.106, 0.106, 0.106, 0.106, 0.106, 0.106, 0.106, 0.106,
1027                 0.106, 0.106, 0.106, 0.106, 0.106, 0.106, 0.106, 0.159,
1028                 0.159, 0.159, 0.159, 0.159, 0.212, 0.212, 0.212, 0.212,
1029                 0.212, 0.212, 0.212, 0.212, 0.212, 0.212, 0.212, 0.264,
1030                 0.264, 0.264, 0.264, 0.264, 0.264, 0.264, 0.264, 0.317,
1031                 0.317, 0.317, 0.317, 0.370, 0.423, 0.423, 0.423, 0.423,
1032                 0.423, 0.423, 0.423, 0.423, 0.423, 0.476, 0.476, 0.529,
1033                 0.582, 0.582, 0.582, 0.582, 0.582, 0.582, 0.582, 0.635,
1034                 0.635, 0.688, 0.688, 0.741, 0.846, 0.846, 0.846, 0.846,
1035                 0.846, 0.846, 0.846, 0.899, 0.899, 1.005, 1.005, 1.058,
1036                 1.164, 1.164, 1.164, 1.164, 1.164, 1.164, 1.164, 1.164,
1037                 1.164, 1.164, 1.164, 1.164, 1.164, 1.164, 1.164, 1.164,
1038                 1.164, 1.164, 1.164, 1.164, 1.164, 1.164, 1.164, 1.164,
1039                 1.164, 1.164, 1.164, 1.164, 1.164, 1.164, 1.164, 1.164
1040             }
1041         };
1042         // LFO table
1043         const uint_least32_t ams_table[4] = {
1044             0,
1045             static_cast<uint_least32_t>(128 - 128 * std::pow(10, -1.44 / 10)),
1046             static_cast<uint_least32_t>(128 - 128 * std::pow(10, -5.9 / 10)),
1047             static_cast<uint_least32_t>(128 - 128 * std::pow(10, -11.8 / 10))
1048         };
1049     }
1050 
1051     // FM operator constructor.
fm_operator(int AR,int DR,int SR,int RR,int SL,int TL,int KS,int ML_,int DT_,int AMS_,int key)1052     fm_operator::fm_operator(int AR, int DR, int SR, int RR, int SL, int TL, int KS, int ML_, int DT_, int AMS_, int key):
1053         eg(AR * 2 + keyscale_table[KS][key],
1054            DR * 2 + keyscale_table[KS][key],
1055            SR * 2 + keyscale_table[KS][key],
1056            RR * 4 + keyscale_table[KS][key] + 2,
1057            SL,
1058            TL)
1059     {
1060         assert(AR >= 0 && AR <= 31);
1061         assert(DR >= 0 && DR <= 31);
1062         assert(SR >= 0 && SR <= 31);
1063         assert(RR >= 0 && RR <= 15);
1064         assert(SL >= 0);
1065         assert(TL >= 0);
1066         assert(KS >= 0 && KS <= 3);
1067         assert(ML_ >= 0 && ML_ <= 15);
1068         assert(DT_ >= 0 && DT_ <= 7);
1069         assert(AMS_ >= 0 && AMS_ <= 3);
1070         assert(key >= 0 && key <= 127);
1071 
1072         if(DT_ >= 4){
1073             DT = -detune_table[DT_ - 4][key];
1074         }else{
1075             DT = detune_table[DT_][key];
1076         }
1077         if(ML_ == 0){
1078             ML = 0.5;
1079         }else{
1080             ML = ML_;
1081         }
1082 
1083         ams_factor = ams_table[AMS_] / 2;
1084         ams_bias = 32768 - ams_factor * 256;
1085     }
1086     // Sets playback frequency rate.
set_freq_rate(float freq,float rate)1087     void fm_operator::set_freq_rate(float freq, float rate)
1088     {
1089         freq += DT;
1090         freq *= ML;
1091         swg.set_cycle(rate / freq);
1092         eg.set_rate(rate);
1093     }
1094     // Gets the next sample.
get_next()1095     inline int fm_operator::get_next()
1096     {
1097         return static_cast<int_least32_t>(swg.get_next()) * eg.get_next() >> 15;
1098     }
get_next(int modulate)1099     inline int fm_operator::get_next(int modulate)
1100     {
1101         return static_cast<int_least32_t>(swg.get_next(modulate)) * eg.get_next() >> 15;
1102     }
get_next(int ams,int modulate)1103     inline int fm_operator::get_next(int ams, int modulate)
1104     {
1105         return (static_cast<int_least32_t>(swg.get_next(modulate)) * eg.get_next() >> 15) * (ams * ams_factor + ams_bias) >> 15;
1106     }
1107 
1108     // Vibrato table.
1109     namespace{
1110         class vibrato_table{
1111         public:
1112             enum{ DIVISION = 16384 };
1113             vibrato_table();
get(int x) const1114             int_least32_t get(int x)const{ return data[x + DIVISION / 2]; }
1115         private:
1116             int_least32_t data[DIVISION];
1117         }vibrato_table;
1118 
vibrato_table()1119         vibrato_table::vibrato_table()
1120         {
1121             for(int i = 0; i < DIVISION; ++i){
1122                 double x = (static_cast<double>(i) / DIVISION - 0.5) * 256.0 / 12.0;
1123                 data[i] = static_cast<int_least32_t>((std::pow(2, x) - 1) * 65536.0);
1124             }
1125         }
1126     }
1127 
1128     // FM sound generator constructor.
fm_sound_generator(const FMPARAMETER & params,int note,float frequency_multiplier)1129     fm_sound_generator::fm_sound_generator(const FMPARAMETER& params, int note, float frequency_multiplier):
1130         op1(params.op1.AR, params.op1.DR, params.op1.SR, params.op1.RR, params.op1.SL, params.op1.TL, params.op1.KS, params.op1.ML, params.op1.DT, params.op1.AMS, note),
1131         op2(params.op2.AR, params.op2.DR, params.op2.SR, params.op2.RR, params.op2.SL, params.op2.TL, params.op2.KS, params.op2.ML, params.op2.DT, params.op2.AMS, note),
1132         op3(params.op3.AR, params.op3.DR, params.op3.SR, params.op3.RR, params.op3.SL, params.op3.TL, params.op3.KS, params.op3.ML, params.op3.DT, params.op3.AMS, note),
1133         op4(params.op4.AR, params.op4.DR, params.op4.SR, params.op4.RR, params.op4.SL, params.op4.TL, params.op4.KS, params.op4.ML, params.op4.DT, params.op4.AMS, note),
1134         ALG(params.ALG),
1135         freq(440 * std::pow(2.0, (note - 69) / 12.0)),
1136         freq_mul(frequency_multiplier),
1137         tremolo_depth(0),
1138         tremolo_freq(1),
1139         vibrato_depth(0),
1140         vibrato_freq(1),
1141         rate(0),
1142         feedback(0),
1143         damper(0),
1144         sostenute(0)
1145     {
1146         assert(ALG >= 0 && ALG <= 7);
1147         assert(params.LFO >= 0 && params.LFO <= 7);
1148         assert(params.FB >= 0 && params.FB <= 7);
1149 
1150         static const int feedbacks[8] = {
1151             31, 6, 5, 4, 3, 2, 1, 0
1152         };
1153         FB = feedbacks[params.FB];
1154 
1155         static const float ams_table[8] = {
1156             3.98, 5.56, 6.02, 6.37, 6.88, 9.63, 48.1, 72.2
1157         };
1158         ams_freq = ams_table[params.LFO];
1159         ams_enable = (params.op1.AMS + params.op2.AMS + params.op3.AMS + params.op4.AMS != 0);
1160     }
1161     // Sets playback rate.
set_rate(float rate)1162     void fm_sound_generator::set_rate(float rate)
1163     {
1164         if(this->rate != rate){
1165             this->rate = rate;
1166             ams_lfo.set_cycle(rate / ams_freq);
1167             vibrato_lfo.set_cycle(rate / vibrato_freq);
1168             tremolo_lfo.set_cycle(rate / tremolo_freq);
1169             float f = freq * freq_mul;
1170             op1.set_freq_rate(f, rate);
1171             op2.set_freq_rate(f, rate);
1172             op3.set_freq_rate(f, rate);
1173             op4.set_freq_rate(f, rate);
1174         }
1175     }
1176     // Sets frequency multiplier.
set_frequency_multiplier(float value)1177     void fm_sound_generator::set_frequency_multiplier(float value)
1178     {
1179         freq_mul = value;
1180         float f = freq * freq_mul;
1181         op1.set_freq_rate(f, rate);
1182         op2.set_freq_rate(f, rate);
1183         op3.set_freq_rate(f, rate);
1184         op4.set_freq_rate(f, rate);
1185     }
1186     // Sets damper effect.
set_damper(int damper)1187     void fm_sound_generator::set_damper(int damper)
1188     {
1189         this->damper = damper;
1190         float value = 1.0 - (1.0 - damper / 127.0) * (1.0 - sostenute / 127.0);
1191         op1.set_hold(value);
1192         op2.set_hold(value);
1193         op3.set_hold(value);
1194         op4.set_hold(value);
1195     }
1196     // Sets sostenuto effect.
set_sostenute(int sostenute)1197     void fm_sound_generator::set_sostenute(int sostenute)
1198     {
1199         this->sostenute = sostenute;
1200         float value = 1.0 - (1.0 - damper / 127.0) * (1.0 - sostenute / 127.0);
1201         op1.set_hold(value);
1202         op2.set_hold(value);
1203         op3.set_hold(value);
1204         op4.set_hold(value);
1205     }
1206     // Sets freeze efect.
set_freeze(int freeze)1207     void fm_sound_generator::set_freeze(int freeze)
1208     {
1209         float value = freeze / 127.0;
1210         op1.set_freeze(value);
1211         op2.set_freeze(value);
1212         op3.set_freeze(value);
1213         op4.set_freeze(value);
1214     }
1215     // Sets tremolo effect.
set_tremolo(int depth,float frequency)1216     void fm_sound_generator::set_tremolo(int depth, float frequency)
1217     {
1218         tremolo_depth = depth;
1219         tremolo_freq = frequency;
1220         tremolo_lfo.set_cycle(rate / frequency);
1221     }
1222     // Sets vibrato effect.
set_vibrato(float depth,float frequency)1223     void fm_sound_generator::set_vibrato(float depth, float frequency)
1224     {
1225         vibrato_depth = static_cast<int>(depth * (vibrato_table::DIVISION / 256.0));
1226         vibrato_freq = frequency;
1227         vibrato_lfo.set_cycle(rate / frequency);
1228     }
1229     // Key-off.
key_off()1230     void fm_sound_generator::key_off()
1231     {
1232         op1.key_off();
1233         op2.key_off();
1234         op3.key_off();
1235         op4.key_off();
1236     }
1237     // Sound off.
sound_off()1238     void fm_sound_generator::sound_off()
1239     {
1240         op1.sound_off();
1241         op2.sound_off();
1242         op3.sound_off();
1243         op4.sound_off();
1244     }
1245     // Returns whether or not the sound generation has been completed.
is_finished() const1246     bool fm_sound_generator::is_finished()const
1247     {
1248         switch(ALG){
1249         case 0:
1250         case 1:
1251         case 2:
1252         case 3:
1253             return op4.is_finished();
1254         case 4:
1255             return op2.is_finished() && op4.is_finished();
1256         case 5:
1257         case 6:
1258             return op2.is_finished() && op3.is_finished() && op4.is_finished();
1259         case 7:
1260             return op1.is_finished() && op2.is_finished() && op3.is_finished() && op4.is_finished();
1261         default:
1262             assert(!"fm_sound_generator: invalid algorithm number");
1263             return true;
1264         }
1265     }
1266     // Gets the next sample.
get_next()1267     int fm_sound_generator::get_next()
1268     {
1269         if(vibrato_depth){
1270             int x = static_cast<int_least32_t>(vibrato_lfo.get_next()) * vibrato_depth >> 15;
1271             int_least32_t modulation = vibrato_table.get(x);
1272             op1.add_modulation(modulation);
1273             op2.add_modulation(modulation);
1274             op3.add_modulation(modulation);
1275             op4.add_modulation(modulation);
1276         }
1277         int feedback = (this->feedback << 1) >> FB;
1278         int ret;
1279         if(ams_enable){
1280             int ams = ams_lfo.get_next() >> 7;
1281             switch(ALG){
1282             case 0:
1283                 ret = op4(ams, op3(ams, op2(ams, this->feedback = op1(ams, feedback))));
1284                 break;
1285             case 1:
1286                 ret = op4(ams, op3(ams, op2(ams, 0) + (this->feedback = op1(ams, feedback))));
1287                 break;
1288             case 2:
1289                 ret = op4(ams, op3(ams, op2(ams, 0)) + (this->feedback = op1(ams, feedback)));
1290                 break;
1291             case 3:
1292                 ret = op4(ams, op3(ams, 0) + op2(ams, this->feedback = op1(ams, feedback)));
1293                 break;
1294             case 4:
1295                 ret = op4(ams, op3(ams, 0)) + op2(ams, this->feedback = op1(ams, feedback));
1296                 break;
1297             case 5:
1298                 this->feedback = feedback = op1(ams, feedback);
1299                 ret = op4(ams, feedback) + op3(ams, feedback) + op2(ams, feedback);
1300                 break;
1301             case 6:
1302                 ret = op4(ams, 0) + op3(ams, 0) + op2(ams, this->feedback = op1(ams, feedback));
1303                 break;
1304             case 7:
1305                 ret = op4(ams, 0) + op3(ams, 0) + op2(ams, 0) + (this->feedback = op1(ams, feedback));
1306                 break;
1307             default:
1308                 assert(!"fm_sound_generator: invalid algorithm number");
1309                 return 0;
1310             }
1311         }else{
1312             switch(ALG){
1313             case 0:
1314                 ret = op4(op3(op2(this->feedback = op1(feedback))));
1315                 break;
1316             case 1:
1317                 ret = op4(op3(op2() + (this->feedback = op1(feedback))));
1318                 break;
1319             case 2:
1320                 ret = op4(op3(op2()) + (this->feedback = op1(feedback)));
1321                 break;
1322             case 3:
1323                 ret = op4(op3() + op2(this->feedback = op1(feedback)));
1324                 break;
1325             case 4:
1326                 ret = op4(op3()) + op2(this->feedback = op1(feedback));
1327                 break;
1328             case 5:
1329                 this->feedback = feedback = op1(feedback);
1330                 ret = op4(feedback) + op3(feedback) + op2(feedback);
1331                 break;
1332             case 6:
1333                 ret = op4() + op3() + op2(this->feedback = op1(feedback));
1334                 break;
1335             case 7:
1336                 ret = op4() + op3() + op2() + (this->feedback = op1(feedback));
1337                 break;
1338             default:
1339                 assert(!"fm_sound_generator: invalid algorithm number");
1340                 return 0;
1341             }
1342         }
1343         if(tremolo_depth){
1344             int_least32_t x = 4096 - (((static_cast<int_least32_t>(tremolo_lfo.get_next()) + 32768) * tremolo_depth) >> 11);
1345             ret = ret * x >> 12;
1346         }
1347         return ret;
1348     }
1349 
1350     // FM notes constructor.
fm_note(const FMPARAMETER & params,int note,int velocity_,int panpot,int assign,float frequency_multiplier)1351     fm_note::fm_note(const FMPARAMETER& params, int note, int velocity_, int panpot, int assign, float frequency_multiplier):
1352         midisynth::note(assign, panpot),
1353         fm(params, note, frequency_multiplier),
1354         velocity(velocity_)
1355     {
1356         assert(velocity >= 1 && velocity <= 127);
1357         ++velocity;
1358     }
1359     // Waveform output.
synthesize(int_least32_t * buf,std::size_t samples,float rate,int_least32_t left,int_least32_t right)1360     bool fm_note::synthesize(int_least32_t* buf, std::size_t samples, float rate, int_least32_t left, int_least32_t right)
1361     {
1362         left = (left * velocity) >> 7;
1363         right = (right * velocity) >> 7;
1364         fm.set_rate(rate);
1365         for(std::size_t i = 0; i < samples; ++i){
1366             int_least32_t sample = fm.get_next();
1367             buf[i * 2 + 0] += (sample * left) >> 14;
1368             buf[i * 2 + 1] += (sample * right) >> 14;
1369         }
1370         return !fm.is_finished();
1371     }
1372     // Note off.
note_off(int)1373     void fm_note::note_off(int)
1374     {
1375         fm.key_off();
1376     }
1377     // Sound off.
sound_off()1378     void fm_note::sound_off()
1379     {
1380         fm.sound_off();
1381     }
1382     // Sets frequency multiplier.
set_frequency_multiplier(float value)1383     void fm_note::set_frequency_multiplier(float value)
1384     {
1385         fm.set_frequency_multiplier(value);
1386     }
1387     // Sets tremolo effect.
set_tremolo(int depth,float freq)1388     void fm_note::set_tremolo(int depth, float freq)
1389     {
1390         fm.set_tremolo(depth, freq);
1391     }
1392     // Sets vibrato effect.
set_vibrato(float depth,float freq)1393     void fm_note::set_vibrato(float depth, float freq)
1394     {
1395         fm.set_vibrato(depth, freq);
1396     }
1397     // Sets damper effect.
set_damper(int value)1398     void fm_note::set_damper(int value)
1399     {
1400         fm.set_damper(value);
1401     }
1402     // Sets sostenuto effect.
set_sostenute(int value)1403     void fm_note::set_sostenute(int value)
1404     {
1405         fm.set_sostenute(value);
1406     }
1407     // Sets freeze effect.
set_freeze(int value)1408     void fm_note::set_freeze(int value)
1409     {
1410         fm.set_freeze(value);
1411     }
1412 
1413     // FM note factory initialization.
fm_note_factory()1414     fm_note_factory::fm_note_factory()
1415     {
1416         clear();
1417     }
1418     // Clear.
clear()1419     void fm_note_factory::clear()
1420     {
1421         // Default tone (sine wave)
1422         static const struct FMPARAMETER param = {
1423             7, 0, 0,    // ALG FB LFO
1424             //AR DR SR RR SL  TL KS ML DT AMS
1425             { 31, 0, 0,15, 0,  0, 0, 0, 0, 0 },
1426             {  0, 0, 0,15, 0,127, 0, 0, 0, 0 },
1427             {  0, 0, 0,15, 0,127, 0, 0, 0, 0 },
1428             {  0, 0, 0,15, 0,127, 0, 0, 0, 0 }
1429         };
1430         drums.clear();
1431         programs.clear();
1432         programs[-1] = param;
1433     }
1434     // Sound parameters validation check
1435     namespace{
is_valid_fmparameter(const FMPARAMETER & p)1436         bool is_valid_fmparameter(const FMPARAMETER& p)
1437         {
1438             return p.ALG >= 0 && p.ALG <= 7
1439                 && p.FB >= 0 && p.FB <= 7
1440                 && p.LFO >= 0 && p.LFO <= 7
1441                 && p.op1.AR >= 0 && p.op1.AR <= 31
1442                 && p.op1.DR >= 0 && p.op1.DR <= 31
1443                 && p.op1.SR >= 0 && p.op1.SR <= 31
1444                 && p.op1.RR >= 0 && p.op1.RR <= 15
1445                 && p.op1.SL >= 0 && p.op1.SL <= 15
1446                 && p.op1.TL >= 0 && p.op1.TL <= 127
1447                 && p.op1.KS >= 0 && p.op1.KS <= 3
1448                 && p.op1.ML >= 0 && p.op1.ML <= 15
1449                 && p.op1.DT >= 0 && p.op1.DT <= 7
1450                 && p.op1.AMS >= 0 && p.op1.AMS <= 3
1451                 && p.op2.AR >= 0 && p.op2.AR <= 31
1452                 && p.op2.DR >= 0 && p.op2.DR <= 31
1453                 && p.op2.SR >= 0 && p.op2.SR <= 31
1454                 && p.op2.RR >= 0 && p.op2.RR <= 15
1455                 && p.op2.SL >= 0 && p.op2.SL <= 15
1456                 && p.op2.TL >= 0 && p.op2.TL <= 127
1457                 && p.op2.KS >= 0 && p.op2.KS <= 3
1458                 && p.op2.ML >= 0 && p.op2.ML <= 15
1459                 && p.op2.DT >= 0 && p.op2.DT <= 7
1460                 && p.op2.AMS >= 0 && p.op2.AMS <= 3
1461                 && p.op3.AR >= 0 && p.op3.AR <= 31
1462                 && p.op3.DR >= 0 && p.op3.DR <= 31
1463                 && p.op3.SR >= 0 && p.op3.SR <= 31
1464                 && p.op3.RR >= 0 && p.op3.RR <= 15
1465                 && p.op3.SL >= 0 && p.op3.SL <= 15
1466                 && p.op3.TL >= 0 && p.op3.TL <= 127
1467                 && p.op3.KS >= 0 && p.op3.KS <= 3
1468                 && p.op3.ML >= 0 && p.op3.ML <= 15
1469                 && p.op3.DT >= 0 && p.op3.DT <= 7
1470                 && p.op3.AMS >= 0 && p.op3.AMS <= 3
1471                 && p.op4.AR >= 0 && p.op4.AR <= 31
1472                 && p.op4.DR >= 0 && p.op4.DR <= 31
1473                 && p.op4.SR >= 0 && p.op4.SR <= 31
1474                 && p.op4.RR >= 0 && p.op4.RR <= 15
1475                 && p.op4.SL >= 0 && p.op4.SL <= 15
1476                 && p.op4.TL >= 0 && p.op4.TL <= 127
1477                 && p.op4.KS >= 0 && p.op4.KS <= 3
1478                 && p.op4.ML >= 0 && p.op4.ML <= 15
1479                 && p.op4.DT >= 0 && p.op4.DT <= 7
1480                 && p.op4.AMS >= 0 && p.op4.AMS <= 3;
1481         }
is_valid_drumparameter(const DRUMPARAMETER & p)1482         bool is_valid_drumparameter(const DRUMPARAMETER& p)
1483         {
1484             return is_valid_fmparameter(p)
1485                 && p.key >= 0 && p.key <= 127
1486                 && p.panpot >= 0 && p.panpot <= 16383;
1487         }
1488     }
1489     // Gets program parameters.
get_program(int program,FMPARAMETER & p)1490     void fm_note_factory::get_program(int program, FMPARAMETER& p)
1491     {
1492         if(programs.find(program) != programs.end()){
1493             p = programs[program];
1494         }else if(programs.find(program & 0x3FFF) != programs.end()){
1495             p = programs[program & 0x3FFF];
1496         }else if(programs.find(program & 0x7F) != programs.end()){
1497             p = programs[program & 0x7F];
1498         }else{
1499             p = programs[-1];
1500         }
1501     }
1502     // Sets program parameter.
set_program(int number,const FMPARAMETER & p)1503     bool fm_note_factory::set_program(int number, const FMPARAMETER& p)
1504     {
1505         if(is_valid_fmparameter(p)){
1506             programs[number] = p;
1507             return true;
1508         }else{
1509             return false;
1510         }
1511     }
1512     // Sets drum program parameter.
set_drum_program(int number,const DRUMPARAMETER & p)1513     bool fm_note_factory::set_drum_program(int number, const DRUMPARAMETER& p)
1514     {
1515         if(is_valid_drumparameter(p)){
1516             drums[number] = p;
1517             return true;
1518         }else{
1519             return false;
1520         }
1521     }
1522     // Note on.
note_on(int_least32_t program,int note,int velocity,float frequency_multiplier)1523     note* fm_note_factory::note_on(int_least32_t program, int note, int velocity, float frequency_multiplier)
1524     {
1525         bool drum = (program >> 14) == 120;
1526         if(drum){
1527             int n = (program & 0x3FFF) * 128 + note;
1528             struct DRUMPARAMETER* p;
1529             if(drums.find(n) != drums.end()){
1530                 p = &drums[n];
1531             }else if(drums.find(n & 0x3FFF) != drums.end()){
1532                 p = &drums[n & 0x3FFF];
1533             }else if(drums.find(note) != drums.end()){
1534                 p = &drums[note];
1535             }else if(drums.find(-1) != drums.end()){
1536                 p = &drums[-1];
1537             }else{
1538                 return NULL;
1539             }
1540             return new fm_note(*p, p->key, velocity, p->panpot, p->assign, 1);
1541         }else{
1542             struct FMPARAMETER* p;
1543             if(programs.find(program) != programs.end()){
1544                 p = &programs[program];
1545             }else if(programs.find(program & 0x7F) != programs.end()){
1546                 p = &programs[program & 0x7F];
1547             }else{
1548                 p = &programs[-1];
1549             }
1550             return new fm_note(*p, note, velocity, 8192, 0, frequency_multiplier);
1551         }
1552     }
1553 }
1554 
1555 #endif
1556