1 /* FluidSynth - A Software Synthesizer
2  *
3  * Copyright (C) 2003  Peter Hanappe and others.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public License
7  * as published by the Free Software Foundation; either version 2 of
8  * the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the Free
17  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18  * 02110-1301, USA
19  */
20 
21 #include "fluidsynth_priv.h"
22 #include "fluid_voice.h"
23 #include "fluid_mod.h"
24 #include "fluid_chan.h"
25 #include "fluid_conv.h"
26 #include "fluid_synth.h"
27 #include "fluid_sys.h"
28 #include "fluid_sfont.h"
29 #include "fluid_rvoice_event.h"
30 
31 /* used for filter turn off optimization - if filter cutoff is above the
32    specified value and filter q is below the other value, turn filter off */
33 #define FLUID_MAX_AUDIBLE_FILTER_FC 19000.0f
34 #define FLUID_MIN_AUDIBLE_FILTER_Q 1.2f
35 
36 /* min vol envelope release (to stop clicks) in SoundFont timecents */
37 #define FLUID_MIN_VOLENVRELEASE -7200.0f /* ~16ms */
38 
39 static int fluid_voice_calculate_runtime_synthesis_parameters(fluid_voice_t* voice);
40 static int calculate_hold_decay_buffers(fluid_voice_t* voice, int gen_base,
41                                         int gen_key2base, int is_decay);
42 static fluid_real_t
43 fluid_voice_get_lower_boundary_for_attenuation(fluid_voice_t* voice);
44 
45 #define UPDATE_RVOICE0(proc) \
46   do { \
47     if (voice->can_access_rvoice) proc(voice->rvoice); \
48     else fluid_rvoice_eventhandler_push(voice->channel->synth->eventhandler, \
49       proc, voice->rvoice, 0, 0.0f); \
50   } while (0)
51 
52 #define UPDATE_RVOICE_PTR(proc, obj) \
53   do { \
54     if (voice->can_access_rvoice) proc(voice->rvoice, obj); \
55     else fluid_rvoice_eventhandler_push_ptr(voice->channel->synth->eventhandler, \
56       proc, voice->rvoice, obj); \
57   } while (0)
58 
59 
60 #define UPDATE_RVOICE_GENERIC_R1(proc, obj, rarg) \
61   do { \
62     if (voice->can_access_rvoice) proc(obj, rarg); \
63     else fluid_rvoice_eventhandler_push(voice->channel->synth->eventhandler, \
64       proc, obj, 0, rarg); \
65   } while (0)
66 
67 #define UPDATE_RVOICE_GENERIC_I1(proc, obj, iarg) \
68   do { \
69     if (voice->can_access_rvoice) proc(obj, iarg); \
70     else fluid_rvoice_eventhandler_push(voice->channel->synth->eventhandler, \
71       proc, obj, iarg, 0.0f); \
72   } while (0)
73 
74 #define UPDATE_RVOICE_GENERIC_IR(proc, obj, iarg, rarg) \
75   do { \
76     if (voice->can_access_rvoice) proc(obj, iarg, rarg); \
77     else fluid_rvoice_eventhandler_push(voice->channel->synth->eventhandler, \
78       proc, obj, iarg, rarg); \
79   } while (0)
80 
81 #define UPDATE_RVOICE_GENERIC_ALL(proc, obj, iarg, r1, r2, r3, r4, r5) \
82   do { \
83     if (voice->can_access_rvoice) proc(obj, iarg, r1, r2, r3, r4, r5); \
84     else fluid_rvoice_eventhandler_push5(voice->channel->synth->eventhandler, \
85       proc, obj, iarg, r1, r2, r3, r4, r5); \
86   } while (0)
87 
88 
89 #define UPDATE_RVOICE_VOLENV(section, arg1, arg2, arg3, arg4, arg5) \
90   do { \
91     fluid_adsr_env_set_data(&voice->volenv, section, arg1, arg2, arg3, arg4, arg5) \
92     UPDATE_RVOICE_GENERIC_ALL(fluid_adsr_env_set_data, &voice->rvoice->envlfo.volenv, section, arg1, arg2, arg3, arg4, arg5) \
93   } while(0)
94 
95 #define UPDATE_RVOICE_MODENV(section, arg1, arg2, arg3, arg4, arg5) \
96   UPDATE_RVOICE_GENERIC_ALL(fluid_adsr_env_set_data, &voice->rvoice->envlfo.modenv, section, arg1, arg2, arg3, arg4, arg5)
97 
98 #define UPDATE_RVOICE_R1(proc, arg1) UPDATE_RVOICE_GENERIC_R1(proc, voice->rvoice, arg1)
99 #define UPDATE_RVOICE_I1(proc, arg1) UPDATE_RVOICE_GENERIC_I1(proc, voice->rvoice, arg1)
100 #define UPDATE_RVOICE_FILTER1(proc, arg1) UPDATE_RVOICE_GENERIC_R1(proc, &voice->rvoice->resonant_filter, arg1)
101 
102 #define UPDATE_RVOICE2(proc, iarg, rarg) UPDATE_RVOICE_GENERIC_IR(proc, voice->rvoice, iarg, rarg)
103 #define UPDATE_RVOICE_BUFFERS2(proc, iarg, rarg) UPDATE_RVOICE_GENERIC_IR(proc, &voice->rvoice->buffers, iarg, rarg)
104 #define UPDATE_RVOICE_ENVLFO_R1(proc, envp, rarg) UPDATE_RVOICE_GENERIC_R1(proc, &voice->rvoice->envlfo.envp, rarg)
105 #define UPDATE_RVOICE_ENVLFO_I1(proc, envp, iarg) UPDATE_RVOICE_GENERIC_I1(proc, &voice->rvoice->envlfo.envp, iarg)
106 
107 static inline void
fluid_voice_update_volenv(fluid_voice_t * voice,fluid_adsr_env_section_t section,unsigned int count,fluid_real_t coeff,fluid_real_t increment,fluid_real_t min,fluid_real_t max)108 fluid_voice_update_volenv(fluid_voice_t* voice,
109 			  fluid_adsr_env_section_t section,
110                           unsigned int count,
111                           fluid_real_t coeff,
112                           fluid_real_t increment,
113                           fluid_real_t min,
114                           fluid_real_t max)
115 {
116   fluid_adsr_env_set_data(&voice->volenv, section, count, coeff, increment,
117 			  min, max);
118   UPDATE_RVOICE_GENERIC_ALL(fluid_adsr_env_set_data,
119 			    &voice->rvoice->envlfo.volenv, section, count,
120 			    coeff, increment, min, max);
121 }
122 
123 static inline void
fluid_voice_update_modenv(fluid_voice_t * voice,fluid_adsr_env_section_t section,unsigned int count,fluid_real_t coeff,fluid_real_t increment,fluid_real_t min,fluid_real_t max)124 fluid_voice_update_modenv(fluid_voice_t* voice,
125 			  fluid_adsr_env_section_t section,
126                           unsigned int count,
127                           fluid_real_t coeff,
128                           fluid_real_t increment,
129                           fluid_real_t min,
130                           fluid_real_t max)
131 {
132   UPDATE_RVOICE_GENERIC_ALL(fluid_adsr_env_set_data,
133 			    &voice->rvoice->envlfo.modenv, section, count,
134 			    coeff, increment, min, max);
135 }
136 
fluid_sample_null_ptr(fluid_sample_t ** sample)137 static inline void fluid_sample_null_ptr(fluid_sample_t** sample)
138 {
139   if (*sample != NULL) {
140     fluid_sample_decr_ref(*sample);
141     *sample = NULL;
142   }
143 }
144 
145 /*
146  * Swaps the current rvoice with the current overflow_rvoice
147  */
fluid_voice_swap_rvoice(fluid_voice_t * voice)148 static void fluid_voice_swap_rvoice(fluid_voice_t* voice)
149 {
150   fluid_rvoice_t* rtemp = voice->rvoice;
151   int ctemp = voice->can_access_rvoice;
152   voice->rvoice = voice->overflow_rvoice;
153   voice->can_access_rvoice = voice->can_access_overflow_rvoice;
154   voice->overflow_rvoice = rtemp;
155   voice->can_access_overflow_rvoice = ctemp;
156 }
157 
fluid_voice_initialize_rvoice(fluid_voice_t * voice)158 static void fluid_voice_initialize_rvoice(fluid_voice_t* voice)
159 {
160   FLUID_MEMSET(voice->rvoice, 0, sizeof(fluid_rvoice_t));
161 
162   /* The 'sustain' and 'finished' segments of the volume / modulation
163    * envelope are constant. They are never affected by any modulator
164    * or generator. Therefore it is enough to initialize them once
165    * during the lifetime of the synth.
166    */
167   fluid_voice_update_volenv(voice, FLUID_VOICE_ENVSUSTAIN,
168                           0xffffffff, 1.0f, 0.0f, -1.0f, 2.0f);
169   fluid_voice_update_volenv(voice, FLUID_VOICE_ENVFINISHED,
170                           0xffffffff, 0.0f, 0.0f, -1.0f, 1.0f);
171   fluid_voice_update_modenv(voice, FLUID_VOICE_ENVSUSTAIN,
172                           0xffffffff, 1.0f, 0.0f, -1.0f, 2.0f);
173   fluid_voice_update_modenv(voice, FLUID_VOICE_ENVFINISHED,
174                           0xffffffff, 0.0f, 0.0f, -1.0f, 1.0f);
175 }
176 
177 /*
178  * new_fluid_voice
179  */
180 fluid_voice_t*
new_fluid_voice(fluid_real_t output_rate)181 new_fluid_voice(fluid_real_t output_rate)
182 {
183   fluid_voice_t* voice;
184   voice = FLUID_NEW(fluid_voice_t);
185   if (voice == NULL) {
186     FLUID_LOG(FLUID_ERR, "Out of memory");
187     return NULL;
188   }
189   voice->rvoice = FLUID_NEW(fluid_rvoice_t);
190   voice->overflow_rvoice = FLUID_NEW(fluid_rvoice_t);
191   if (voice->rvoice == NULL || voice->overflow_rvoice == NULL) {
192     FLUID_LOG(FLUID_ERR, "Out of memory");
193     FLUID_FREE(voice->rvoice);
194     FLUID_FREE(voice);
195     return NULL;
196   }
197 
198   voice->status = FLUID_VOICE_CLEAN;
199   voice->chan = NO_CHANNEL;
200   voice->key = 0;
201   voice->vel = 0;
202   voice->channel = NULL;
203   voice->sample = NULL;
204 
205   /* Initialize both the rvoice and overflow_rvoice */
206   voice->can_access_rvoice = 1;
207   voice->can_access_overflow_rvoice = 1;
208   fluid_voice_initialize_rvoice(voice);
209   fluid_voice_swap_rvoice(voice);
210   fluid_voice_initialize_rvoice(voice);
211 
212   fluid_voice_set_output_rate(voice, output_rate);
213 
214   return voice;
215 }
216 
217 /*
218  * delete_fluid_voice
219  */
220 int
delete_fluid_voice(fluid_voice_t * voice)221 delete_fluid_voice(fluid_voice_t* voice)
222 {
223   if (voice == NULL) {
224     return FLUID_OK;
225   }
226   if (!voice->can_access_rvoice || !voice->can_access_overflow_rvoice) {
227     /* stop rvoice before deleting voice! */
228     return FLUID_FAILED;
229   }
230   FLUID_FREE(voice->overflow_rvoice);
231   FLUID_FREE(voice->rvoice);
232   FLUID_FREE(voice);
233   return FLUID_OK;
234 }
235 
236 /* fluid_voice_init
237  *
238  * Initialize the synthesis process
239  */
240 int
fluid_voice_init(fluid_voice_t * voice,fluid_sample_t * sample,fluid_channel_t * channel,int key,int vel,unsigned int id,unsigned int start_time,fluid_real_t gain)241 fluid_voice_init(fluid_voice_t* voice, fluid_sample_t* sample,
242 		 fluid_channel_t* channel, int key, int vel, unsigned int id,
243 		 unsigned int start_time, fluid_real_t gain)
244 {
245   /* Note: The voice parameters will be initialized later, when the
246    * generators have been retrieved from the sound font. Here, only
247    * the 'working memory' of the voice (position in envelopes, history
248    * of IIR filters, position in sample etc) is initialized. */
249   int i;
250 
251   if (!voice->can_access_rvoice) {
252     if (voice->can_access_overflow_rvoice)
253       fluid_voice_swap_rvoice(voice);
254     else {
255       FLUID_LOG(FLUID_ERR, "Internal error: Cannot access an rvoice in fluid_voice_init!");
256       return FLUID_FAILED;
257     }
258   }
259   /* We are now guaranteed to have access to the rvoice */
260 
261   if (voice->sample)
262     fluid_voice_off(voice);
263 
264   voice->id = id;
265   voice->chan = fluid_channel_get_num(channel);
266   voice->key = (unsigned char) key;
267   voice->vel = (unsigned char) vel;
268   voice->channel = channel;
269   voice->mod_count = 0;
270   voice->start_time = start_time;
271   voice->debug = 0;
272   voice->has_noteoff = 0;
273   UPDATE_RVOICE0(fluid_rvoice_reset);
274 
275   /* Increment the reference count of the sample to prevent the
276      unloading of the soundfont while this voice is playing,
277      once for us and once for the rvoice. */
278   fluid_sample_incr_ref(sample);
279   UPDATE_RVOICE_PTR(fluid_rvoice_set_sample, sample);
280   fluid_sample_incr_ref(sample);
281   voice->sample = sample;
282 
283   i = fluid_channel_get_interp_method(channel);
284   UPDATE_RVOICE_I1(fluid_rvoice_set_interp_method, i);
285 
286   /* Set all the generators to their default value, according to SF
287    * 2.01 section 8.1.3 (page 48). The value of NRPN messages are
288    * copied from the channel to the voice's generators. The sound font
289    * loader overwrites them. The generator values are later converted
290    * into voice parameters in
291    * fluid_voice_calculate_runtime_synthesis_parameters.  */
292   fluid_gen_init(&voice->gen[0], channel);
293   UPDATE_RVOICE_I1(fluid_rvoice_set_samplemode, _SAMPLEMODE(voice));
294 
295   voice->synth_gain = gain;
296   /* avoid division by zero later*/
297   if (voice->synth_gain < 0.0000001){
298     voice->synth_gain = 0.0000001;
299   }
300   UPDATE_RVOICE_R1(fluid_rvoice_set_synth_gain, voice->synth_gain);
301 
302   /* Set up buffer mapping, should be done more flexible in the future. */
303   i = channel->synth->audio_groups;
304   UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_mapping, 2, i*2 + SYNTH_REVERB_CHANNEL);
305   UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_mapping, 3, i*2 + SYNTH_CHORUS_CHANNEL);
306   i = 2 * (voice->chan % i);
307   UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_mapping, 0, i);
308   UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_mapping, 1, i+1);
309 
310   return FLUID_OK;
311 }
312 
313 
314 /**
315  * Update sample rate.
316  * NOTE: If the voice is active, it will be turned off.
317  */
318 int
fluid_voice_set_output_rate(fluid_voice_t * voice,fluid_real_t value)319 fluid_voice_set_output_rate(fluid_voice_t* voice, fluid_real_t value)
320 {
321   if (_PLAYING(voice))
322     fluid_voice_off(voice);
323 
324   voice->output_rate = value;
325   UPDATE_RVOICE_R1(fluid_rvoice_set_output_rate, value);
326   /* Update the other rvoice as well */
327   fluid_voice_swap_rvoice(voice);
328   UPDATE_RVOICE_R1(fluid_rvoice_set_output_rate, value);
329   fluid_voice_swap_rvoice(voice);
330 
331   return FLUID_FAILED;
332 }
333 
334 
335 /**
336  * Set the value of a generator.
337  * @param voice Voice instance
338  * @param i Generator ID (#fluid_gen_type)
339  * @param val Generator value
340  */
341 void
fluid_voice_gen_set(fluid_voice_t * voice,int i,float val)342 fluid_voice_gen_set(fluid_voice_t* voice, int i, float val)
343 {
344   voice->gen[i].val = val;
345   voice->gen[i].flags = GEN_SET;
346   if (i == GEN_SAMPLEMODE)
347     UPDATE_RVOICE_I1(fluid_rvoice_set_samplemode, (int) val);
348 }
349 
350 /**
351  * Offset the value of a generator.
352  * @param voice Voice instance
353  * @param i Generator ID (#fluid_gen_type)
354  * @param val Value to add to the existing value
355  */
356 void
fluid_voice_gen_incr(fluid_voice_t * voice,int i,float val)357 fluid_voice_gen_incr(fluid_voice_t* voice, int i, float val)
358 {
359   voice->gen[i].val += val;
360   voice->gen[i].flags = GEN_SET;
361 }
362 
363 /**
364  * Get the value of a generator.
365  * @param voice Voice instance
366  * @param gen Generator ID (#fluid_gen_type)
367  * @return Current generator value
368  */
369 float
fluid_voice_gen_get(fluid_voice_t * voice,int gen)370 fluid_voice_gen_get(fluid_voice_t* voice, int gen)
371 {
372   return voice->gen[gen].val;
373 }
374 
fluid_voice_gen_value(fluid_voice_t * voice,int num)375 fluid_real_t fluid_voice_gen_value(fluid_voice_t* voice, int num)
376 {
377 	/* This is an extension to the SoundFont standard. More
378 	 * documentation is available at the fluid_synth_set_gen2()
379 	 * function. */
380 	if (voice->gen[num].flags == GEN_ABS_NRPN) {
381 		return (fluid_real_t) voice->gen[num].nrpn;
382 	} else {
383 		return (fluid_real_t) (voice->gen[num].val + voice->gen[num].mod + voice->gen[num].nrpn);
384 	}
385 }
386 
387 
388 /**
389  * Synthesize a voice to a buffer.
390  *
391  * @param voice Voice to synthesize
392  * @param dsp_buf Audio buffer to synthesize to (#FLUID_BUFSIZE in length)
393  * @return Count of samples written to dsp_buf (can be 0)
394  *
395  * Panning, reverb and chorus are processed separately. The dsp interpolation
396  * routine is in (fluid_dsp_float.c).
397  */
398 int
fluid_voice_write(fluid_voice_t * voice,fluid_real_t * dsp_buf)399 fluid_voice_write (fluid_voice_t* voice, fluid_real_t *dsp_buf)
400 {
401   int result;
402   if (!voice->can_access_rvoice)
403     return 0;
404 
405   result = fluid_rvoice_write(voice->rvoice, dsp_buf);
406 
407   if (result == -1)
408     return 0;
409 
410   if ((result < FLUID_BUFSIZE) && _PLAYING(voice)) /* Voice finished by itself */
411     fluid_voice_off(voice);
412 
413   return result;
414 }
415 
416 
417 /**
418  * Mix voice data to left/right (panning), reverb and chorus buffers.
419  * @param count Number of samples
420  * @param dsp_buf Source buffer
421  * @param voice Voice to mix
422  * @param left_buf Left audio buffer
423  * @param right_buf Right audio buffer
424  * @param reverb_buf Reverb buffer
425  * @param chorus_buf Chorus buffer
426  *
427  */
428 void
fluid_voice_mix(fluid_voice_t * voice,int count,fluid_real_t * dsp_buf,fluid_real_t * left_buf,fluid_real_t * right_buf,fluid_real_t * reverb_buf,fluid_real_t * chorus_buf)429 fluid_voice_mix (fluid_voice_t *voice, int count, fluid_real_t* dsp_buf,
430 		 fluid_real_t* left_buf, fluid_real_t* right_buf,
431 		 fluid_real_t* reverb_buf, fluid_real_t* chorus_buf)
432 {
433   fluid_rvoice_buffers_t buffers;
434   fluid_real_t* dest_buf[4] = {left_buf, right_buf, reverb_buf, chorus_buf};
435 
436   fluid_rvoice_buffers_set_amp(&buffers, 0, voice->amp_left);
437   fluid_rvoice_buffers_set_amp(&buffers, 1, voice->amp_right);
438   fluid_rvoice_buffers_set_amp(&buffers, 2, voice->amp_reverb);
439   fluid_rvoice_buffers_set_amp(&buffers, 3, voice->amp_chorus);
440 
441   fluid_rvoice_buffers_mix(&buffers, dsp_buf, count, dest_buf, 4);
442 
443   fluid_check_fpe ("voice_mix");
444 }
445 
446 
447 
448 /*
449  * fluid_voice_start
450  */
fluid_voice_start(fluid_voice_t * voice)451 void fluid_voice_start(fluid_voice_t* voice)
452 {
453   /* The maximum volume of the loop is calculated and cached once for each
454    * sample with its nominal loop settings. This happens, when the sample is used
455    * for the first time.*/
456 
457   fluid_voice_calculate_runtime_synthesis_parameters(voice);
458 
459   voice->ref = fluid_profile_ref();
460 
461   voice->status = FLUID_VOICE_ON;
462 
463   /* Increment voice count */
464   voice->channel->synth->active_voice_count++;
465 }
466 
467 void
fluid_voice_calculate_gen_pitch(fluid_voice_t * voice)468 fluid_voice_calculate_gen_pitch(fluid_voice_t* voice)
469 {
470   fluid_tuning_t* tuning;
471   fluid_real_t x;
472 
473   /* The GEN_PITCH is a hack to fit the pitch bend controller into the
474    * modulator paradigm.  Now the nominal pitch of the key is set.
475    * Note about SCALETUNE: SF2.01 8.1.3 says, that this generator is a
476    * non-realtime parameter. So we don't allow modulation (as opposed
477    * to _GEN(voice, GEN_SCALETUNE) When the scale tuning is varied,
478    * one key remains fixed. Here C3 (MIDI number 60) is used.
479    */
480   if (fluid_channel_has_tuning(voice->channel)) {
481     tuning = fluid_channel_get_tuning (voice->channel);
482     x = fluid_tuning_get_pitch (tuning, (int)(voice->root_pitch / 100.0f));
483     voice->gen[GEN_PITCH].val = voice->gen[GEN_SCALETUNE].val / 100.0f *
484       (fluid_tuning_get_pitch (tuning, voice->key) - x) + x;
485   } else {
486     voice->gen[GEN_PITCH].val = voice->gen[GEN_SCALETUNE].val
487       * (voice->key - voice->root_pitch / 100.0f) + voice->root_pitch;
488   }
489 
490 }
491 
492 /*
493  * fluid_voice_calculate_runtime_synthesis_parameters
494  *
495  * in this function we calculate the values of all the parameters. the
496  * parameters are converted to their most useful unit for the DSP
497  * algorithm, for example, number of samples instead of
498  * timecents. Some parameters keep their "perceptual" unit and
499  * conversion will be done in the DSP function. This is the case, for
500  * example, for the pitch since it is modulated by the controllers in
501  * cents. */
502 static int
fluid_voice_calculate_runtime_synthesis_parameters(fluid_voice_t * voice)503 fluid_voice_calculate_runtime_synthesis_parameters(fluid_voice_t* voice)
504 {
505   int i;
506 
507   int list_of_generators_to_initialize[35] = {
508     GEN_STARTADDROFS,                    /* SF2.01 page 48 #0   */
509     GEN_ENDADDROFS,                      /*                #1   */
510     GEN_STARTLOOPADDROFS,                /*                #2   */
511     GEN_ENDLOOPADDROFS,                  /*                #3   */
512     /* GEN_STARTADDRCOARSEOFS see comment below [1]        #4   */
513     GEN_MODLFOTOPITCH,                   /*                #5   */
514     GEN_VIBLFOTOPITCH,                   /*                #6   */
515     GEN_MODENVTOPITCH,                   /*                #7   */
516     GEN_FILTERFC,                        /*                #8   */
517     GEN_FILTERQ,                         /*                #9   */
518     GEN_MODLFOTOFILTERFC,                /*                #10  */
519     GEN_MODENVTOFILTERFC,                /*                #11  */
520     /* GEN_ENDADDRCOARSEOFS [1]                            #12  */
521     GEN_MODLFOTOVOL,                     /*                #13  */
522     /* not defined                                         #14  */
523     GEN_CHORUSSEND,                      /*                #15  */
524     GEN_REVERBSEND,                      /*                #16  */
525     GEN_PAN,                             /*                #17  */
526     /* not defined                                         #18  */
527     /* not defined                                         #19  */
528     /* not defined                                         #20  */
529     GEN_MODLFODELAY,                     /*                #21  */
530     GEN_MODLFOFREQ,                      /*                #22  */
531     GEN_VIBLFODELAY,                     /*                #23  */
532     GEN_VIBLFOFREQ,                      /*                #24  */
533     GEN_MODENVDELAY,                     /*                #25  */
534     GEN_MODENVATTACK,                    /*                #26  */
535     GEN_MODENVHOLD,                      /*                #27  */
536     GEN_MODENVDECAY,                     /*                #28  */
537     /* GEN_MODENVSUSTAIN [1]                               #29  */
538     GEN_MODENVRELEASE,                   /*                #30  */
539     /* GEN_KEYTOMODENVHOLD [1]                             #31  */
540     /* GEN_KEYTOMODENVDECAY [1]                            #32  */
541     GEN_VOLENVDELAY,                     /*                #33  */
542     GEN_VOLENVATTACK,                    /*                #34  */
543     GEN_VOLENVHOLD,                      /*                #35  */
544     GEN_VOLENVDECAY,                     /*                #36  */
545     /* GEN_VOLENVSUSTAIN [1]                               #37  */
546     GEN_VOLENVRELEASE,                   /*                #38  */
547     /* GEN_KEYTOVOLENVHOLD [1]                             #39  */
548     /* GEN_KEYTOVOLENVDECAY [1]                            #40  */
549     /* GEN_STARTLOOPADDRCOARSEOFS [1]                      #45  */
550     GEN_KEYNUM,                          /*                #46  */
551     GEN_VELOCITY,                        /*                #47  */
552     GEN_ATTENUATION,                     /*                #48  */
553     /* GEN_ENDLOOPADDRCOARSEOFS [1]                        #50  */
554     /* GEN_COARSETUNE           [1]                        #51  */
555     /* GEN_FINETUNE             [1]                        #52  */
556     GEN_OVERRIDEROOTKEY,                 /*                #58  */
557     GEN_PITCH,                           /*                ---  */
558     -1};                                 /* end-of-list marker  */
559 
560   /* When the voice is made ready for the synthesis process, a lot of
561    * voice-internal parameters have to be calculated.
562    *
563    * At this point, the sound font has already set the -nominal- value
564    * for all generators (excluding GEN_PITCH). Most generators can be
565    * modulated - they include a nominal value and an offset (which
566    * changes with velocity, note number, channel parameters like
567    * aftertouch, mod wheel...) Now this offset will be calculated as
568    * follows:
569    *
570    *  - Process each modulator once.
571    *  - Calculate its output value.
572    *  - Find the target generator.
573    *  - Add the output value to the modulation value of the generator.
574    *
575    * Note: The generators have been initialized with
576    * fluid_gen_set_default_values.
577    */
578 
579   for (i = 0; i < voice->mod_count; i++) {
580     fluid_mod_t* mod = &voice->mod[i];
581     fluid_real_t modval = fluid_mod_get_value(mod, voice->channel, voice);
582     int dest_gen_index = mod->dest;
583     fluid_gen_t* dest_gen = &voice->gen[dest_gen_index];
584     dest_gen->mod += modval;
585     /*      fluid_dump_modulator(mod); */
586   }
587 
588   /* Now the generators are initialized, nominal and modulation value.
589    * The voice parameters (which depend on generators) are calculated
590    * with fluid_voice_update_param. Processing the list of generator
591    * changes will calculate each voice parameter once.
592    *
593    * Note [1]: Some voice parameters depend on several generators. For
594    * example, the pitch depends on GEN_COARSETUNE, GEN_FINETUNE and
595    * GEN_PITCH.  voice->pitch.  Unnecessary recalculation is avoided
596    * by removing all but one generator from the list of voice
597    * parameters.  Same with GEN_XXX and GEN_XXXCOARSE: the
598    * initialisation list contains only GEN_XXX.
599    */
600 
601   /* Calculate the voice parameter(s) dependent on each generator. */
602   for (i = 0; list_of_generators_to_initialize[i] != -1; i++) {
603     fluid_voice_update_param(voice, list_of_generators_to_initialize[i]);
604   }
605 
606   /* Make an estimate on how loud this voice can get at any time (attenuation). */
607   UPDATE_RVOICE_R1(fluid_rvoice_set_min_attenuation_cB,
608                  fluid_voice_get_lower_boundary_for_attenuation(voice));
609   return FLUID_OK;
610 }
611 
612 /*
613  * calculate_hold_decay_buffers
614  */
615 static int
calculate_hold_decay_buffers(fluid_voice_t * voice,int gen_base,int gen_key2base,int is_decay)616 calculate_hold_decay_buffers(fluid_voice_t* voice, int gen_base,
617                              int gen_key2base, int is_decay)
618 {
619   /* Purpose:
620    *
621    * Returns the number of DSP loops, that correspond to the hold
622    * (is_decay=0) or decay (is_decay=1) time.
623    * gen_base=GEN_VOLENVHOLD, GEN_VOLENVDECAY, GEN_MODENVHOLD,
624    * GEN_MODENVDECAY gen_key2base=GEN_KEYTOVOLENVHOLD,
625    * GEN_KEYTOVOLENVDECAY, GEN_KEYTOMODENVHOLD, GEN_KEYTOMODENVDECAY
626    */
627 
628   fluid_real_t timecents;
629   fluid_real_t seconds;
630   int buffers;
631 
632   /* SF2.01 section 8.4.3 # 31, 32, 39, 40
633    * GEN_KEYTOxxxENVxxx uses key 60 as 'origin'.
634    * The unit of the generator is timecents per key number.
635    * If KEYTOxxxENVxxx is 100, a key one octave over key 60 (72)
636    * will cause (60-72)*100=-1200 timecents of time variation.
637    * The time is cut in half.
638    */
639   timecents = (_GEN(voice, gen_base) + _GEN(voice, gen_key2base) * (60.0 - voice->key));
640 
641   /* Range checking */
642   if (is_decay){
643     /* SF 2.01 section 8.1.3 # 28, 36 */
644     if (timecents > 8000.0) {
645       timecents = 8000.0;
646     }
647   } else {
648     /* SF 2.01 section 8.1.3 # 27, 35 */
649     if (timecents > 5000) {
650       timecents = 5000.0;
651     }
652     /* SF 2.01 section 8.1.2 # 27, 35:
653      * The most negative number indicates no hold time
654      */
655     if (timecents <= -32768.) {
656       return 0;
657     }
658   }
659   /* SF 2.01 section 8.1.3 # 27, 28, 35, 36 */
660   if (timecents < -12000.0) {
661     timecents = -12000.0;
662   }
663 
664   seconds = fluid_tc2sec(timecents);
665   /* Each DSP loop processes FLUID_BUFSIZE samples. */
666 
667   /* round to next full number of buffers */
668   buffers = (int)(((fluid_real_t)voice->output_rate * seconds)
669 		  / (fluid_real_t)FLUID_BUFSIZE
670 		  +0.5);
671 
672   return buffers;
673 }
674 
675 /*
676  * The value of a generator (gen) has changed.  (The different
677  * generators are listed in fluidsynth.h, or in SF2.01 page 48-49)
678  * Now the dependent 'voice' parameters are calculated.
679  *
680  * fluid_voice_update_param can be called during the setup of the
681  * voice (to calculate the initial value for a voice parameter), or
682  * during its operation (a generator has been changed due to
683  * real-time parameter modifications like pitch-bend).
684  *
685  * Note: The generator holds three values: The base value .val, an
686  * offset caused by modulators .mod, and an offset caused by the
687  * NRPN system. _GEN(voice, generator_enumerator) returns the sum
688  * of all three.
689  */
690 /**
691  * Update all the synthesis parameters, which depend on generator \a gen.
692  * @param voice Voice instance
693  * @param gen Generator id (#fluid_gen_type)
694  *
695  * This is only necessary after changing a generator of an already operating voice.
696  * Most applications will not need this function.
697  */
698 void
fluid_voice_update_param(fluid_voice_t * voice,int gen)699 fluid_voice_update_param(fluid_voice_t* voice, int gen)
700 {
701   double q_dB;
702   fluid_real_t x;
703   fluid_real_t y;
704   unsigned int count, z;
705   // Alternate attenuation scale used by EMU10K1 cards when setting the attenuation at the preset or instrument level within the SoundFont bank.
706   static const float ALT_ATTENUATION_SCALE = 0.4;
707 
708   switch (gen) {
709 
710   case GEN_PAN:
711     /* range checking is done in the fluid_pan function */
712     voice->pan = _GEN(voice, GEN_PAN);
713     voice->amp_left = fluid_pan(voice->pan, 1) * voice->synth_gain / 32768.0f;
714     voice->amp_right = fluid_pan(voice->pan, 0) * voice->synth_gain / 32768.0f;
715     UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_amp, 0, voice->amp_left);
716     UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_amp, 1, voice->amp_right);
717     break;
718 
719   case GEN_ATTENUATION:
720     voice->attenuation = ((fluid_real_t)(voice)->gen[GEN_ATTENUATION].val*ALT_ATTENUATION_SCALE) +
721     (fluid_real_t)(voice)->gen[GEN_ATTENUATION].mod + (fluid_real_t)(voice)->gen[GEN_ATTENUATION].nrpn;
722 
723     /* Range: SF2.01 section 8.1.3 # 48
724      * Motivation for range checking:
725      * OHPiano.SF2 sets initial attenuation to a whooping -96 dB */
726     fluid_clip(voice->attenuation, 0.0, 1440.0);
727     UPDATE_RVOICE_R1(fluid_rvoice_set_attenuation, voice->attenuation);
728     break;
729 
730     /* The pitch is calculated from three different generators.
731      * Read comment in fluidsynth.h about GEN_PITCH.
732      */
733   case GEN_PITCH:
734   case GEN_COARSETUNE:
735   case GEN_FINETUNE:
736     /* The testing for allowed range is done in 'fluid_ct2hz' */
737     voice->pitch = (_GEN(voice, GEN_PITCH)
738 		    + 100.0f * _GEN(voice, GEN_COARSETUNE)
739 		    + _GEN(voice, GEN_FINETUNE));
740     UPDATE_RVOICE_R1(fluid_rvoice_set_pitch, voice->pitch);
741     break;
742 
743   case GEN_REVERBSEND:
744     /* The generator unit is 'tenths of a percent'. */
745     voice->reverb_send = _GEN(voice, GEN_REVERBSEND) / 1000.0f;
746     fluid_clip(voice->reverb_send, 0.0, 1.0);
747     voice->amp_reverb = voice->reverb_send * voice->synth_gain / 32768.0f;
748     UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_amp, 2, voice->amp_reverb);
749     break;
750 
751   case GEN_CHORUSSEND:
752     /* The generator unit is 'tenths of a percent'. */
753     voice->chorus_send = _GEN(voice, GEN_CHORUSSEND) / 1000.0f;
754     fluid_clip(voice->chorus_send, 0.0, 1.0);
755     voice->amp_chorus = voice->chorus_send * voice->synth_gain / 32768.0f;
756     UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_amp, 3, voice->amp_chorus);
757     break;
758 
759   case GEN_OVERRIDEROOTKEY:
760     /* This is a non-realtime parameter. Therefore the .mod part of the generator
761      * can be neglected.
762      * NOTE: origpitch sets MIDI root note while pitchadj is a fine tuning amount
763      * which offsets the original rate.  This means that the fine tuning is
764      * inverted with respect to the root note (so subtract it, not add).
765      */
766     if (voice->sample != NULL) {
767       if (voice->gen[GEN_OVERRIDEROOTKEY].val > -1)   //FIXME: use flag instead of -1
768         voice->root_pitch = voice->gen[GEN_OVERRIDEROOTKEY].val * 100.0f
769 	  - voice->sample->pitchadj;
770       else
771         voice->root_pitch = voice->sample->origpitch * 100.0f - voice->sample->pitchadj;
772       x = (fluid_ct2hz(voice->root_pitch) * ((fluid_real_t) voice->output_rate / voice->sample->samplerate));
773     } else {
774       if (voice->gen[GEN_OVERRIDEROOTKEY].val > -1)    //FIXME: use flag instead of -1
775         voice->root_pitch = voice->gen[GEN_OVERRIDEROOTKEY].val * 100.0f;
776       else
777         voice->root_pitch = 0;
778       x = fluid_ct2hz(voice->root_pitch);
779     }
780     /* voice->pitch depends on voice->root_pitch, so calculate voice->pitch now */
781     fluid_voice_calculate_gen_pitch(voice);
782     UPDATE_RVOICE_R1(fluid_rvoice_set_root_pitch_hz, x);
783 
784     break;
785 
786   case GEN_FILTERFC:
787     /* The resonance frequency is converted from absolute cents to
788      * midicents .val and .mod are both used, this permits real-time
789      * modulation.  The allowed range is tested in the 'fluid_ct2hz'
790      * function [PH,20021214]
791      */
792     x = _GEN(voice, GEN_FILTERFC);
793     UPDATE_RVOICE_FILTER1(fluid_iir_filter_set_fres, x);
794     break;
795 
796   case GEN_FILTERQ:
797     /* The generator contains 'centibels' (1/10 dB) => divide by 10 to
798      * obtain dB */
799     q_dB = _GEN(voice, GEN_FILTERQ) / 10.0f;
800 
801     /* Range: SF2.01 section 8.1.3 # 8 (convert from cB to dB => /10) */
802     fluid_clip(q_dB, 0.0f, 96.0f);
803 
804     /* Short version: Modify the Q definition in a way, that a Q of 0
805      * dB leads to no resonance hump in the freq. response.
806      *
807      * Long version: From SF2.01, page 39, item 9 (initialFilterQ):
808      * "The gain at the cutoff frequency may be less than zero when
809      * zero is specified".  Assume q_dB=0 / q_lin=1: If we would leave
810      * q as it is, then this results in a 3 dB hump slightly below
811      * fc. At fc, the gain is exactly the DC gain (0 dB).  What is
812      * (probably) meant here is that the filter does not show a
813      * resonance hump for q_dB=0. In this case, the corresponding
814      * q_lin is 1/sqrt(2)=0.707.  The filter should have 3 dB of
815      * attenuation at fc now.  In this case Q_dB is the height of the
816      * resonance peak not over the DC gain, but over the frequency
817      * response of a non-resonant filter.  This idea is implemented as
818      * follows: */
819     q_dB -= 3.01f;
820     UPDATE_RVOICE_FILTER1(fluid_iir_filter_set_q_dB, q_dB);
821 
822     break;
823 
824   case GEN_MODLFOTOPITCH:
825     x = _GEN(voice, GEN_MODLFOTOPITCH);
826     fluid_clip(x, -12000.0, 12000.0);
827     UPDATE_RVOICE_R1(fluid_rvoice_set_modlfo_to_pitch, x);
828     break;
829 
830   case GEN_MODLFOTOVOL:
831     x = _GEN(voice, GEN_MODLFOTOVOL);
832     fluid_clip(x, -960.0, 960.0);
833     UPDATE_RVOICE_R1(fluid_rvoice_set_modlfo_to_vol, x);
834     break;
835 
836   case GEN_MODLFOTOFILTERFC:
837     x = _GEN(voice, GEN_MODLFOTOFILTERFC);
838     fluid_clip(x, -12000, 12000);
839     UPDATE_RVOICE_R1(fluid_rvoice_set_modlfo_to_fc, x);
840     break;
841 
842   case GEN_MODLFODELAY:
843     x = _GEN(voice, GEN_MODLFODELAY);
844     fluid_clip(x, -12000.0f, 5000.0f);
845     z = (unsigned int) (voice->output_rate * fluid_tc2sec_delay(x));
846     UPDATE_RVOICE_ENVLFO_I1(fluid_lfo_set_delay, modlfo, z);
847     break;
848 
849   case GEN_MODLFOFREQ:
850     /* - the frequency is converted into a delta value, per buffer of FLUID_BUFSIZE samples
851      * - the delay into a sample delay
852      */
853     x = _GEN(voice, GEN_MODLFOFREQ);
854     fluid_clip(x, -16000.0f, 4500.0f);
855     x = (4.0f * FLUID_BUFSIZE * fluid_act2hz(x) / voice->output_rate);
856     UPDATE_RVOICE_ENVLFO_R1(fluid_lfo_set_incr, modlfo, x);
857     break;
858 
859   case GEN_VIBLFOFREQ:
860     /* vib lfo
861      *
862      * - the frequency is converted into a delta value, per buffer of FLUID_BUFSIZE samples
863      * - the delay into a sample delay
864      */
865     x = _GEN(voice, GEN_VIBLFOFREQ);
866     fluid_clip(x, -16000.0f, 4500.0f);
867     x = 4.0f * FLUID_BUFSIZE * fluid_act2hz(x) / voice->output_rate;
868     UPDATE_RVOICE_ENVLFO_R1(fluid_lfo_set_incr, viblfo, x);
869     break;
870 
871   case GEN_VIBLFODELAY:
872     x = _GEN(voice,GEN_VIBLFODELAY);
873     fluid_clip(x, -12000.0f, 5000.0f);
874     z = (unsigned int) (voice->output_rate * fluid_tc2sec_delay(x));
875     UPDATE_RVOICE_ENVLFO_I1(fluid_lfo_set_delay, viblfo, z);
876     break;
877 
878   case GEN_VIBLFOTOPITCH:
879     x = _GEN(voice, GEN_VIBLFOTOPITCH);
880     fluid_clip(x, -12000.0, 12000.0);
881     UPDATE_RVOICE_R1(fluid_rvoice_set_viblfo_to_pitch, x);
882     break;
883 
884   case GEN_KEYNUM:
885     /* GEN_KEYNUM: SF2.01 page 46, item 46
886      *
887      * If this generator is active, it forces the key number to its
888      * value.  Non-realtime controller.
889      *
890      * There is a flag, which should indicate, whether a generator is
891      * enabled or not.  But here we rely on the default value of -1.
892      * */
893     x = _GEN(voice, GEN_KEYNUM);
894     if (x >= 0){
895       voice->key = x;
896     }
897     break;
898 
899   case GEN_VELOCITY:
900     /* GEN_VELOCITY: SF2.01 page 46, item 47
901      *
902      * If this generator is active, it forces the velocity to its
903      * value. Non-realtime controller.
904      *
905      * There is a flag, which should indicate, whether a generator is
906      * enabled or not. But here we rely on the default value of -1.  */
907     x = _GEN(voice, GEN_VELOCITY);
908     if (x > 0) {
909       voice->vel = x;
910     }
911     break;
912 
913   case GEN_MODENVTOPITCH:
914     x = _GEN(voice, GEN_MODENVTOPITCH);
915     fluid_clip(x, -12000.0, 12000.0);
916     UPDATE_RVOICE_R1(fluid_rvoice_set_modenv_to_pitch, x);
917     break;
918 
919   case GEN_MODENVTOFILTERFC:
920     x = _GEN(voice,GEN_MODENVTOFILTERFC);
921 
922     /* Range: SF2.01 section 8.1.3 # 1
923      * Motivation for range checking:
924      * Filter is reported to make funny noises now and then
925      */
926     fluid_clip(x, -12000.0, 12000.0);
927     UPDATE_RVOICE_R1(fluid_rvoice_set_modenv_to_fc, x);
928     break;
929 
930 
931     /* sample start and ends points
932      *
933      * Range checking is initiated via the
934      * voice->check_sample_sanity flag,
935      * because it is impossible to check here:
936      * During the voice setup, all modulators are processed, while
937      * the voice is inactive. Therefore, illegal settings may
938      * occur during the setup (for example: First move the loop
939      * end point ahead of the loop start point => invalid, then
940      * move the loop start point forward => valid again.
941      */
942   case GEN_STARTADDROFS:              /* SF2.01 section 8.1.3 # 0 */
943   case GEN_STARTADDRCOARSEOFS:        /* SF2.01 section 8.1.3 # 4 */
944     if (voice->sample != NULL) {
945       z = (voice->sample->start
946 			     + (int) _GEN(voice, GEN_STARTADDROFS)
947 			     + 32768 * (int) _GEN(voice, GEN_STARTADDRCOARSEOFS));
948       UPDATE_RVOICE_I1(fluid_rvoice_set_start, z);
949     }
950     break;
951   case GEN_ENDADDROFS:                 /* SF2.01 section 8.1.3 # 1 */
952   case GEN_ENDADDRCOARSEOFS:           /* SF2.01 section 8.1.3 # 12 */
953     if (voice->sample != NULL) {
954       z = (voice->sample->end
955 			   + (int) _GEN(voice, GEN_ENDADDROFS)
956 			   + 32768 * (int) _GEN(voice, GEN_ENDADDRCOARSEOFS));
957       UPDATE_RVOICE_I1(fluid_rvoice_set_end, z);
958     }
959     break;
960   case GEN_STARTLOOPADDROFS:           /* SF2.01 section 8.1.3 # 2 */
961   case GEN_STARTLOOPADDRCOARSEOFS:     /* SF2.01 section 8.1.3 # 45 */
962     if (voice->sample != NULL) {
963       z = (voice->sample->loopstart
964 				  + (int) _GEN(voice, GEN_STARTLOOPADDROFS)
965 				  + 32768 * (int) _GEN(voice, GEN_STARTLOOPADDRCOARSEOFS));
966       UPDATE_RVOICE_I1(fluid_rvoice_set_loopstart, z);
967     }
968     break;
969 
970   case GEN_ENDLOOPADDROFS:             /* SF2.01 section 8.1.3 # 3 */
971   case GEN_ENDLOOPADDRCOARSEOFS:       /* SF2.01 section 8.1.3 # 50 */
972     if (voice->sample != NULL) {
973       z = (voice->sample->loopend
974 				+ (int) _GEN(voice, GEN_ENDLOOPADDROFS)
975 				+ 32768 * (int) _GEN(voice, GEN_ENDLOOPADDRCOARSEOFS));
976       UPDATE_RVOICE_I1(fluid_rvoice_set_loopend, z);
977     }
978     break;
979 
980     /* Conversion functions differ in range limit */
981 #define NUM_BUFFERS_DELAY(_v)   (unsigned int) (voice->output_rate * fluid_tc2sec_delay(_v) / FLUID_BUFSIZE)
982 #define NUM_BUFFERS_ATTACK(_v)  (unsigned int) (voice->output_rate * fluid_tc2sec_attack(_v) / FLUID_BUFSIZE)
983 #define NUM_BUFFERS_RELEASE(_v) (unsigned int) (voice->output_rate * fluid_tc2sec_release(_v) / FLUID_BUFSIZE)
984 
985     /* volume envelope
986      *
987      * - delay and hold times are converted to absolute number of samples
988      * - sustain is converted to its absolute value
989      * - attack, decay and release are converted to their increment per sample
990      */
991   case GEN_VOLENVDELAY:                /* SF2.01 section 8.1.3 # 33 */
992     x = _GEN(voice, GEN_VOLENVDELAY);
993     fluid_clip(x, -12000.0f, 5000.0f);
994     count = NUM_BUFFERS_DELAY(x);
995     fluid_voice_update_volenv(voice, FLUID_VOICE_ENVDELAY,
996                             count, 0.0f, 0.0f, -1.0f, 1.0f);
997     break;
998 
999   case GEN_VOLENVATTACK:               /* SF2.01 section 8.1.3 # 34 */
1000     x = _GEN(voice, GEN_VOLENVATTACK);
1001     fluid_clip(x, -12000.0f, 8000.0f);
1002     count = 1 + NUM_BUFFERS_ATTACK(x);
1003     fluid_voice_update_volenv(voice, FLUID_VOICE_ENVATTACK,
1004                             count, 1.0f, count ? 1.0f / count : 0.0f, -1.0f, 1.0f);
1005     break;
1006 
1007   case GEN_VOLENVHOLD:                 /* SF2.01 section 8.1.3 # 35 */
1008   case GEN_KEYTOVOLENVHOLD:            /* SF2.01 section 8.1.3 # 39 */
1009     count = calculate_hold_decay_buffers(voice, GEN_VOLENVHOLD, GEN_KEYTOVOLENVHOLD, 0); /* 0 means: hold */
1010     fluid_voice_update_volenv(voice, FLUID_VOICE_ENVHOLD,
1011                             count, 1.0f, 0.0f, -1.0f, 2.0f);
1012     break;
1013 
1014   case GEN_VOLENVDECAY:               /* SF2.01 section 8.1.3 # 36 */
1015   case GEN_VOLENVSUSTAIN:             /* SF2.01 section 8.1.3 # 37 */
1016   case GEN_KEYTOVOLENVDECAY:          /* SF2.01 section 8.1.3 # 40 */
1017     y = 1.0f - 0.001f * _GEN(voice, GEN_VOLENVSUSTAIN);
1018     fluid_clip(y, 0.0f, 1.0f);
1019     count = calculate_hold_decay_buffers(voice, GEN_VOLENVDECAY, GEN_KEYTOVOLENVDECAY, 1); /* 1 for decay */
1020     fluid_voice_update_volenv(voice, FLUID_VOICE_ENVDECAY,
1021                             count, 1.0f, count ? -1.0f / count : 0.0f, y, 2.0f);
1022     break;
1023 
1024   case GEN_VOLENVRELEASE:             /* SF2.01 section 8.1.3 # 38 */
1025     x = _GEN(voice, GEN_VOLENVRELEASE);
1026     fluid_clip(x, FLUID_MIN_VOLENVRELEASE, 8000.0f);
1027     count = 1 + NUM_BUFFERS_RELEASE(x);
1028     fluid_voice_update_volenv(voice, FLUID_VOICE_ENVRELEASE,
1029                             count, 1.0f, count ? -1.0f / count : 0.0f, 0.0f, 1.0f);
1030     break;
1031 
1032     /* Modulation envelope */
1033   case GEN_MODENVDELAY:               /* SF2.01 section 8.1.3 # 25 */
1034     x = _GEN(voice, GEN_MODENVDELAY);
1035     fluid_clip(x, -12000.0f, 5000.0f);
1036     fluid_voice_update_modenv(voice, FLUID_VOICE_ENVDELAY,
1037                             NUM_BUFFERS_DELAY(x), 0.0f, 0.0f, -1.0f, 1.0f);
1038     break;
1039 
1040   case GEN_MODENVATTACK:               /* SF2.01 section 8.1.3 # 26 */
1041     x = _GEN(voice, GEN_MODENVATTACK);
1042     fluid_clip(x, -12000.0f, 8000.0f);
1043     count = 1 + NUM_BUFFERS_ATTACK(x);
1044     fluid_voice_update_modenv(voice, FLUID_VOICE_ENVATTACK,
1045                             count, 1.0f, count ? 1.0f / count : 0.0f, -1.0f, 1.0f);
1046     break;
1047 
1048   case GEN_MODENVHOLD:               /* SF2.01 section 8.1.3 # 27 */
1049   case GEN_KEYTOMODENVHOLD:          /* SF2.01 section 8.1.3 # 31 */
1050     count = calculate_hold_decay_buffers(voice, GEN_MODENVHOLD, GEN_KEYTOMODENVHOLD, 0); /* 1 means: hold */
1051     fluid_voice_update_modenv(voice, FLUID_VOICE_ENVHOLD,
1052                             count, 1.0f, 0.0f, -1.0f, 2.0f);
1053     break;
1054 
1055   case GEN_MODENVDECAY:                                   /* SF 2.01 section 8.1.3 # 28 */
1056   case GEN_MODENVSUSTAIN:                                 /* SF 2.01 section 8.1.3 # 29 */
1057   case GEN_KEYTOMODENVDECAY:                              /* SF 2.01 section 8.1.3 # 32 */
1058     count = calculate_hold_decay_buffers(voice, GEN_MODENVDECAY, GEN_KEYTOMODENVDECAY, 1); /* 1 for decay */
1059     y = 1.0f - 0.001f * _GEN(voice, GEN_MODENVSUSTAIN);
1060     fluid_clip(y, 0.0f, 1.0f);
1061     fluid_voice_update_modenv(voice, FLUID_VOICE_ENVDECAY,
1062                             count, 1.0f, count ? -1.0f / count : 0.0f, y, 2.0f);
1063     break;
1064 
1065   case GEN_MODENVRELEASE:                                  /* SF 2.01 section 8.1.3 # 30 */
1066     x = _GEN(voice, GEN_MODENVRELEASE);
1067     fluid_clip(x, -12000.0f, 8000.0f);
1068     count = 1 + NUM_BUFFERS_RELEASE(x);
1069     fluid_voice_update_modenv(voice, FLUID_VOICE_ENVRELEASE,
1070                             count, 1.0f, count ? -1.0f / count : 0.0f, 0.0f, 2.0f);
1071 
1072     break;
1073 
1074   } /* switch gen */
1075 }
1076 
1077 /**
1078  * Recalculate voice parameters for a given control.
1079  * @param voice the synthesis voice
1080  * @param cc flag to distinguish between a continous control and a channel control (pitch bend, ...)
1081  * @param ctrl the control number
1082  *
1083  * In this implementation, I want to make sure that all controllers
1084  * are event based: the parameter values of the DSP algorithm should
1085  * only be updates when a controller event arrived and not at every
1086  * iteration of the audio cycle (which would probably be feasible if
1087  * the synth was made in silicon).
1088  *
1089  * The update is done in three steps:
1090  *
1091  * - first, we look for all the modulators that have the changed
1092  * controller as a source. This will yield a list of generators that
1093  * will be changed because of the controller event.
1094  *
1095  * - For every changed generator, calculate its new value. This is the
1096  * sum of its original value plus the values of al the attached
1097  * modulators.
1098  *
1099  * - For every changed generator, convert its value to the correct
1100  * unit of the corresponding DSP parameter
1101  */
fluid_voice_modulate(fluid_voice_t * voice,int cc,int ctrl)1102 int fluid_voice_modulate(fluid_voice_t* voice, int cc, int ctrl)
1103 {
1104   int i, k;
1105   fluid_mod_t* mod;
1106   int gen;
1107   fluid_real_t modval;
1108 
1109 /*    printf("Chan=%d, CC=%d, Src=%d, Val=%d\n", voice->channel->channum, cc, ctrl, val); */
1110 
1111   for (i = 0; i < voice->mod_count; i++) {
1112 
1113     mod = &voice->mod[i];
1114 
1115     /* step 1: find all the modulators that have the changed controller
1116      * as input source. */
1117     if (fluid_mod_has_source(mod, cc, ctrl)) {
1118 
1119       gen = fluid_mod_get_dest(mod);
1120       modval = 0.0;
1121 
1122       /* step 2: for every changed modulator, calculate the modulation
1123        * value of its associated generator */
1124       for (k = 0; k < voice->mod_count; k++) {
1125 	if (fluid_mod_has_dest(&voice->mod[k], gen)) {
1126 	  modval += fluid_mod_get_value(&voice->mod[k], voice->channel, voice);
1127 	}
1128       }
1129 
1130       fluid_gen_set_mod(&voice->gen[gen], modval);
1131 
1132       /* step 3: now that we have the new value of the generator,
1133        * recalculate the parameter values that are derived from the
1134        * generator */
1135       fluid_voice_update_param(voice, gen);
1136     }
1137   }
1138   return FLUID_OK;
1139 }
1140 
1141 /**
1142  * Update all the modulators. This function is called after a
1143  * ALL_CTRL_OFF MIDI message has been received (CC 121).
1144  *
1145  */
fluid_voice_modulate_all(fluid_voice_t * voice)1146 int fluid_voice_modulate_all(fluid_voice_t* voice)
1147 {
1148   fluid_mod_t* mod;
1149   int i, k, gen;
1150   fluid_real_t modval;
1151 
1152   /* Loop through all the modulators.
1153 
1154      FIXME: we should loop through the set of generators instead of
1155      the set of modulators. We risk to call 'fluid_voice_update_param'
1156      several times for the same generator if several modulators have
1157      that generator as destination. It's not an error, just a wast of
1158      energy (think polution, global warming, unhappy musicians,
1159      ...) */
1160 
1161   for (i = 0; i < voice->mod_count; i++) {
1162 
1163     mod = &voice->mod[i];
1164     gen = fluid_mod_get_dest(mod);
1165     modval = 0.0;
1166 
1167     /* Accumulate the modulation values of all the modulators with
1168      * destination generator 'gen' */
1169     for (k = 0; k < voice->mod_count; k++) {
1170       if (fluid_mod_has_dest(&voice->mod[k], gen)) {
1171 	modval += fluid_mod_get_value(&voice->mod[k], voice->channel, voice);
1172       }
1173     }
1174 
1175     fluid_gen_set_mod(&voice->gen[gen], modval);
1176 
1177     /* Update the parameter values that are depend on the generator
1178      * 'gen' */
1179     fluid_voice_update_param(voice, gen);
1180   }
1181 
1182   return FLUID_OK;
1183 }
1184 
1185 /*
1186  Force the voice into release stage. Useful anywhere a voice
1187  needs to be damped even if pedals (sustain sostenuto) are depressed.
1188  See fluid_synth_damp_voices_by_sustain_LOCAL(),
1189  fluid_synth_damp_voices_by_sostenuto_LOCAL,
1190  fluid_voice_noteoff().
1191 */
1192 void
fluid_voice_release(fluid_voice_t * voice)1193 fluid_voice_release(fluid_voice_t* voice)
1194 {
1195     unsigned int at_tick = fluid_channel_get_min_note_length_ticks (voice->channel);
1196     UPDATE_RVOICE_I1(fluid_rvoice_noteoff, at_tick);
1197     voice->has_noteoff = 1; // voice is marked as noteoff occured
1198 }
1199 
1200 /*
1201  * fluid_voice_noteoff
1202  */
1203 int
fluid_voice_noteoff(fluid_voice_t * voice)1204 fluid_voice_noteoff(fluid_voice_t* voice)
1205 {
1206   fluid_channel_t* channel;
1207 
1208   fluid_profile(FLUID_PROF_VOICE_NOTE, voice->ref);
1209 
1210   channel = voice->channel;
1211 
1212   /* Sustain a note under Sostenuto pedal */
1213   if (fluid_channel_sostenuto(channel) &&
1214       channel->sostenuto_orderid > voice->id)
1215   { // Sostenuto depressed after note
1216     voice->status = FLUID_VOICE_HELD_BY_SOSTENUTO;
1217   }
1218   /* Or sustain a note under Sustain pedal */
1219   else if (fluid_channel_sustained(channel)) {
1220      voice->status = FLUID_VOICE_SUSTAINED;
1221   }
1222   /* Or force the voice to release stage */
1223   else
1224     fluid_voice_release(voice);
1225 
1226   return FLUID_OK;
1227 }
1228 
1229 /*
1230  * fluid_voice_kill_excl
1231  *
1232  * Percussion sounds can be mutually exclusive: for example, a 'closed
1233  * hihat' sound will terminate an 'open hihat' sound ringing at the
1234  * same time. This behaviour is modeled using 'exclusive classes',
1235  * turning on a voice with an exclusive class other than 0 will kill
1236  * all other voices having that exclusive class within the same preset
1237  * or channel.  fluid_voice_kill_excl gets called, when 'voice' is to
1238  * be killed for that reason.
1239  */
1240 
1241 int
fluid_voice_kill_excl(fluid_voice_t * voice)1242 fluid_voice_kill_excl(fluid_voice_t* voice){
1243 
1244   unsigned int at_tick;
1245 
1246   if (!_PLAYING(voice)) {
1247     return FLUID_OK;
1248   }
1249 
1250   /* Turn off the exclusive class information for this voice,
1251      so that it doesn't get killed twice
1252   */
1253   fluid_voice_gen_set(voice, GEN_EXCLUSIVECLASS, 0);
1254 
1255   /* Speed up the volume envelope */
1256   /* The value was found through listening tests with hi-hat samples. */
1257   fluid_voice_gen_set(voice, GEN_VOLENVRELEASE, -200);
1258   fluid_voice_update_param(voice, GEN_VOLENVRELEASE);
1259 
1260   /* Speed up the modulation envelope */
1261   fluid_voice_gen_set(voice, GEN_MODENVRELEASE, -200);
1262   fluid_voice_update_param(voice, GEN_MODENVRELEASE);
1263 
1264   at_tick = fluid_channel_get_min_note_length_ticks (voice->channel);
1265   UPDATE_RVOICE_I1(fluid_rvoice_noteoff, at_tick);
1266 
1267 
1268   return FLUID_OK;
1269 }
1270 
1271 /*
1272  * Called by fluid_synth when the overflow rvoice can be reclaimed.
1273  */
fluid_voice_overflow_rvoice_finished(fluid_voice_t * voice)1274 void fluid_voice_overflow_rvoice_finished(fluid_voice_t* voice)
1275 {
1276   voice->can_access_overflow_rvoice = 1;
1277   fluid_sample_null_ptr(&voice->overflow_rvoice->dsp.sample);
1278 }
1279 
1280 
1281 /*
1282  * fluid_voice_off
1283  *
1284  * Purpose:
1285  * Turns off a voice, meaning that it is not processed
1286  * anymore by the DSP loop.
1287  */
1288 int
fluid_voice_off(fluid_voice_t * voice)1289 fluid_voice_off(fluid_voice_t* voice)
1290 {
1291   fluid_profile(FLUID_PROF_VOICE_RELEASE, voice->ref);
1292 
1293   voice->chan = NO_CHANNEL;
1294   UPDATE_RVOICE0(fluid_rvoice_voiceoff);
1295 
1296   if (voice->can_access_rvoice)
1297     fluid_sample_null_ptr(&voice->rvoice->dsp.sample);
1298 
1299   voice->status = FLUID_VOICE_OFF;
1300   voice->has_noteoff = 1;
1301 
1302   /* Decrement the reference count of the sample. */
1303   fluid_sample_null_ptr(&voice->sample);
1304 
1305   /* Decrement voice count */
1306   voice->channel->synth->active_voice_count--;
1307 
1308   return FLUID_OK;
1309 }
1310 
1311 /**
1312  * Adds a modulator to the voice.
1313  * @param voice Voice instance
1314  * @param mod Modulator info (copied)
1315  * @param mode Determines how to handle an existing identical modulator
1316  *   #FLUID_VOICE_ADD to add (offset) the modulator amounts,
1317  *   #FLUID_VOICE_OVERWRITE to replace the modulator,
1318  *   #FLUID_VOICE_DEFAULT when adding a default modulator - no duplicate should
1319  *   exist so don't check.
1320  */
1321 void
fluid_voice_add_mod(fluid_voice_t * voice,fluid_mod_t * mod,int mode)1322 fluid_voice_add_mod(fluid_voice_t* voice, fluid_mod_t* mod, int mode)
1323 {
1324   int i;
1325 
1326   /*
1327    * Some soundfonts come with a huge number of non-standard
1328    * controllers, because they have been designed for one particular
1329    * sound card.  Discard them, maybe print a warning.
1330    */
1331 
1332   if (((mod->flags1 & FLUID_MOD_CC) == 0)
1333       && ((mod->src1 != 0)          /* SF2.01 section 8.2.1: Constant value */
1334 	  && (mod->src1 != 2)       /* Note-on velocity */
1335 	  && (mod->src1 != 3)       /* Note-on key number */
1336 	  && (mod->src1 != 10)      /* Poly pressure */
1337 	  && (mod->src1 != 13)      /* Channel pressure */
1338 	  && (mod->src1 != 14)      /* Pitch wheel */
1339 	  && (mod->src1 != 16))) {  /* Pitch wheel sensitivity */
1340     FLUID_LOG(FLUID_WARN, "Ignoring invalid controller, using non-CC source %i.", mod->src1);
1341     return;
1342   }
1343 
1344   if (mode == FLUID_VOICE_ADD) {
1345 
1346     /* if identical modulator exists, add them */
1347     for (i = 0; i < voice->mod_count; i++) {
1348       if (fluid_mod_test_identity(&voice->mod[i], mod)) {
1349 	//		printf("Adding modulator...\n");
1350 	voice->mod[i].amount += mod->amount;
1351 	return;
1352       }
1353     }
1354 
1355   } else if (mode == FLUID_VOICE_OVERWRITE) {
1356 
1357     /* if identical modulator exists, replace it (only the amount has to be changed) */
1358     for (i = 0; i < voice->mod_count; i++) {
1359       if (fluid_mod_test_identity(&voice->mod[i], mod)) {
1360 	//		printf("Replacing modulator...amount is %f\n",mod->amount);
1361 	voice->mod[i].amount = mod->amount;
1362 	return;
1363       }
1364     }
1365   }
1366 
1367   /* Add a new modulator (No existing modulator to add / overwrite).
1368      Also, default modulators (FLUID_VOICE_DEFAULT) are added without
1369      checking, if the same modulator already exists. */
1370   if (voice->mod_count < FLUID_NUM_MOD) {
1371     fluid_mod_clone(&voice->mod[voice->mod_count++], mod);
1372   }
1373 }
1374 
1375 /**
1376  * Get the unique ID of the noteon-event.
1377  * @param voice Voice instance
1378  * @return Note on unique ID
1379  *
1380  * A SoundFont loader may store the voice processes it has created for
1381  * real-time control during the operation of a voice (for example: parameter
1382  * changes in SoundFont editor). The synth uses a pool of voices, which are
1383  * 'recycled' and never deallocated.
1384  *
1385  * Before modifying an existing voice, check
1386  * - that its state is still 'playing'
1387  * - that the ID is still the same
1388  *
1389  * Otherwise the voice has finished playing.
1390  */
fluid_voice_get_id(fluid_voice_t * voice)1391 unsigned int fluid_voice_get_id(fluid_voice_t* voice)
1392 {
1393   return voice->id;
1394 }
1395 
1396 /**
1397  * Check if a voice is still playing.
1398  * @param voice Voice instance
1399  * @return TRUE if playing, FALSE otherwise
1400  */
fluid_voice_is_playing(fluid_voice_t * voice)1401 int fluid_voice_is_playing(fluid_voice_t* voice)
1402 {
1403   return _PLAYING(voice);
1404 }
1405 
1406 /*
1407  * fluid_voice_get_lower_boundary_for_attenuation
1408  *
1409  * Purpose:
1410  *
1411  * A lower boundary for the attenuation (as in 'the minimum
1412  * attenuation of this voice, with volume pedals, modulators
1413  * etc. resulting in minimum attenuation, cannot fall below x cB) is
1414  * calculated.  This has to be called during fluid_voice_init, after
1415  * all modulators have been run on the voice once.  Also,
1416  * voice->attenuation has to be initialized.
1417  */
1418 static fluid_real_t
fluid_voice_get_lower_boundary_for_attenuation(fluid_voice_t * voice)1419 fluid_voice_get_lower_boundary_for_attenuation(fluid_voice_t* voice)
1420 {
1421   int i;
1422   fluid_mod_t* mod;
1423   fluid_real_t possible_att_reduction_cB=0;
1424   fluid_real_t lower_bound;
1425 
1426   for (i = 0; i < voice->mod_count; i++) {
1427     mod = &voice->mod[i];
1428 
1429     /* Modulator has attenuation as target and can change over time? */
1430     if ((mod->dest == GEN_ATTENUATION)
1431 	&& ((mod->flags1 & FLUID_MOD_CC) || (mod->flags2 & FLUID_MOD_CC))) {
1432 
1433       fluid_real_t current_val = fluid_mod_get_value(mod, voice->channel, voice);
1434       fluid_real_t v = fabs(mod->amount);
1435 
1436       if ((mod->src1 == FLUID_MOD_PITCHWHEEL)
1437 	  || (mod->flags1 & FLUID_MOD_BIPOLAR)
1438 	  || (mod->flags2 & FLUID_MOD_BIPOLAR)
1439 	  || (mod->amount < 0)) {
1440 	/* Can this modulator produce a negative contribution? */
1441 	v *= -1.0;
1442       } else {
1443 	/* No negative value possible. But still, the minimum contribution is 0. */
1444 	v = 0;
1445       }
1446 
1447       /* For example:
1448        * - current_val=100
1449        * - min_val=-4000
1450        * - possible_att_reduction_cB += 4100
1451        */
1452       if (current_val > v){
1453 	possible_att_reduction_cB += (current_val - v);
1454       }
1455     }
1456   }
1457 
1458   lower_bound = voice->attenuation-possible_att_reduction_cB;
1459 
1460   /* SF2.01 specs do not allow negative attenuation */
1461   if (lower_bound < 0) {
1462     lower_bound = 0;
1463   }
1464   return lower_bound;
1465 }
1466 
1467 
1468 
1469 
fluid_voice_set_param(fluid_voice_t * voice,int gen,fluid_real_t nrpn_value,int abs)1470 int fluid_voice_set_param(fluid_voice_t* voice, int gen, fluid_real_t nrpn_value, int abs)
1471 {
1472   voice->gen[gen].nrpn = nrpn_value;
1473   voice->gen[gen].flags = (abs)? GEN_ABS_NRPN : GEN_SET;
1474   fluid_voice_update_param(voice, gen);
1475   return FLUID_OK;
1476 }
1477 
fluid_voice_set_gain(fluid_voice_t * voice,fluid_real_t gain)1478 int fluid_voice_set_gain(fluid_voice_t* voice, fluid_real_t gain)
1479 {
1480   /* avoid division by zero*/
1481   if (gain < 0.0000001){
1482     gain = 0.0000001;
1483   }
1484 
1485   voice->synth_gain = gain;
1486   voice->amp_left = fluid_pan(voice->pan, 1) * gain / 32768.0f;
1487   voice->amp_right = fluid_pan(voice->pan, 0) * gain / 32768.0f;
1488   voice->amp_reverb = voice->reverb_send * gain / 32768.0f;
1489   voice->amp_chorus = voice->chorus_send * gain / 32768.0f;
1490 
1491   UPDATE_RVOICE_R1(fluid_rvoice_set_synth_gain, gain);
1492   UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_amp, 0, voice->amp_left);
1493   UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_amp, 1, voice->amp_right);
1494   UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_amp, 2, voice->amp_reverb);
1495   UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_amp, 3, voice->amp_chorus);
1496 
1497   return FLUID_OK;
1498 }
1499 
1500 /* - Scan the loop
1501  * - determine the peak level
1502  * - Calculate, what factor will make the loop inaudible
1503  * - Store in sample
1504  */
1505 /**
1506  * Calculate the peak volume of a sample for voice off optimization.
1507  * @param s Sample to optimize
1508  * @return #FLUID_OK on success, #FLUID_FAILED otherwise
1509  *
1510  * If the peak volume during the loop is known, then the voice can
1511  * be released earlier during the release phase. Otherwise, the
1512  * voice will operate (inaudibly), until the envelope is at the
1513  * nominal turnoff point.  So it's a good idea to call
1514  * fluid_voice_optimize_sample() on each sample once.
1515  */
1516 int
fluid_voice_optimize_sample(fluid_sample_t * s)1517 fluid_voice_optimize_sample(fluid_sample_t* s)
1518 {
1519   signed short peak_max = 0;
1520   signed short peak_min = 0;
1521   signed short peak;
1522   fluid_real_t normalized_amplitude_during_loop;
1523   double result;
1524   int i;
1525 
1526   /* ignore ROM and other(?) invalid samples */
1527   if (!s->valid) return (FLUID_OK);
1528 
1529   if (!s->amplitude_that_reaches_noise_floor_is_valid){ /* Only once */
1530     /* Scan the loop */
1531     for (i = (int)s->loopstart; i < (int) s->loopend; i ++){
1532       signed short val = s->data[i];
1533       if (val > peak_max) {
1534 	peak_max = val;
1535       } else if (val < peak_min) {
1536 	peak_min = val;
1537       }
1538     }
1539 
1540     /* Determine the peak level */
1541     if (peak_max >- peak_min){
1542       peak = peak_max;
1543     } else {
1544       peak =- peak_min;
1545     };
1546     if (peak == 0){
1547       /* Avoid division by zero */
1548       peak = 1;
1549     };
1550 
1551     /* Calculate what factor will make the loop inaudible
1552      * For example: Take a peak of 3277 (10 % of 32768).  The
1553      * normalized amplitude is 0.1 (10 % of 32768).  An amplitude
1554      * factor of 0.0001 (as opposed to the default 0.00001) will
1555      * drop this sample to the noise floor.
1556      */
1557 
1558     /* 16 bits => 96+4=100 dB dynamic range => 0.00001 */
1559     normalized_amplitude_during_loop = ((fluid_real_t)peak)/32768.;
1560     result = FLUID_NOISE_FLOOR / normalized_amplitude_during_loop;
1561 
1562     /* Store in sample */
1563     s->amplitude_that_reaches_noise_floor = (double)result;
1564     s->amplitude_that_reaches_noise_floor_is_valid = 1;
1565 #if 0
1566     printf("Sample peak detection: factor %f\n", (double)result);
1567 #endif
1568   };
1569   return FLUID_OK;
1570 }
1571 
1572 fluid_real_t
fluid_voice_get_overflow_prio(fluid_voice_t * voice,fluid_overflow_prio_t * score,unsigned int cur_time)1573 fluid_voice_get_overflow_prio(fluid_voice_t* voice,
1574 			       fluid_overflow_prio_t* score,
1575 			       unsigned int cur_time)
1576 {
1577   fluid_real_t this_voice_prio = 0;
1578 
1579   /* Are we already overflowing? */
1580   if (!voice->can_access_overflow_rvoice) {
1581     return OVERFLOW_PRIO_CANNOT_KILL;
1582   }
1583 
1584   /* Is this voice on the drum channel?
1585    * Then it is very important.
1586    * Also skip the released and sustained scores.
1587    */
1588   if (voice->channel->channel_type == CHANNEL_TYPE_DRUM){
1589     this_voice_prio += score->percussion;
1590   }
1591   else if (voice->has_noteoff) {
1592     /* Noteoff has */
1593     this_voice_prio += score->released;
1594   } else if (_SUSTAINED(voice) || _HELD_BY_SOSTENUTO(voice)) {
1595     /* This voice is still active, since the sustain pedal is held down.
1596      * Consider it less important than non-sustained channels.
1597      * This decision is somehow subjective. But usually the sustain pedal
1598      * is used to play 'more-voices-than-fingers', so it shouldn't hurt
1599      * if we kill one voice.
1600      */
1601     this_voice_prio += score->sustained;
1602   }
1603 
1604   /* We are not enthusiastic about releasing voices, which have just been started.
1605    * Otherwise hitting a chord may result in killing notes belonging to that very same
1606    * chord. So give newer voices a higher score. */
1607   if (score->age) {
1608     cur_time -= voice->start_time;
1609     if (cur_time < 1)
1610       cur_time = 1; // Avoid div by zero
1611     this_voice_prio += (score->age * voice->output_rate) / cur_time;
1612   }
1613 
1614   /* take a rough estimate of loudness into account. Louder voices are more important. */
1615   if (score->volume) {
1616     fluid_real_t a = voice->attenuation;
1617     if (voice->has_noteoff) {
1618       // FIXME: Should take into account where on the envelope we are...?
1619     }
1620     if (a < 0.1)
1621       a = 0.1; // Avoid div by zero
1622       this_voice_prio += score->volume / a;
1623     }
1624 
1625   return this_voice_prio;
1626 }
1627