Update Fluidsynth to 2.0.1
[ardour.git] / libs / fluidsynth / src / fluid_voice.c
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 Lesser General Public License
7  * as published by the Free Software Foundation; either version 2.1 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  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser 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 #include "fluid_defsfont.h"
31
32 /* used for filter turn off optimization - if filter cutoff is above the
33    specified value and filter q is below the other value, turn filter off */
34 #define FLUID_MAX_AUDIBLE_FILTER_FC 19000.0f
35 #define FLUID_MIN_AUDIBLE_FILTER_Q 1.2f
36
37 /* min vol envelope release (to stop clicks) in SoundFont timecents */
38 #define FLUID_MIN_VOLENVRELEASE -7200.0f /* ~16ms */
39
40
41 static const int32_t INT24_MAX = (1 << (16 + 8 - 1));
42
43 static int fluid_voice_calculate_runtime_synthesis_parameters(fluid_voice_t *voice);
44 static int calculate_hold_decay_buffers(fluid_voice_t *voice, int gen_base,
45                                         int gen_key2base, int is_decay);
46 static fluid_real_t
47 fluid_voice_get_lower_boundary_for_attenuation(fluid_voice_t *voice);
48
49 #define UPDATE_RVOICE0(proc) \
50   do { \
51       fluid_rvoice_param_t param[MAX_EVENT_PARAMS]; \
52       fluid_rvoice_eventhandler_push(voice->eventhandler, proc, voice->rvoice, param); \
53   } while (0)
54
55 #define UPDATE_RVOICE_GENERIC_R1(proc, obj, rarg) \
56   do { \
57       fluid_rvoice_param_t param[MAX_EVENT_PARAMS]; \
58       param[0].real = rarg; \
59       fluid_rvoice_eventhandler_push(voice->eventhandler, proc, obj, param); \
60   } while (0)
61
62 #define UPDATE_RVOICE_GENERIC_I1(proc, obj, iarg) \
63   do { \
64       fluid_rvoice_param_t param[MAX_EVENT_PARAMS]; \
65       param[0].i = iarg; \
66       fluid_rvoice_eventhandler_push(voice->eventhandler, proc, obj, param); \
67   } while (0)
68
69 #define UPDATE_RVOICE_GENERIC_I2(proc, obj, iarg1, iarg2) \
70   do { \
71       fluid_rvoice_param_t param[MAX_EVENT_PARAMS]; \
72       param[0].i = iarg1; \
73       param[1].i = iarg2; \
74       fluid_rvoice_eventhandler_push(voice->eventhandler, proc, obj, param); \
75   } while (0)
76
77 #define UPDATE_RVOICE_GENERIC_IR(proc, obj, iarg, rarg) \
78   do { \
79       fluid_rvoice_param_t param[MAX_EVENT_PARAMS]; \
80       param[0].i = iarg; \
81       param[1].real = rarg; \
82       fluid_rvoice_eventhandler_push(voice->eventhandler, proc, obj, param); \
83   } while (0)
84
85
86 #define UPDATE_RVOICE_R1(proc, arg1) UPDATE_RVOICE_GENERIC_R1(proc, voice->rvoice, arg1)
87 #define UPDATE_RVOICE_I1(proc, arg1) UPDATE_RVOICE_GENERIC_I1(proc, voice->rvoice, arg1)
88
89 #define UPDATE_RVOICE_BUFFERS_AMP(proc, iarg, rarg) UPDATE_RVOICE_GENERIC_IR(proc, &voice->rvoice->buffers, iarg, rarg)
90 #define UPDATE_RVOICE_ENVLFO_R1(proc, envp, rarg) UPDATE_RVOICE_GENERIC_R1(proc, &voice->rvoice->envlfo.envp, rarg)
91 #define UPDATE_RVOICE_ENVLFO_I1(proc, envp, iarg) UPDATE_RVOICE_GENERIC_I1(proc, &voice->rvoice->envlfo.envp, iarg)
92
93 static FLUID_INLINE void
94 fluid_voice_update_volenv(fluid_voice_t *voice,
95                           int enqueue,
96                           fluid_adsr_env_section_t section,
97                           unsigned int count,
98                           fluid_real_t coeff,
99                           fluid_real_t increment,
100                           fluid_real_t min,
101                           fluid_real_t max)
102 {
103     fluid_rvoice_param_t param[MAX_EVENT_PARAMS];
104
105     param[0].i = section;
106     param[1].i = count;
107     param[2].real = coeff;
108     param[3].real = increment;
109     param[4].real = min;
110     param[5].real = max;
111
112     if(enqueue)
113     {
114         fluid_rvoice_eventhandler_push(voice->eventhandler,
115                                        fluid_adsr_env_set_data,
116                                        &voice->rvoice->envlfo.volenv,
117                                        param);
118     }
119     else
120     {
121         fluid_adsr_env_set_data(&voice->rvoice->envlfo.volenv, param);
122     }
123 }
124
125 static FLUID_INLINE void
126 fluid_voice_update_modenv(fluid_voice_t *voice,
127                           int enqueue,
128                           fluid_adsr_env_section_t section,
129                           unsigned int count,
130                           fluid_real_t coeff,
131                           fluid_real_t increment,
132                           fluid_real_t min,
133                           fluid_real_t max)
134 {
135     fluid_rvoice_param_t param[MAX_EVENT_PARAMS];
136
137     param[0].i = section;
138     param[1].i = count;
139     param[2].real = coeff;
140     param[3].real = increment;
141     param[4].real = min;
142     param[5].real = max;
143
144     if(enqueue)
145     {
146         fluid_rvoice_eventhandler_push(voice->eventhandler,
147                                        fluid_adsr_env_set_data,
148                                        &voice->rvoice->envlfo.modenv,
149                                        param);
150     }
151     else
152     {
153         fluid_adsr_env_set_data(&voice->rvoice->envlfo.modenv, param);
154     }
155 }
156
157 static FLUID_INLINE void fluid_voice_sample_unref(fluid_sample_t **sample)
158 {
159     if(*sample != NULL)
160     {
161         fluid_sample_decr_ref(*sample);
162         *sample = NULL;
163     }
164 }
165
166 /*
167  * Swaps the current rvoice with the current overflow_rvoice
168  */
169 static void fluid_voice_swap_rvoice(fluid_voice_t *voice)
170 {
171     fluid_rvoice_t *rtemp = voice->rvoice;
172     int ctemp = voice->can_access_rvoice;
173     voice->rvoice = voice->overflow_rvoice;
174     voice->can_access_rvoice = voice->can_access_overflow_rvoice;
175     voice->overflow_rvoice = rtemp;
176     voice->can_access_overflow_rvoice = ctemp;
177 }
178
179 static void fluid_voice_initialize_rvoice(fluid_voice_t *voice, fluid_real_t output_rate)
180 {
181     fluid_rvoice_param_t param[MAX_EVENT_PARAMS];
182
183     FLUID_MEMSET(voice->rvoice, 0, sizeof(fluid_rvoice_t));
184
185     /* The 'sustain' and 'finished' segments of the volume / modulation
186      * envelope are constant. They are never affected by any modulator
187      * or generator. Therefore it is enough to initialize them once
188      * during the lifetime of the synth.
189      */
190     fluid_voice_update_volenv(voice, FALSE, FLUID_VOICE_ENVSUSTAIN,
191                               0xffffffff, 1.0f, 0.0f, -1.0f, 2.0f);
192     fluid_voice_update_volenv(voice, FALSE, FLUID_VOICE_ENVFINISHED,
193                               0xffffffff, 0.0f, 0.0f, -1.0f, 1.0f);
194     fluid_voice_update_modenv(voice, FALSE, FLUID_VOICE_ENVSUSTAIN,
195                               0xffffffff, 1.0f, 0.0f, -1.0f, 2.0f);
196     fluid_voice_update_modenv(voice, FALSE, FLUID_VOICE_ENVFINISHED,
197                               0xffffffff, 0.0f, 0.0f, -1.0f, 1.0f);
198
199     param[0].i = FLUID_IIR_LOWPASS;
200     param[1].i = 0;
201     fluid_iir_filter_init(&voice->rvoice->resonant_filter, param);
202
203     param[0].i = FLUID_IIR_DISABLED;
204     fluid_iir_filter_init(&voice->rvoice->resonant_custom_filter, param);
205
206     param[0].real = output_rate;
207     fluid_rvoice_set_output_rate(voice->rvoice, param);
208 }
209
210 /*
211  * new_fluid_voice
212  */
213 fluid_voice_t *
214 new_fluid_voice(fluid_rvoice_eventhandler_t *handler, fluid_real_t output_rate)
215 {
216     fluid_voice_t *voice;
217     voice = FLUID_NEW(fluid_voice_t);
218
219     if(voice == NULL)
220     {
221         FLUID_LOG(FLUID_ERR, "Out of memory");
222         return NULL;
223     }
224
225     voice->can_access_rvoice = TRUE;
226     voice->can_access_overflow_rvoice = TRUE;
227
228     voice->rvoice = FLUID_NEW(fluid_rvoice_t);
229     voice->overflow_rvoice = FLUID_NEW(fluid_rvoice_t);
230
231     if(voice->rvoice == NULL || voice->overflow_rvoice == NULL)
232     {
233         FLUID_LOG(FLUID_ERR, "Out of memory");
234         delete_fluid_voice(voice);
235         return NULL;
236     }
237
238     voice->status = FLUID_VOICE_CLEAN;
239     voice->chan = NO_CHANNEL;
240     voice->key = 0;
241     voice->vel = 0;
242     voice->eventhandler = handler;
243     voice->channel = NULL;
244     voice->sample = NULL;
245     voice->output_rate = output_rate;
246
247     /* Initialize both the rvoice and overflow_rvoice */
248     fluid_voice_initialize_rvoice(voice, output_rate);
249     fluid_voice_swap_rvoice(voice);
250     fluid_voice_initialize_rvoice(voice, output_rate);
251
252     return voice;
253 }
254
255 /*
256  * delete_fluid_voice
257  */
258 void
259 delete_fluid_voice(fluid_voice_t *voice)
260 {
261     fluid_return_if_fail(voice != NULL);
262
263     if(!voice->can_access_rvoice || !voice->can_access_overflow_rvoice)
264     {
265         FLUID_LOG(FLUID_WARN, "Deleting voice %u which has locked rvoices!", voice->id);
266     }
267
268     FLUID_FREE(voice->overflow_rvoice);
269     FLUID_FREE(voice->rvoice);
270     FLUID_FREE(voice);
271 }
272
273 /* fluid_voice_init
274  *
275  * Initialize the synthesis process
276  * inst_zone, the Instrument Zone contains the sample, Keyrange,Velrange
277  * of the voice.
278  * When playing legato (n1,n2) in mono mode, n2 will use n1 voices
279  * as far as n2 still enters in Keyrange,Velrange of n1.
280  */
281 int
282 fluid_voice_init(fluid_voice_t *voice, fluid_sample_t *sample,
283                  fluid_zone_range_t *inst_zone_range,
284                  fluid_channel_t *channel, int key, int vel, unsigned int id,
285                  unsigned int start_time, fluid_real_t gain)
286 {
287     /* Note: The voice parameters will be initialized later, when the
288      * generators have been retrieved from the sound font. Here, only
289      * the 'working memory' of the voice (position in envelopes, history
290      * of IIR filters, position in sample etc) is initialized. */
291     int i;
292
293     if(!voice->can_access_rvoice)
294     {
295         if(voice->can_access_overflow_rvoice)
296         {
297             fluid_voice_swap_rvoice(voice);
298         }
299         else
300         {
301             FLUID_LOG(FLUID_ERR, "Internal error: Cannot access an rvoice in fluid_voice_init!");
302             return FLUID_FAILED;
303         }
304     }
305
306     /* We are now guaranteed to have access to the rvoice */
307
308     if(voice->sample)
309     {
310         fluid_voice_off(voice);
311     }
312
313     voice->zone_range = inst_zone_range; /* Instrument zone range for legato */
314     voice->id = id;
315     voice->chan = fluid_channel_get_num(channel);
316     voice->key = (unsigned char) key;
317     voice->vel = (unsigned char) vel;
318     voice->channel = channel;
319     voice->mod_count = 0;
320     voice->start_time = start_time;
321     voice->has_noteoff = 0;
322     UPDATE_RVOICE0(fluid_rvoice_reset);
323
324     /* Increment the reference count of the sample to prevent the
325        unloading of the soundfont while this voice is playing,
326        once for us and once for the rvoice. */
327     fluid_sample_incr_ref(sample);
328     fluid_rvoice_eventhandler_push_ptr(voice->eventhandler, fluid_rvoice_set_sample, voice->rvoice, sample);
329     fluid_sample_incr_ref(sample);
330     voice->sample = sample;
331
332     i = fluid_channel_get_interp_method(channel);
333     UPDATE_RVOICE_I1(fluid_rvoice_set_interp_method, i);
334
335     /* Set all the generators to their default value, according to SF
336      * 2.01 section 8.1.3 (page 48). The value of NRPN messages are
337      * copied from the channel to the voice's generators. The sound font
338      * loader overwrites them. The generator values are later converted
339      * into voice parameters in
340      * fluid_voice_calculate_runtime_synthesis_parameters.  */
341     fluid_gen_init(&voice->gen[0], channel);
342     UPDATE_RVOICE_I1(fluid_rvoice_set_samplemode, _SAMPLEMODE(voice));
343
344     voice->synth_gain = gain;
345
346     /* avoid division by zero later*/
347     if(voice->synth_gain < 0.0000001)
348     {
349         voice->synth_gain = 0.0000001;
350     }
351
352     UPDATE_RVOICE_R1(fluid_rvoice_set_synth_gain, voice->synth_gain);
353
354     /* Set up buffer mapping, should be done more flexible in the future. */
355     i = 2 * channel->synth->audio_groups;
356     i += (voice->chan % channel->synth->effects_groups) * channel->synth->effects_channels;
357     UPDATE_RVOICE_GENERIC_I2(fluid_rvoice_buffers_set_mapping, &voice->rvoice->buffers, 2, i + SYNTH_REVERB_CHANNEL);
358     UPDATE_RVOICE_GENERIC_I2(fluid_rvoice_buffers_set_mapping, &voice->rvoice->buffers, 3, i + SYNTH_CHORUS_CHANNEL);
359
360     i = 2 * (voice->chan % channel->synth->audio_groups);
361     UPDATE_RVOICE_GENERIC_I2(fluid_rvoice_buffers_set_mapping, &voice->rvoice->buffers, 0, i);
362     UPDATE_RVOICE_GENERIC_I2(fluid_rvoice_buffers_set_mapping, &voice->rvoice->buffers, 1, i + 1);
363
364     return FLUID_OK;
365 }
366
367
368 /**
369  * Update sample rate.
370  * @note If the voice is active, it will be turned off.
371  */
372 void
373 fluid_voice_set_output_rate(fluid_voice_t *voice, fluid_real_t value)
374 {
375     if(fluid_voice_is_playing(voice))
376     {
377         fluid_voice_off(voice);
378     }
379
380     voice->output_rate = value;
381     UPDATE_RVOICE_GENERIC_R1(fluid_rvoice_set_output_rate, voice->rvoice, value);
382     UPDATE_RVOICE_GENERIC_R1(fluid_rvoice_set_output_rate, voice->overflow_rvoice, value);
383 }
384
385
386 /**
387  * Set the value of a generator.
388  * @param voice Voice instance
389  * @param i Generator ID (#fluid_gen_type)
390  * @param val Generator value
391  */
392 void
393 fluid_voice_gen_set(fluid_voice_t *voice, int i, float val)
394 {
395     voice->gen[i].val = val;
396     voice->gen[i].flags = GEN_SET;
397
398     if(i == GEN_SAMPLEMODE)
399     {
400         UPDATE_RVOICE_I1(fluid_rvoice_set_samplemode, (int) val);
401     }
402 }
403
404 /**
405  * Offset the value of a generator.
406  * @param voice Voice instance
407  * @param i Generator ID (#fluid_gen_type)
408  * @param val Value to add to the existing value
409  */
410 void
411 fluid_voice_gen_incr(fluid_voice_t *voice, int i, float val)
412 {
413     voice->gen[i].val += val;
414     voice->gen[i].flags = GEN_SET;
415 }
416
417 /**
418  * Get the value of a generator.
419  * @param voice Voice instance
420  * @param gen Generator ID (#fluid_gen_type)
421  * @return Current generator value
422  */
423 float
424 fluid_voice_gen_get(fluid_voice_t *voice, int gen)
425 {
426     return voice->gen[gen].val;
427 }
428
429 fluid_real_t fluid_voice_gen_value(const fluid_voice_t *voice, int num)
430 {
431     /* This is an extension to the SoundFont standard. More
432      * documentation is available at the fluid_synth_set_gen2()
433      * function. */
434     if(voice->gen[num].flags == GEN_ABS_NRPN)
435     {
436         return (fluid_real_t) voice->gen[num].nrpn;
437     }
438     else
439     {
440         return (fluid_real_t)(voice->gen[num].val + voice->gen[num].mod + voice->gen[num].nrpn);
441     }
442 }
443
444 /*
445  * fluid_voice_start
446  */
447 void fluid_voice_start(fluid_voice_t *voice)
448 {
449     /* The maximum volume of the loop is calculated and cached once for each
450      * sample with its nominal loop settings. This happens, when the sample is used
451      * for the first time.*/
452
453     fluid_voice_calculate_runtime_synthesis_parameters(voice);
454
455 #ifdef WITH_PROFILING
456     voice->ref = fluid_profile_ref();
457 #endif
458
459     voice->status = FLUID_VOICE_ON;
460
461     /* Increment voice count */
462     voice->channel->synth->active_voice_count++;
463 }
464
465 /**
466  * Calculate the amplitude of a voice.
467  *
468  * @param gain The gain value in the range [0.0 ; 1.0]
469  * @return An amplitude used by rvoice_mixer's buffers
470  */
471 static FLUID_INLINE fluid_real_t
472 fluid_voice_calculate_gain_amplitude(const fluid_voice_t *voice, fluid_real_t gain)
473 {
474     /* we use 24bit samples in fluid_rvoice_dsp. in order to normalize float
475      * samples to [0.0;1.0] divide samples by the max. value of an int24 and
476      * amplify them with the gain */
477     return gain * voice->synth_gain / (INT24_MAX * 1.0f);
478 }
479
480 /* Useful to return the nominal pitch of a key */
481 /* The nominal pitch is dependant of voice->root_pitch,tuning, and
482    GEN_SCALETUNE generator.
483    This is useful to set the value of GEN_PITCH generator on noteOn.
484    This is useful to get the beginning/ending pitch for portamento.
485 */
486 fluid_real_t fluid_voice_calculate_pitch(fluid_voice_t *voice, int key)
487 {
488     fluid_tuning_t *tuning;
489     fluid_real_t x, pitch;
490
491     /* Now the nominal pitch of the key is returned.
492      * Note about SCALETUNE: SF2.01 8.1.3 says, that this generator is a
493      * non-realtime parameter. So we don't allow modulation (as opposed
494      * to fluid_voice_gen_value(voice, GEN_SCALETUNE) When the scale tuning is varied,
495      * one key remains fixed. Here C3 (MIDI number 60) is used.
496      */
497     if(fluid_channel_has_tuning(voice->channel))
498     {
499         tuning = fluid_channel_get_tuning(voice->channel);
500         x = fluid_tuning_get_pitch(tuning, (int)(voice->root_pitch / 100.0f));
501         pitch = voice->gen[GEN_SCALETUNE].val / 100.0f *
502                 (fluid_tuning_get_pitch(tuning, key) - x) + x;
503     }
504     else
505     {
506         pitch = voice->gen[GEN_SCALETUNE].val
507                 * (key - voice->root_pitch / 100.0f) + voice->root_pitch;
508     }
509
510     return pitch;
511 }
512
513 void
514 fluid_voice_calculate_gen_pitch(fluid_voice_t *voice)
515 {
516     voice->gen[GEN_PITCH].val = fluid_voice_calculate_pitch(voice, fluid_voice_get_actual_key(voice));
517 }
518
519
520 /*
521  * fluid_voice_calculate_runtime_synthesis_parameters
522  *
523  * in this function we calculate the values of all the parameters. the
524  * parameters are converted to their most useful unit for the DSP
525  * algorithm, for example, number of samples instead of
526  * timecents. Some parameters keep their "perceptual" unit and
527  * conversion will be done in the DSP function. This is the case, for
528  * example, for the pitch since it is modulated by the controllers in
529  * cents. */
530 static int
531 fluid_voice_calculate_runtime_synthesis_parameters(fluid_voice_t *voice)
532 {
533     int i;
534     unsigned int n;
535
536     static int const list_of_generators_to_initialize[] =
537     {
538         GEN_STARTADDROFS,                    /* SF2.01 page 48 #0   */
539         GEN_ENDADDROFS,                      /*                #1   */
540         GEN_STARTLOOPADDROFS,                /*                #2   */
541         GEN_ENDLOOPADDROFS,                  /*                #3   */
542         /* GEN_STARTADDRCOARSEOFS see comment below [1]        #4   */
543         GEN_MODLFOTOPITCH,                   /*                #5   */
544         GEN_VIBLFOTOPITCH,                   /*                #6   */
545         GEN_MODENVTOPITCH,                   /*                #7   */
546         GEN_FILTERFC,                        /*                #8   */
547         GEN_FILTERQ,                         /*                #9   */
548         GEN_MODLFOTOFILTERFC,                /*                #10  */
549         GEN_MODENVTOFILTERFC,                /*                #11  */
550         /* GEN_ENDADDRCOARSEOFS [1]                            #12  */
551         GEN_MODLFOTOVOL,                     /*                #13  */
552         /* not defined                                         #14  */
553         GEN_CHORUSSEND,                      /*                #15  */
554         GEN_REVERBSEND,                      /*                #16  */
555         GEN_PAN,                             /*                #17  */
556         /* not defined                                         #18  */
557         /* not defined                                         #19  */
558         /* not defined                                         #20  */
559         GEN_MODLFODELAY,                     /*                #21  */
560         GEN_MODLFOFREQ,                      /*                #22  */
561         GEN_VIBLFODELAY,                     /*                #23  */
562         GEN_VIBLFOFREQ,                      /*                #24  */
563         GEN_MODENVDELAY,                     /*                #25  */
564         GEN_MODENVATTACK,                    /*                #26  */
565         GEN_MODENVHOLD,                      /*                #27  */
566         GEN_MODENVDECAY,                     /*                #28  */
567         /* GEN_MODENVSUSTAIN [1]                               #29  */
568         GEN_MODENVRELEASE,                   /*                #30  */
569         /* GEN_KEYTOMODENVHOLD [1]                             #31  */
570         /* GEN_KEYTOMODENVDECAY [1]                            #32  */
571         GEN_VOLENVDELAY,                     /*                #33  */
572         GEN_VOLENVATTACK,                    /*                #34  */
573         GEN_VOLENVHOLD,                      /*                #35  */
574         GEN_VOLENVDECAY,                     /*                #36  */
575         /* GEN_VOLENVSUSTAIN [1]                               #37  */
576         GEN_VOLENVRELEASE,                   /*                #38  */
577         /* GEN_KEYTOVOLENVHOLD [1]                             #39  */
578         /* GEN_KEYTOVOLENVDECAY [1]                            #40  */
579         /* GEN_STARTLOOPADDRCOARSEOFS [1]                      #45  */
580         GEN_KEYNUM,                          /*                #46  */
581         GEN_VELOCITY,                        /*                #47  */
582         GEN_ATTENUATION,                     /*                #48  */
583         /* GEN_ENDLOOPADDRCOARSEOFS [1]                        #50  */
584         /* GEN_COARSETUNE           [1]                        #51  */
585         /* GEN_FINETUNE             [1]                        #52  */
586         GEN_OVERRIDEROOTKEY,                 /*                #58  */
587         GEN_PITCH,                           /*                ---  */
588         GEN_CUSTOM_BALANCE,                  /*                ---  */
589         GEN_CUSTOM_FILTERFC,                 /*                ---  */
590         GEN_CUSTOM_FILTERQ                   /*                ---  */
591     };
592
593     /* When the voice is made ready for the synthesis process, a lot of
594      * voice-internal parameters have to be calculated.
595      *
596      * At this point, the sound font has already set the -nominal- value
597      * for all generators (excluding GEN_PITCH). Most generators can be
598      * modulated - they include a nominal value and an offset (which
599      * changes with velocity, note number, channel parameters like
600      * aftertouch, mod wheel...) Now this offset will be calculated as
601      * follows:
602      *
603      *  - Process each modulator once.
604      *  - Calculate its output value.
605      *  - Find the target generator.
606      *  - Add the output value to the modulation value of the generator.
607      *
608      * Note: The generators have been initialized with
609      * fluid_gen_set_default_values.
610      */
611
612     for(i = 0; i < voice->mod_count; i++)
613     {
614         fluid_mod_t *mod = &voice->mod[i];
615         fluid_real_t modval = fluid_mod_get_value(mod, voice);
616         int dest_gen_index = mod->dest;
617         fluid_gen_t *dest_gen = &voice->gen[dest_gen_index];
618         dest_gen->mod += modval;
619         /*      fluid_dump_modulator(mod); */
620     }
621
622     /* Now the generators are initialized, nominal and modulation value.
623      * The voice parameters (which depend on generators) are calculated
624      * with fluid_voice_update_param. Processing the list of generator
625      * changes will calculate each voice parameter once.
626      *
627      * Note [1]: Some voice parameters depend on several generators. For
628      * example, the pitch depends on GEN_COARSETUNE, GEN_FINETUNE and
629      * GEN_PITCH.  voice->pitch.  Unnecessary recalculation is avoided
630      * by removing all but one generator from the list of voice
631      * parameters.  Same with GEN_XXX and GEN_XXXCOARSE: the
632      * initialisation list contains only GEN_XXX.
633      */
634
635     /* Calculate the voice parameter(s) dependent on each generator. */
636     for(n = 0; n < FLUID_N_ELEMENTS(list_of_generators_to_initialize); n++)
637     {
638         fluid_voice_update_param(voice, list_of_generators_to_initialize[n]);
639     }
640
641     /* Start portamento if enabled */
642     {
643         /* fromkey note comes from "GetFromKeyPortamentoLegato()" detector.
644         When fromkey is set to ValidNote , portamento is started */
645         /* Return fromkey portamento */
646         int fromkey = voice->channel->synth->fromkey_portamento;
647
648         if(fluid_channel_is_valid_note(fromkey))
649         {
650             /* Send portamento parameters to the voice dsp */
651             fluid_voice_update_portamento(voice, fromkey, fluid_voice_get_actual_key(voice));
652         }
653     }
654
655     /* Make an estimate on how loud this voice can get at any time (attenuation). */
656     UPDATE_RVOICE_R1(fluid_rvoice_set_min_attenuation_cB,
657                      fluid_voice_get_lower_boundary_for_attenuation(voice));
658     return FLUID_OK;
659 }
660
661 /*
662  * calculate_hold_decay_buffers
663  */
664 static int
665 calculate_hold_decay_buffers(fluid_voice_t *voice, int gen_base,
666                              int gen_key2base, int is_decay)
667 {
668     /* Purpose:
669      *
670      * Returns the number of DSP loops, that correspond to the hold
671      * (is_decay=0) or decay (is_decay=1) time.
672      * gen_base=GEN_VOLENVHOLD, GEN_VOLENVDECAY, GEN_MODENVHOLD,
673      * GEN_MODENVDECAY gen_key2base=GEN_KEYTOVOLENVHOLD,
674      * GEN_KEYTOVOLENVDECAY, GEN_KEYTOMODENVHOLD, GEN_KEYTOMODENVDECAY
675      */
676
677     fluid_real_t timecents;
678     fluid_real_t seconds;
679     int buffers;
680
681     /* SF2.01 section 8.4.3 # 31, 32, 39, 40
682      * GEN_KEYTOxxxENVxxx uses key 60 as 'origin'.
683      * The unit of the generator is timecents per key number.
684      * If KEYTOxxxENVxxx is 100, a key one octave over key 60 (72)
685      * will cause (60-72)*100=-1200 timecents of time variation.
686      * The time is cut in half.
687      */
688     timecents = (fluid_voice_gen_value(voice, gen_base) + fluid_voice_gen_value(voice, gen_key2base) * (60.0 - fluid_voice_get_actual_key(voice)));
689
690     /* Range checking */
691     if(is_decay)
692     {
693         /* SF 2.01 section 8.1.3 # 28, 36 */
694         if(timecents > 8000.0)
695         {
696             timecents = 8000.0;
697         }
698     }
699     else
700     {
701         /* SF 2.01 section 8.1.3 # 27, 35 */
702         if(timecents > 5000)
703         {
704             timecents = 5000.0;
705         }
706
707         /* SF 2.01 section 8.1.2 # 27, 35:
708          * The most negative number indicates no hold time
709          */
710         if(timecents <= -32768.)
711         {
712             return 0;
713         }
714     }
715
716     /* SF 2.01 section 8.1.3 # 27, 28, 35, 36 */
717     if(timecents < -12000.0)
718     {
719         timecents = -12000.0;
720     }
721
722     seconds = fluid_tc2sec(timecents);
723     /* Each DSP loop processes FLUID_BUFSIZE samples. */
724
725     /* round to next full number of buffers */
726     buffers = (int)(((fluid_real_t)voice->output_rate * seconds)
727                     / (fluid_real_t)FLUID_BUFSIZE
728                     + 0.5);
729
730     return buffers;
731 }
732
733 /*
734  * The value of a generator (gen) has changed.  (The different
735  * generators are listed in fluidsynth.h, or in SF2.01 page 48-49)
736  * Now the dependent 'voice' parameters are calculated.
737  *
738  * fluid_voice_update_param can be called during the setup of the
739  * voice (to calculate the initial value for a voice parameter), or
740  * during its operation (a generator has been changed due to
741  * real-time parameter modifications like pitch-bend).
742  *
743  * Note: The generator holds three values: The base value .val, an
744  * offset caused by modulators .mod, and an offset caused by the
745  * NRPN system. fluid_voice_gen_value(voice, generator_enumerator) returns the sum
746  * of all three.
747  */
748 /**
749  * Update all the synthesis parameters, which depend on generator \a gen.
750  * @param voice Voice instance
751  * @param gen Generator id (#fluid_gen_type)
752  *
753  * This is only necessary after changing a generator of an already operating voice.
754  * Most applications will not need this function.
755  */
756 void
757 fluid_voice_update_param(fluid_voice_t *voice, int gen)
758 {
759     unsigned int count, z;
760     fluid_real_t x = fluid_voice_gen_value(voice, gen);
761
762     switch(gen)
763     {
764
765     case GEN_PAN:
766     case GEN_CUSTOM_BALANCE:
767         /* range checking is done in the fluid_pan and fluid_balance functions */
768         voice->pan = fluid_voice_gen_value(voice, GEN_PAN);
769         voice->balance = fluid_voice_gen_value(voice, GEN_CUSTOM_BALANCE);
770
771         /* left amp */
772         UPDATE_RVOICE_BUFFERS_AMP(fluid_rvoice_buffers_set_amp, 0,
773                                   fluid_voice_calculate_gain_amplitude(voice,
774                                           fluid_pan(voice->pan, 1) * fluid_balance(voice->balance, 1)));
775
776         /* right amp */
777         UPDATE_RVOICE_BUFFERS_AMP(fluid_rvoice_buffers_set_amp, 1,
778                                   fluid_voice_calculate_gain_amplitude(voice,
779                                           fluid_pan(voice->pan, 0) * fluid_balance(voice->balance, 0)));
780         break;
781
782     case GEN_ATTENUATION:
783         voice->attenuation = x;
784
785         /* Range: SF2.01 section 8.1.3 # 48
786          * Motivation for range checking:
787          * OHPiano.SF2 sets initial attenuation to a whooping -96 dB */
788         fluid_clip(voice->attenuation, 0.0, 1440.0);
789         UPDATE_RVOICE_R1(fluid_rvoice_set_attenuation, voice->attenuation);
790         break;
791
792     /* The pitch is calculated from three different generators.
793      * Read comment in fluidsynth.h about GEN_PITCH.
794      */
795     case GEN_PITCH:
796     case GEN_COARSETUNE:
797     case GEN_FINETUNE:
798         /* The testing for allowed range is done in 'fluid_ct2hz' */
799         voice->pitch = (fluid_voice_gen_value(voice, GEN_PITCH)
800                         + 100.0f * fluid_voice_gen_value(voice, GEN_COARSETUNE)
801                         + fluid_voice_gen_value(voice, GEN_FINETUNE));
802         UPDATE_RVOICE_R1(fluid_rvoice_set_pitch, voice->pitch);
803         break;
804
805     case GEN_REVERBSEND:
806         /* The generator unit is 'tenths of a percent'. */
807         voice->reverb_send = x / 1000.0f;
808         fluid_clip(voice->reverb_send, 0.0, 1.0);
809         UPDATE_RVOICE_BUFFERS_AMP(fluid_rvoice_buffers_set_amp, 2, fluid_voice_calculate_gain_amplitude(voice, voice->reverb_send));
810         break;
811
812     case GEN_CHORUSSEND:
813         /* The generator unit is 'tenths of a percent'. */
814         voice->chorus_send = x / 1000.0f;
815         fluid_clip(voice->chorus_send, 0.0, 1.0);
816         UPDATE_RVOICE_BUFFERS_AMP(fluid_rvoice_buffers_set_amp, 3, fluid_voice_calculate_gain_amplitude(voice, voice->chorus_send));
817         break;
818
819     case GEN_OVERRIDEROOTKEY:
820
821         /* This is a non-realtime parameter. Therefore the .mod part of the generator
822          * can be neglected.
823          * NOTE: origpitch sets MIDI root note while pitchadj is a fine tuning amount
824          * which offsets the original rate.  This means that the fine tuning is
825          * inverted with respect to the root note (so subtract it, not add).
826          */
827         if(voice->sample != NULL)
828         {
829             if(voice->gen[GEN_OVERRIDEROOTKEY].val > -1)    //FIXME: use flag instead of -1
830             {
831                 voice->root_pitch = voice->gen[GEN_OVERRIDEROOTKEY].val * 100.0f
832                                     - voice->sample->pitchadj;
833             }
834             else
835             {
836                 voice->root_pitch = voice->sample->origpitch * 100.0f - voice->sample->pitchadj;
837             }
838
839             x = (fluid_ct2hz(voice->root_pitch) * ((fluid_real_t) voice->output_rate / voice->sample->samplerate));
840         }
841         else
842         {
843             if(voice->gen[GEN_OVERRIDEROOTKEY].val > -1)     //FIXME: use flag instead of -1
844             {
845                 voice->root_pitch = voice->gen[GEN_OVERRIDEROOTKEY].val * 100.0f;
846             }
847             else
848             {
849                 voice->root_pitch = 0;
850             }
851
852             x = fluid_ct2hz(voice->root_pitch);
853         }
854
855         /* voice->pitch depends on voice->root_pitch, so calculate voice->pitch now */
856         fluid_voice_calculate_gen_pitch(voice);
857         UPDATE_RVOICE_R1(fluid_rvoice_set_root_pitch_hz, x);
858
859         break;
860
861     case GEN_FILTERFC:
862         /* The resonance frequency is converted from absolute cents to
863          * midicents .val and .mod are both used, this permits real-time
864          * modulation.  The allowed range is tested in the 'fluid_ct2hz'
865          * function [PH,20021214]
866          */
867         UPDATE_RVOICE_GENERIC_R1(fluid_iir_filter_set_fres, &voice->rvoice->resonant_filter, x);
868         break;
869
870     case GEN_FILTERQ:
871         UPDATE_RVOICE_GENERIC_R1(fluid_iir_filter_set_q, &voice->rvoice->resonant_filter, x);
872         break;
873
874     /* same as the two above, only for the custom filter */
875     case GEN_CUSTOM_FILTERFC:
876         UPDATE_RVOICE_GENERIC_R1(fluid_iir_filter_set_fres, &voice->rvoice->resonant_custom_filter, x);
877         break;
878
879     case GEN_CUSTOM_FILTERQ:
880         UPDATE_RVOICE_GENERIC_R1(fluid_iir_filter_set_q, &voice->rvoice->resonant_custom_filter, x);
881         break;
882
883     case GEN_MODLFOTOPITCH:
884         fluid_clip(x, -12000.0, 12000.0);
885         UPDATE_RVOICE_R1(fluid_rvoice_set_modlfo_to_pitch, x);
886         break;
887
888     case GEN_MODLFOTOVOL:
889         fluid_clip(x, -960.0, 960.0);
890         UPDATE_RVOICE_R1(fluid_rvoice_set_modlfo_to_vol, x);
891         break;
892
893     case GEN_MODLFOTOFILTERFC:
894         fluid_clip(x, -12000, 12000);
895         UPDATE_RVOICE_R1(fluid_rvoice_set_modlfo_to_fc, x);
896         break;
897
898     case GEN_MODLFODELAY:
899         fluid_clip(x, -12000.0f, 5000.0f);
900         z = (unsigned int)(voice->output_rate * fluid_tc2sec_delay(x));
901         UPDATE_RVOICE_ENVLFO_I1(fluid_lfo_set_delay, modlfo, z);
902         break;
903
904     case GEN_MODLFOFREQ:
905         /* - the frequency is converted into a delta value, per buffer of FLUID_BUFSIZE samples
906          * - the delay into a sample delay
907          */
908         fluid_clip(x, -16000.0f, 4500.0f);
909         x = (4.0f * FLUID_BUFSIZE * fluid_act2hz(x) / voice->output_rate);
910         UPDATE_RVOICE_ENVLFO_R1(fluid_lfo_set_incr, modlfo, x);
911         break;
912
913     case GEN_VIBLFOFREQ:
914         /* vib lfo
915          *
916          * - the frequency is converted into a delta value, per buffer of FLUID_BUFSIZE samples
917          * - the delay into a sample delay
918          */
919         fluid_clip(x, -16000.0f, 4500.0f);
920         x = 4.0f * FLUID_BUFSIZE * fluid_act2hz(x) / voice->output_rate;
921         UPDATE_RVOICE_ENVLFO_R1(fluid_lfo_set_incr, viblfo, x);
922         break;
923
924     case GEN_VIBLFODELAY:
925         fluid_clip(x, -12000.0f, 5000.0f);
926         z = (unsigned int)(voice->output_rate * fluid_tc2sec_delay(x));
927         UPDATE_RVOICE_ENVLFO_I1(fluid_lfo_set_delay, viblfo, z);
928         break;
929
930     case GEN_VIBLFOTOPITCH:
931         fluid_clip(x, -12000.0, 12000.0);
932         UPDATE_RVOICE_R1(fluid_rvoice_set_viblfo_to_pitch, x);
933         break;
934
935     case GEN_KEYNUM:
936         /* GEN_KEYNUM: SF2.01 page 46, item 46
937          *
938          * If this generator is active, it forces the key number to its
939          * value.  Non-realtime controller.
940          *
941          * There is a flag, which should indicate, whether a generator is
942          * enabled or not.  But here we rely on the default value of -1.
943          */
944
945         /* 2017-09-02: do not change the voice's key here, otherwise it will
946          * never be released on a noteoff event
947          */
948 #if 0
949         x = fluid_voice_gen_value(voice, GEN_KEYNUM);
950
951         if(x >= 0)
952         {
953             voice->key = x;
954         }
955
956 #endif
957         break;
958
959     case GEN_VELOCITY:
960         /* GEN_VELOCITY: SF2.01 page 46, item 47
961          *
962          * If this generator is active, it forces the velocity to its
963          * value. Non-realtime controller.
964          *
965          * There is a flag, which should indicate, whether a generator is
966          * enabled or not. But here we rely on the default value of -1.
967          */
968         /* 2017-09-02: do not change the voice's velocity here, use
969          * fluid_voice_get_actual_velocity() to get the value of this generator
970          * if active.
971          */
972 #if 0
973         x = fluid_voice_gen_value(voice, GEN_VELOCITY);
974
975         if(x > 0)
976         {
977             voice->vel = x;
978         }
979
980 #endif
981         break;
982
983     case GEN_MODENVTOPITCH:
984         fluid_clip(x, -12000.0, 12000.0);
985         UPDATE_RVOICE_R1(fluid_rvoice_set_modenv_to_pitch, x);
986         break;
987
988     case GEN_MODENVTOFILTERFC:
989         /* Range: SF2.01 section 8.1.3 # 1
990          * Motivation for range checking:
991          * Filter is reported to make funny noises now and then
992          */
993         fluid_clip(x, -12000.0, 12000.0);
994         UPDATE_RVOICE_R1(fluid_rvoice_set_modenv_to_fc, x);
995         break;
996
997
998     /* sample start and ends points
999      *
1000      * Range checking is initiated via the
1001      * voice->check_sample_sanity flag,
1002      * because it is impossible to check here:
1003      * During the voice setup, all modulators are processed, while
1004      * the voice is inactive. Therefore, illegal settings may
1005      * occur during the setup (for example: First move the loop
1006      * end point ahead of the loop start point => invalid, then
1007      * move the loop start point forward => valid again.
1008      */
1009     case GEN_STARTADDROFS:              /* SF2.01 section 8.1.3 # 0 */
1010     case GEN_STARTADDRCOARSEOFS:        /* SF2.01 section 8.1.3 # 4 */
1011         if(voice->sample != NULL)
1012         {
1013             fluid_real_t start_fine = fluid_voice_gen_value(voice, GEN_STARTADDROFS);
1014             fluid_real_t start_coar = fluid_voice_gen_value(voice, GEN_STARTADDRCOARSEOFS);
1015
1016             z = voice->sample->start + (int)start_fine + 32768 * (int)start_coar;
1017             UPDATE_RVOICE_I1(fluid_rvoice_set_start, z);
1018         }
1019
1020         break;
1021
1022     case GEN_ENDADDROFS:                 /* SF2.01 section 8.1.3 # 1 */
1023     case GEN_ENDADDRCOARSEOFS:           /* SF2.01 section 8.1.3 # 12 */
1024         if(voice->sample != NULL)
1025         {
1026             fluid_real_t end_fine = fluid_voice_gen_value(voice, GEN_ENDADDROFS);
1027             fluid_real_t end_coar = fluid_voice_gen_value(voice, GEN_ENDADDRCOARSEOFS);
1028
1029             z = voice->sample->end + (int)end_fine + 32768 * (int)end_coar;
1030             UPDATE_RVOICE_I1(fluid_rvoice_set_end, z);
1031         }
1032
1033         break;
1034
1035     case GEN_STARTLOOPADDROFS:           /* SF2.01 section 8.1.3 # 2 */
1036     case GEN_STARTLOOPADDRCOARSEOFS:     /* SF2.01 section 8.1.3 # 45 */
1037         if(voice->sample != NULL)
1038         {
1039             fluid_real_t lstart_fine = fluid_voice_gen_value(voice, GEN_STARTLOOPADDROFS);
1040             fluid_real_t lstart_coar = fluid_voice_gen_value(voice, GEN_STARTLOOPADDRCOARSEOFS);
1041
1042             z = voice->sample->loopstart + (int)lstart_fine + 32768 * (int)lstart_coar;
1043             UPDATE_RVOICE_I1(fluid_rvoice_set_loopstart, z);
1044         }
1045
1046         break;
1047
1048     case GEN_ENDLOOPADDROFS:             /* SF2.01 section 8.1.3 # 3 */
1049     case GEN_ENDLOOPADDRCOARSEOFS:       /* SF2.01 section 8.1.3 # 50 */
1050         if(voice->sample != NULL)
1051         {
1052             fluid_real_t lend_fine = fluid_voice_gen_value(voice, GEN_ENDLOOPADDROFS);
1053             fluid_real_t lend_coar = fluid_voice_gen_value(voice, GEN_ENDLOOPADDRCOARSEOFS);
1054
1055             z = voice->sample->loopend + (int)lend_fine + 32768 * (int)lend_coar;
1056             UPDATE_RVOICE_I1(fluid_rvoice_set_loopend, z);
1057         }
1058
1059         break;
1060
1061         /* Conversion functions differ in range limit */
1062 #define NUM_BUFFERS_DELAY(_v)   (unsigned int) (voice->output_rate * fluid_tc2sec_delay(_v) / FLUID_BUFSIZE)
1063 #define NUM_BUFFERS_ATTACK(_v)  (unsigned int) (voice->output_rate * fluid_tc2sec_attack(_v) / FLUID_BUFSIZE)
1064 #define NUM_BUFFERS_RELEASE(_v) (unsigned int) (voice->output_rate * fluid_tc2sec_release(_v) / FLUID_BUFSIZE)
1065
1066     /* volume envelope
1067      *
1068      * - delay and hold times are converted to absolute number of samples
1069      * - sustain is converted to its absolute value
1070      * - attack, decay and release are converted to their increment per sample
1071      */
1072     case GEN_VOLENVDELAY:                /* SF2.01 section 8.1.3 # 33 */
1073         fluid_clip(x, -12000.0f, 5000.0f);
1074         count = NUM_BUFFERS_DELAY(x);
1075         fluid_voice_update_volenv(voice, TRUE, FLUID_VOICE_ENVDELAY,
1076                                   count, 0.0f, 0.0f, -1.0f, 1.0f);
1077         break;
1078
1079     case GEN_VOLENVATTACK:               /* SF2.01 section 8.1.3 # 34 */
1080         fluid_clip(x, -12000.0f, 8000.0f);
1081         count = 1 + NUM_BUFFERS_ATTACK(x);
1082         fluid_voice_update_volenv(voice, TRUE, FLUID_VOICE_ENVATTACK,
1083                                   count, 1.0f, 1.0f / count, -1.0f, 1.0f);
1084         break;
1085
1086     case GEN_VOLENVHOLD:                 /* SF2.01 section 8.1.3 # 35 */
1087     case GEN_KEYTOVOLENVHOLD:            /* SF2.01 section 8.1.3 # 39 */
1088         count = calculate_hold_decay_buffers(voice, GEN_VOLENVHOLD, GEN_KEYTOVOLENVHOLD, 0); /* 0 means: hold */
1089         fluid_voice_update_volenv(voice, TRUE, FLUID_VOICE_ENVHOLD,
1090                                   count, 1.0f, 0.0f, -1.0f, 2.0f);
1091         break;
1092
1093     case GEN_VOLENVDECAY:               /* SF2.01 section 8.1.3 # 36 */
1094     case GEN_VOLENVSUSTAIN:             /* SF2.01 section 8.1.3 # 37 */
1095     case GEN_KEYTOVOLENVDECAY:          /* SF2.01 section 8.1.3 # 40 */
1096         x = 1.0f - 0.001f * fluid_voice_gen_value(voice, GEN_VOLENVSUSTAIN);
1097         fluid_clip(x, 0.0f, 1.0f);
1098         count = calculate_hold_decay_buffers(voice, GEN_VOLENVDECAY, GEN_KEYTOVOLENVDECAY, 1); /* 1 for decay */
1099         fluid_voice_update_volenv(voice, TRUE, FLUID_VOICE_ENVDECAY,
1100                                   count, 1.0f, count ? -1.0f / count : 0.0f, x, 2.0f);
1101         break;
1102
1103     case GEN_VOLENVRELEASE:             /* SF2.01 section 8.1.3 # 38 */
1104         fluid_clip(x, FLUID_MIN_VOLENVRELEASE, 8000.0f);
1105         count = 1 + NUM_BUFFERS_RELEASE(x);
1106         fluid_voice_update_volenv(voice, TRUE, FLUID_VOICE_ENVRELEASE,
1107                                   count, 1.0f, -1.0f / count, 0.0f, 1.0f);
1108         break;
1109
1110     /* Modulation envelope */
1111     case GEN_MODENVDELAY:               /* SF2.01 section 8.1.3 # 25 */
1112         fluid_clip(x, -12000.0f, 5000.0f);
1113         fluid_voice_update_modenv(voice, TRUE, FLUID_VOICE_ENVDELAY,
1114                                   NUM_BUFFERS_DELAY(x), 0.0f, 0.0f, -1.0f, 1.0f);
1115         break;
1116
1117     case GEN_MODENVATTACK:               /* SF2.01 section 8.1.3 # 26 */
1118         fluid_clip(x, -12000.0f, 8000.0f);
1119         count = 1 + NUM_BUFFERS_ATTACK(x);
1120         fluid_voice_update_modenv(voice, TRUE, FLUID_VOICE_ENVATTACK,
1121                                   count, 1.0f, 1.0f / count, -1.0f, 1.0f);
1122         break;
1123
1124     case GEN_MODENVHOLD:               /* SF2.01 section 8.1.3 # 27 */
1125     case GEN_KEYTOMODENVHOLD:          /* SF2.01 section 8.1.3 # 31 */
1126         count = calculate_hold_decay_buffers(voice, GEN_MODENVHOLD, GEN_KEYTOMODENVHOLD, 0); /* 1 means: hold */
1127         fluid_voice_update_modenv(voice, TRUE, FLUID_VOICE_ENVHOLD,
1128                                   count, 1.0f, 0.0f, -1.0f, 2.0f);
1129         break;
1130
1131     case GEN_MODENVDECAY:                                   /* SF 2.01 section 8.1.3 # 28 */
1132     case GEN_MODENVSUSTAIN:                                 /* SF 2.01 section 8.1.3 # 29 */
1133     case GEN_KEYTOMODENVDECAY:                              /* SF 2.01 section 8.1.3 # 32 */
1134         count = calculate_hold_decay_buffers(voice, GEN_MODENVDECAY, GEN_KEYTOMODENVDECAY, 1); /* 1 for decay */
1135         x = 1.0f - 0.001f * fluid_voice_gen_value(voice, GEN_MODENVSUSTAIN);
1136         fluid_clip(x, 0.0f, 1.0f);
1137         fluid_voice_update_modenv(voice, TRUE, FLUID_VOICE_ENVDECAY,
1138                                   count, 1.0f, count ? -1.0f / count : 0.0f, x, 2.0f);
1139         break;
1140
1141     case GEN_MODENVRELEASE:                                  /* SF 2.01 section 8.1.3 # 30 */
1142         fluid_clip(x, -12000.0f, 8000.0f);
1143         count = 1 + NUM_BUFFERS_RELEASE(x);
1144         fluid_voice_update_modenv(voice, TRUE, FLUID_VOICE_ENVRELEASE,
1145                                   count, 1.0f, -1.0f / count, 0.0f, 2.0f);
1146
1147         break;
1148
1149     } /* switch gen */
1150 }
1151
1152 /**
1153  * Recalculate voice parameters for a given control.
1154  * @param voice the synthesis voice
1155  * @param cc flag to distinguish between a continous control and a channel control (pitch bend, ...)
1156  * @param ctrl the control number
1157  *
1158  * In this implementation, I want to make sure that all controllers
1159  * are event based: the parameter values of the DSP algorithm should
1160  * only be updates when a controller event arrived and not at every
1161  * iteration of the audio cycle (which would probably be feasible if
1162  * the synth was made in silicon).
1163  *
1164  * The update is done in three steps:
1165  *
1166  * - first, we look for all the modulators that have the changed
1167  * controller as a source. This will yield a list of generators that
1168  * will be changed because of the controller event.
1169  *
1170  * - For every changed generator, calculate its new value. This is the
1171  * sum of its original value plus the values of al the attached
1172  * modulators.
1173  *
1174  * - For every changed generator, convert its value to the correct
1175  * unit of the corresponding DSP parameter
1176  */
1177 int fluid_voice_modulate(fluid_voice_t *voice, int cc, int ctrl)
1178 {
1179     int i, k;
1180     fluid_mod_t *mod;
1181     int gen;
1182     fluid_real_t modval;
1183
1184     /*    printf("Chan=%d, CC=%d, Src=%d, Val=%d\n", voice->channel->channum, cc, ctrl, val); */
1185
1186     for(i = 0; i < voice->mod_count; i++)
1187     {
1188
1189         mod = &voice->mod[i];
1190
1191         /* step 1: find all the modulators that have the changed controller
1192          * as input source. */
1193         if(fluid_mod_has_source(mod, cc, ctrl))
1194         {
1195
1196             gen = fluid_mod_get_dest(mod);
1197             modval = 0.0;
1198
1199             /* step 2: for every changed modulator, calculate the modulation
1200              * value of its associated generator */
1201             for(k = 0; k < voice->mod_count; k++)
1202             {
1203                 if(fluid_mod_has_dest(&voice->mod[k], gen))
1204                 {
1205                     modval += fluid_mod_get_value(&voice->mod[k], voice);
1206                 }
1207             }
1208
1209             fluid_gen_set_mod(&voice->gen[gen], modval);
1210
1211             /* step 3: now that we have the new value of the generator,
1212              * recalculate the parameter values that are derived from the
1213              * generator */
1214             fluid_voice_update_param(voice, gen);
1215         }
1216     }
1217
1218     return FLUID_OK;
1219 }
1220
1221 /**
1222  * Update all the modulators. This function is called after a
1223  * ALL_CTRL_OFF MIDI message has been received (CC 121).
1224  *
1225  */
1226 int fluid_voice_modulate_all(fluid_voice_t *voice)
1227 {
1228     fluid_mod_t *mod;
1229     int i, k, gen;
1230     fluid_real_t modval;
1231
1232     /* Loop through all the modulators.
1233
1234        FIXME: we should loop through the set of generators instead of
1235        the set of modulators. We risk to call 'fluid_voice_update_param'
1236        several times for the same generator if several modulators have
1237        that generator as destination. It's not an error, just a wast of
1238        energy (think polution, global warming, unhappy musicians,
1239        ...) */
1240
1241     for(i = 0; i < voice->mod_count; i++)
1242     {
1243
1244         mod = &voice->mod[i];
1245         gen = fluid_mod_get_dest(mod);
1246         modval = 0.0;
1247
1248         /* Accumulate the modulation values of all the modulators with
1249          * destination generator 'gen' */
1250         for(k = 0; k < voice->mod_count; k++)
1251         {
1252             if(fluid_mod_has_dest(&voice->mod[k], gen))
1253             {
1254                 modval += fluid_mod_get_value(&voice->mod[k], voice);
1255             }
1256         }
1257
1258         fluid_gen_set_mod(&voice->gen[gen], modval);
1259
1260         /* Update the parameter values that are depend on the generator
1261          * 'gen' */
1262         fluid_voice_update_param(voice, gen);
1263     }
1264
1265     return FLUID_OK;
1266 }
1267
1268 /** legato update functions --------------------------------------------------*/
1269 /* Updates voice portamento parameters
1270  *
1271  * @voice voice the synthesis voice
1272  * @fromkey the beginning pitch of portamento.
1273  * @tokey the ending pitch of portamento.
1274  *
1275  * The function calculates pitch offset and increment, then these parameters
1276  * are send to the dsp.
1277 */
1278 void fluid_voice_update_portamento(fluid_voice_t *voice, int fromkey, int tokey)
1279
1280 {
1281     fluid_channel_t *channel = voice->channel;
1282
1283     /* calculates pitch offset */
1284     fluid_real_t PitchBeg = fluid_voice_calculate_pitch(voice, fromkey);
1285     fluid_real_t PitchEnd = fluid_voice_calculate_pitch(voice, tokey);
1286     fluid_real_t pitchoffset = PitchBeg - PitchEnd;
1287
1288     /* Calculates increment countinc */
1289     /* Increment is function of PortamentoTime (ms)*/
1290     unsigned int countinc = (unsigned int)(((fluid_real_t)voice->output_rate *
1291                                             0.001f *
1292                                             (fluid_real_t)fluid_channel_portamentotime(channel))  /
1293                                            (fluid_real_t)FLUID_BUFSIZE  + 0.5);
1294
1295     /* Send portamento parameters to the voice dsp */
1296     UPDATE_RVOICE_GENERIC_IR(fluid_rvoice_set_portamento, voice->rvoice, countinc, pitchoffset);
1297 }
1298
1299 /*---------------------------------------------------------------*/
1300 /*legato mode 1: multi_retrigger
1301  *
1302  * Modulates all generators dependent of key,vel.
1303  * Forces the voice envelopes in the attack section (legato mode 1).
1304  *
1305  * @voice voice the synthesis voice
1306  * @tokey the new key to be applied to this voice.
1307  * @vel the new velocity to be applied to this voice.
1308  */
1309 void fluid_voice_update_multi_retrigger_attack(fluid_voice_t *voice,
1310         int tokey, int vel)
1311 {
1312     voice->key = tokey;  /* new note */
1313     voice->vel = vel; /* new velocity */
1314     /* Updates generators dependent of velocity */
1315     /* Modulates GEN_ATTENUATION (and others ) before calling
1316        fluid_rvoice_multi_retrigger_attack().*/
1317     fluid_voice_modulate(voice, FALSE, FLUID_MOD_VELOCITY);
1318
1319     /* Updates generator dependent of voice->key */
1320     fluid_voice_update_param(voice, GEN_KEYTOMODENVHOLD);
1321     fluid_voice_update_param(voice, GEN_KEYTOMODENVDECAY);
1322     fluid_voice_update_param(voice, GEN_KEYTOVOLENVHOLD);
1323     fluid_voice_update_param(voice, GEN_KEYTOVOLENVDECAY);
1324
1325     /* Updates pitch generator  */
1326     fluid_voice_calculate_gen_pitch(voice);
1327     fluid_voice_update_param(voice, GEN_PITCH);
1328
1329     /* updates adsr generator */
1330     UPDATE_RVOICE0(fluid_rvoice_multi_retrigger_attack);
1331 }
1332 /** end of legato update functions */
1333
1334 /*
1335  Force the voice into release stage. Useful anywhere a voice
1336  needs to be damped even if pedals (sustain sostenuto) are depressed.
1337  See fluid_synth_damp_voices_by_sustain_LOCAL(),
1338  fluid_synth_damp_voices_by_sostenuto_LOCAL,
1339  fluid_voice_noteoff().
1340 */
1341 void
1342 fluid_voice_release(fluid_voice_t *voice)
1343 {
1344     unsigned int at_tick = fluid_channel_get_min_note_length_ticks(voice->channel);
1345     UPDATE_RVOICE_I1(fluid_rvoice_noteoff, at_tick);
1346     voice->has_noteoff = 1; // voice is marked as noteoff occured
1347 }
1348
1349 /*
1350  * fluid_voice_noteoff
1351  *
1352  * Sending a noteoff event will advance the envelopes to section 5 (release).
1353  * The function is convenient for polyphonic or monophonic note
1354  */
1355 void
1356 fluid_voice_noteoff(fluid_voice_t *voice)
1357 {
1358     fluid_channel_t *channel;
1359
1360     fluid_profile(FLUID_PROF_VOICE_NOTE, voice->ref, 0, 0);
1361
1362     channel = voice->channel;
1363
1364     /* Sustain a note under Sostenuto pedal */
1365     if(fluid_channel_sostenuto(channel) &&
1366             channel->sostenuto_orderid > voice->id)
1367     {
1368         // Sostenuto depressed after note
1369         voice->status = FLUID_VOICE_HELD_BY_SOSTENUTO;
1370     }
1371     /* Or sustain a note under Sustain pedal */
1372     else if(fluid_channel_sustained(channel))
1373     {
1374         voice->status = FLUID_VOICE_SUSTAINED;
1375     }
1376     /* Or force the voice to release stage */
1377     else
1378     {
1379         fluid_voice_release(voice);
1380     }
1381 }
1382
1383 /*
1384  * fluid_voice_kill_excl
1385  *
1386  * Percussion sounds can be mutually exclusive: for example, a 'closed
1387  * hihat' sound will terminate an 'open hihat' sound ringing at the
1388  * same time. This behaviour is modeled using 'exclusive classes',
1389  * turning on a voice with an exclusive class other than 0 will kill
1390  * all other voices having that exclusive class within the same preset
1391  * or channel.  fluid_voice_kill_excl gets called, when 'voice' is to
1392  * be killed for that reason.
1393  */
1394
1395 int
1396 fluid_voice_kill_excl(fluid_voice_t *voice)
1397 {
1398
1399     unsigned int at_tick;
1400
1401     if(!fluid_voice_is_playing(voice))
1402     {
1403         return FLUID_OK;
1404     }
1405
1406     /* Turn off the exclusive class information for this voice,
1407        so that it doesn't get killed twice
1408     */
1409     fluid_voice_gen_set(voice, GEN_EXCLUSIVECLASS, 0);
1410
1411     /* Speed up the volume envelope */
1412     /* The value was found through listening tests with hi-hat samples. */
1413     fluid_voice_gen_set(voice, GEN_VOLENVRELEASE, -200);
1414     fluid_voice_update_param(voice, GEN_VOLENVRELEASE);
1415
1416     /* Speed up the modulation envelope */
1417     fluid_voice_gen_set(voice, GEN_MODENVRELEASE, -200);
1418     fluid_voice_update_param(voice, GEN_MODENVRELEASE);
1419
1420     at_tick = fluid_channel_get_min_note_length_ticks(voice->channel);
1421     UPDATE_RVOICE_I1(fluid_rvoice_noteoff, at_tick);
1422
1423
1424     return FLUID_OK;
1425 }
1426
1427 /*
1428  * Called by fluid_synth when the overflow rvoice can be reclaimed.
1429  */
1430 void fluid_voice_overflow_rvoice_finished(fluid_voice_t *voice)
1431 {
1432     voice->can_access_overflow_rvoice = 1;
1433     fluid_voice_sample_unref(&voice->overflow_rvoice->dsp.sample);
1434 }
1435
1436 /*
1437  * fluid_voice_off
1438  *
1439  * Force the voice into finished stage. Useful anywhere a voice
1440  * needs to be cancelled from MIDI API.
1441  */
1442 void fluid_voice_off(fluid_voice_t *voice)
1443 {
1444     UPDATE_RVOICE0(fluid_rvoice_voiceoff); /* request to finish the voice */
1445 }
1446
1447 /*
1448  * fluid_voice_stop
1449  *
1450  * Purpose:
1451  * Turns off a voice, meaning that it is not processed anymore by the
1452  * DSP loop, i.e. contrary part to fluid_voice_start().
1453  */
1454 void
1455 fluid_voice_stop(fluid_voice_t *voice)
1456 {
1457     fluid_profile(FLUID_PROF_VOICE_RELEASE, voice->ref, 0, 0);
1458
1459     voice->chan = NO_CHANNEL;
1460
1461     if(voice->can_access_rvoice)
1462     {
1463         fluid_voice_sample_unref(&voice->rvoice->dsp.sample);
1464     }
1465
1466     voice->status = FLUID_VOICE_OFF;
1467     voice->has_noteoff = 1;
1468
1469     /* Decrement the reference count of the sample. */
1470     fluid_voice_sample_unref(&voice->sample);
1471
1472     /* Decrement voice count */
1473     voice->channel->synth->active_voice_count--;
1474 }
1475
1476 /**
1477  * Adds a modulator to the voice.
1478  * @param voice Voice instance
1479  * @param mod Modulator info (copied)
1480  * @param mode Determines how to handle an existing identical modulator
1481  *   #FLUID_VOICE_ADD to add (offset) the modulator amounts,
1482  *   #FLUID_VOICE_OVERWRITE to replace the modulator,
1483  *   #FLUID_VOICE_DEFAULT when adding a default modulator - no duplicate should
1484  *   exist so don't check.
1485  */
1486 void
1487 fluid_voice_add_mod(fluid_voice_t *voice, fluid_mod_t *mod, int mode)
1488 {
1489     int i;
1490
1491     /*
1492      * Some soundfonts come with a huge number of non-standard
1493      * controllers, because they have been designed for one particular
1494      * sound card.  Discard them, maybe print a warning.
1495      */
1496
1497     if(((mod->flags1 & FLUID_MOD_CC) == 0)
1498             && ((mod->src1 != FLUID_MOD_NONE)            /* SF2.01 section 8.2.1: Constant value */
1499                 && (mod->src1 != FLUID_MOD_VELOCITY)        /* Note-on velocity */
1500                 && (mod->src1 != FLUID_MOD_KEY)             /* Note-on key number */
1501                 && (mod->src1 != FLUID_MOD_KEYPRESSURE)     /* Poly pressure */
1502                 && (mod->src1 != FLUID_MOD_CHANNELPRESSURE) /* Channel pressure */
1503                 && (mod->src1 != FLUID_MOD_PITCHWHEEL)      /* Pitch wheel */
1504                 && (mod->src1 != FLUID_MOD_PITCHWHEELSENS)))/* Pitch wheel sensitivity */
1505     {
1506         FLUID_LOG(FLUID_WARN, "Ignoring invalid controller, using non-CC source %i.", mod->src1);
1507         return;
1508     }
1509
1510     if(mode == FLUID_VOICE_ADD)
1511     {
1512
1513         /* if identical modulator exists, add them */
1514         for(i = 0; i < voice->mod_count; i++)
1515         {
1516             if(fluid_mod_test_identity(&voice->mod[i], mod))
1517             {
1518                 //              printf("Adding modulator...\n");
1519                 voice->mod[i].amount += mod->amount;
1520                 return;
1521             }
1522         }
1523
1524     }
1525     else if(mode == FLUID_VOICE_OVERWRITE)
1526     {
1527
1528         /* if identical modulator exists, replace it (only the amount has to be changed) */
1529         for(i = 0; i < voice->mod_count; i++)
1530         {
1531             if(fluid_mod_test_identity(&voice->mod[i], mod))
1532             {
1533                 //              printf("Replacing modulator...amount is %f\n",mod->amount);
1534                 voice->mod[i].amount = mod->amount;
1535                 return;
1536             }
1537         }
1538     }
1539
1540     /* Add a new modulator (No existing modulator to add / overwrite).
1541        Also, default modulators (FLUID_VOICE_DEFAULT) are added without
1542        checking, if the same modulator already exists. */
1543     if(voice->mod_count < FLUID_NUM_MOD)
1544     {
1545         fluid_mod_clone(&voice->mod[voice->mod_count++], mod);
1546     }
1547     else
1548     {
1549         FLUID_LOG(FLUID_WARN, "Voice %i has more modulators than supported, ignoring.", voice->id);
1550     }
1551 }
1552
1553 /**
1554  * Get the unique ID of the noteon-event.
1555  * @param voice Voice instance
1556  * @return Note on unique ID
1557  *
1558  * A SoundFont loader may store the voice processes it has created for
1559  * real-time control during the operation of a voice (for example: parameter
1560  * changes in SoundFont editor). The synth uses a pool of voices, which are
1561  * 'recycled' and never deallocated.
1562  *
1563  * Before modifying an existing voice, check
1564  * - that its state is still 'playing'
1565  * - that the ID is still the same
1566  *
1567  * Otherwise the voice has finished playing.
1568  */
1569 unsigned int fluid_voice_get_id(const fluid_voice_t *voice)
1570 {
1571     return voice->id;
1572 }
1573
1574 /**
1575  * Check if a voice is producing sound. This is also true after a voice received a noteoff as it may be playing in release phase.
1576  * @param voice Voice instance
1577  * @return TRUE if playing, FALSE otherwise
1578  */
1579 int fluid_voice_is_playing(const fluid_voice_t *voice)
1580 {
1581     return (voice->status == FLUID_VOICE_ON)
1582            || fluid_voice_is_sustained(voice)
1583            || fluid_voice_is_sostenuto(voice);
1584
1585 }
1586
1587 /**
1588  * Check if a voice is ON. A voice is ON, if it has not yet received a noteoff event.
1589  * @param voice Voice instance
1590  * @return TRUE if on, FALSE otherwise
1591  * @since 1.1.7
1592  */
1593 int fluid_voice_is_on(const fluid_voice_t *voice)
1594 {
1595     return (voice->status == FLUID_VOICE_ON && !voice->has_noteoff);
1596 }
1597
1598 /**
1599  * Check if a voice keeps playing after it has received a noteoff due to being held by sustain.
1600  * @param voice Voice instance
1601  * @return TRUE if sustained, FALSE otherwise
1602  * @since 1.1.7
1603  */
1604 int fluid_voice_is_sustained(const fluid_voice_t *voice)
1605 {
1606     return (voice->status == FLUID_VOICE_SUSTAINED);
1607 }
1608
1609 /**
1610  * Check if a voice keeps playing after it has received a noteoff due to being held by sostenuto.
1611  * @param voice Voice instance
1612  * @return TRUE if sostenuto, FALSE otherwise
1613  * @since 1.1.7
1614  */
1615 int fluid_voice_is_sostenuto(const fluid_voice_t *voice)
1616 {
1617     return (voice->status == FLUID_VOICE_HELD_BY_SOSTENUTO);
1618 }
1619
1620 /**
1621  * If the voice is playing, gets the midi channel the voice is playing on. Else the result is undefined.
1622  * @param voice Voice instance
1623  * @return The channel assigned to this voice
1624  * @since 1.1.7
1625  */
1626 int fluid_voice_get_channel(const fluid_voice_t *voice)
1627 {
1628     return voice->chan;
1629 }
1630
1631 /**
1632  * If the voice is playing, gets the midi key the voice is actually playing at. Else the result is undefined.
1633  * If the voice was started from an instrument which uses a fixed key generator, it returns that.
1634  * Else returns the same as \c fluid_voice_get_key.
1635  * @param voice Voice instance
1636  * @return The midi key this voice is playing at
1637  * @since 1.1.7
1638  */
1639 int fluid_voice_get_actual_key(const fluid_voice_t *voice)
1640 {
1641     fluid_real_t x = fluid_voice_gen_value(voice, GEN_KEYNUM);
1642
1643     if(x >= 0)
1644     {
1645         return (int)x;
1646     }
1647     else
1648     {
1649         return fluid_voice_get_key(voice);
1650     }
1651 }
1652
1653 /**
1654  * If the voice is playing, gets the midi key from the noteon event, by which the voice was initially turned on with.
1655  * Else the result is undefined.
1656  * @param voice Voice instance
1657  * @return The midi key of the noteon event that originally turned on this voice
1658  * @since 1.1.7
1659  */
1660 int fluid_voice_get_key(const fluid_voice_t *voice)
1661 {
1662     return voice->key;
1663 }
1664
1665 /**
1666  * If the voice is playing, gets the midi velocity the voice is actually playing at. Else the result is undefined.
1667  * If the voice was started from an instrument which uses a fixed velocity generator, it returns that.
1668  * Else returns the same as \c fluid_voice_get_velocity.
1669  * @param voice Voice instance
1670  * @return The midi velocity this voice is playing at
1671  * @since 1.1.7
1672  */
1673 int fluid_voice_get_actual_velocity(const fluid_voice_t *voice)
1674 {
1675     fluid_real_t x = fluid_voice_gen_value(voice, GEN_VELOCITY);
1676
1677     if(x > 0)
1678     {
1679         return (int)x;
1680     }
1681     else
1682     {
1683         return fluid_voice_get_velocity(voice);
1684     }
1685 }
1686
1687 /**
1688  * If the voice is playing, gets the midi velocity from the noteon event, by which the voice was initially
1689  * turned on with. Else the result is undefined.
1690  * @param voice Voice instance
1691  * @return The midi velocity which originally turned on this voice
1692  * @since 1.1.7
1693  */
1694 int fluid_voice_get_velocity(const fluid_voice_t *voice)
1695 {
1696     return voice->vel;
1697 }
1698
1699 /*
1700  * fluid_voice_get_lower_boundary_for_attenuation
1701  *
1702  * Purpose:
1703  *
1704  * A lower boundary for the attenuation (as in 'the minimum
1705  * attenuation of this voice, with volume pedals, modulators
1706  * etc. resulting in minimum attenuation, cannot fall below x cB) is
1707  * calculated.  This has to be called during fluid_voice_init, after
1708  * all modulators have been run on the voice once.  Also,
1709  * voice->attenuation has to be initialized.
1710  */
1711 static fluid_real_t
1712 fluid_voice_get_lower_boundary_for_attenuation(fluid_voice_t *voice)
1713 {
1714     int i;
1715     fluid_mod_t *mod;
1716     fluid_real_t possible_att_reduction_cB = 0;
1717     fluid_real_t lower_bound;
1718
1719     for(i = 0; i < voice->mod_count; i++)
1720     {
1721         mod = &voice->mod[i];
1722
1723         /* Modulator has attenuation as target and can change over time? */
1724         if((mod->dest == GEN_ATTENUATION)
1725                 && ((mod->flags1 & FLUID_MOD_CC)
1726                     || (mod->flags2 & FLUID_MOD_CC)
1727                     || (mod->src1 == FLUID_MOD_CHANNELPRESSURE)
1728                     || (mod->src1 == FLUID_MOD_KEYPRESSURE)
1729                     || (mod->src1 == FLUID_MOD_PITCHWHEEL)
1730                     || (mod->src2 == FLUID_MOD_CHANNELPRESSURE)
1731                     || (mod->src2 == FLUID_MOD_KEYPRESSURE)
1732                     || (mod->src2 == FLUID_MOD_PITCHWHEEL)))
1733         {
1734
1735             fluid_real_t current_val = fluid_mod_get_value(mod, voice);
1736             fluid_real_t v = fabs(mod->amount);
1737
1738             if((mod->src1 == FLUID_MOD_PITCHWHEEL)
1739                     || (mod->flags1 & FLUID_MOD_BIPOLAR)
1740                     || (mod->flags2 & FLUID_MOD_BIPOLAR)
1741                     || (mod->amount < 0))
1742             {
1743                 /* Can this modulator produce a negative contribution? */
1744                 v *= -1.0;
1745             }
1746             else
1747             {
1748                 /* No negative value possible. But still, the minimum contribution is 0. */
1749                 v = 0;
1750             }
1751
1752             /* For example:
1753              * - current_val=100
1754              * - min_val=-4000
1755              * - possible_att_reduction_cB += 4100
1756              */
1757             if(current_val > v)
1758             {
1759                 possible_att_reduction_cB += (current_val - v);
1760             }
1761         }
1762     }
1763
1764     lower_bound = voice->attenuation - possible_att_reduction_cB;
1765
1766     /* SF2.01 specs do not allow negative attenuation */
1767     if(lower_bound < 0)
1768     {
1769         lower_bound = 0;
1770     }
1771
1772     return lower_bound;
1773 }
1774
1775
1776
1777
1778 int fluid_voice_set_param(fluid_voice_t *voice, int gen, fluid_real_t nrpn_value, int abs)
1779 {
1780     voice->gen[gen].nrpn = nrpn_value;
1781     voice->gen[gen].flags = (abs) ? GEN_ABS_NRPN : GEN_SET;
1782     fluid_voice_update_param(voice, gen);
1783     return FLUID_OK;
1784 }
1785
1786 int fluid_voice_set_gain(fluid_voice_t *voice, fluid_real_t gain)
1787 {
1788     fluid_real_t left, right, reverb, chorus;
1789
1790     /* avoid division by zero*/
1791     if(gain < 0.0000001)
1792     {
1793         gain = 0.0000001;
1794     }
1795
1796     voice->synth_gain = gain;
1797     left = fluid_voice_calculate_gain_amplitude(voice,
1798             fluid_pan(voice->pan, 1) * fluid_balance(voice->balance, 1));
1799     right = fluid_voice_calculate_gain_amplitude(voice,
1800             fluid_pan(voice->pan, 0) * fluid_balance(voice->balance, 0));
1801     reverb = fluid_voice_calculate_gain_amplitude(voice, voice->reverb_send);
1802     chorus = fluid_voice_calculate_gain_amplitude(voice, voice->chorus_send);
1803
1804     UPDATE_RVOICE_R1(fluid_rvoice_set_synth_gain, gain);
1805     UPDATE_RVOICE_BUFFERS_AMP(fluid_rvoice_buffers_set_amp, 0, left);
1806     UPDATE_RVOICE_BUFFERS_AMP(fluid_rvoice_buffers_set_amp, 1, right);
1807     UPDATE_RVOICE_BUFFERS_AMP(fluid_rvoice_buffers_set_amp, 2, reverb);
1808     UPDATE_RVOICE_BUFFERS_AMP(fluid_rvoice_buffers_set_amp, 3, chorus);
1809
1810     return FLUID_OK;
1811 }
1812
1813 /* - Scan the loop
1814  * - determine the peak level
1815  * - Calculate, what factor will make the loop inaudible
1816  * - Store in sample
1817  */
1818 /**
1819  * Calculate the peak volume of a sample for voice off optimization.
1820  * @param s Sample to optimize
1821  * @return #FLUID_OK on success, #FLUID_FAILED otherwise
1822  *
1823  * If the peak volume during the loop is known, then the voice can
1824  * be released earlier during the release phase. Otherwise, the
1825  * voice will operate (inaudibly), until the envelope is at the
1826  * nominal turnoff point.  So it's a good idea to call
1827  * fluid_voice_optimize_sample() on each sample once.
1828  */
1829 int
1830 fluid_voice_optimize_sample(fluid_sample_t *s)
1831 {
1832     int32_t peak_max = 0;
1833     int32_t peak_min = 0;
1834     int32_t peak;
1835     fluid_real_t normalized_amplitude_during_loop;
1836     double result;
1837     unsigned int i;
1838
1839     /* ignore disabled samples */
1840     if(s->start == s->end)
1841     {
1842         return (FLUID_OK);
1843     }
1844
1845     if(!s->amplitude_that_reaches_noise_floor_is_valid)    /* Only once */
1846     {
1847         /* Scan the loop */
1848         for(i = s->loopstart; i < s->loopend; i++)
1849         {
1850             int32_t val = fluid_rvoice_get_sample(s->data, s->data24, i);
1851
1852             if(val > peak_max)
1853             {
1854                 peak_max = val;
1855             }
1856             else if(val < peak_min)
1857             {
1858                 peak_min = val;
1859             }
1860         }
1861
1862         /* Determine the peak level */
1863         if(peak_max > -peak_min)
1864         {
1865             peak = peak_max;
1866         }
1867         else
1868         {
1869             peak = -peak_min;
1870         }
1871
1872         if(peak == 0)
1873         {
1874             /* Avoid division by zero */
1875             peak = 1;
1876         }
1877
1878         /* Calculate what factor will make the loop inaudible
1879          * For example: Take a peak of 3277 (10 % of 32768).  The
1880          * normalized amplitude is 0.1 (10 % of 32768).  An amplitude
1881          * factor of 0.0001 (as opposed to the default 0.00001) will
1882          * drop this sample to the noise floor.
1883          */
1884
1885         /* 16 bits => 96+4=100 dB dynamic range => 0.00001 */
1886         normalized_amplitude_during_loop = ((fluid_real_t)peak) / (INT24_MAX * 1.0f);
1887         result = FLUID_NOISE_FLOOR / normalized_amplitude_during_loop;
1888
1889         /* Store in sample */
1890         s->amplitude_that_reaches_noise_floor = (double)result;
1891         s->amplitude_that_reaches_noise_floor_is_valid = 1;
1892 #if 0
1893         printf("Sample peak detection: factor %f\n", (double)result);
1894 #endif
1895     }
1896
1897     return FLUID_OK;
1898 }
1899
1900 float
1901 fluid_voice_get_overflow_prio(fluid_voice_t *voice,
1902                               fluid_overflow_prio_t *score,
1903                               unsigned int cur_time)
1904 {
1905     float this_voice_prio = 0;
1906     int channel;
1907
1908     /* Are we already overflowing? */
1909     if(!voice->can_access_overflow_rvoice)
1910     {
1911         return OVERFLOW_PRIO_CANNOT_KILL;
1912     }
1913
1914     /* Is this voice on the drum channel?
1915      * Then it is very important.
1916      * Also skip the released and sustained scores.
1917      */
1918     if(voice->channel->channel_type == CHANNEL_TYPE_DRUM)
1919     {
1920         this_voice_prio += score->percussion;
1921     }
1922     else if(voice->has_noteoff)
1923     {
1924         /* Noteoff has */
1925         this_voice_prio += score->released;
1926     }
1927     else if(fluid_voice_is_sustained(voice) || fluid_voice_is_sostenuto(voice))
1928     {
1929         /* This voice is still active, since the sustain pedal is held down.
1930          * Consider it less important than non-sustained channels.
1931          * This decision is somehow subjective. But usually the sustain pedal
1932          * is used to play 'more-voices-than-fingers', so it shouldn't hurt
1933          * if we kill one voice.
1934          */
1935         this_voice_prio += score->sustained;
1936     }
1937
1938     /* We are not enthusiastic about releasing voices, which have just been started.
1939      * Otherwise hitting a chord may result in killing notes belonging to that very same
1940      * chord. So give newer voices a higher score. */
1941     if(score->age)
1942     {
1943         cur_time -= voice->start_time;
1944
1945         if(cur_time < 1)
1946         {
1947             cur_time = 1; // Avoid div by zero
1948         }
1949
1950         this_voice_prio += (score->age * voice->output_rate) / cur_time;
1951     }
1952
1953     /* take a rough estimate of loudness into account. Louder voices are more important. */
1954     if(score->volume)
1955     {
1956         fluid_real_t a = voice->attenuation;
1957
1958         if(voice->has_noteoff)
1959         {
1960             // FIXME: Should take into account where on the envelope we are...?
1961         }
1962
1963         if(a < 0.1)
1964         {
1965             a = 0.1; // Avoid div by zero
1966         }
1967
1968         this_voice_prio += score->volume / a;
1969     }
1970
1971     /* Check if this voice is on an important channel. If so, then add the
1972      * score for important channels */
1973     channel = fluid_voice_get_channel(voice);
1974
1975     if(channel < score->num_important_channels && score->important_channels[channel])
1976     {
1977         this_voice_prio += score->important;
1978     }
1979
1980     return this_voice_prio;
1981 }
1982
1983
1984 void fluid_voice_set_custom_filter(fluid_voice_t *voice, enum fluid_iir_filter_type type, enum fluid_iir_filter_flags flags)
1985 {
1986     UPDATE_RVOICE_GENERIC_I2(fluid_iir_filter_init, &voice->rvoice->resonant_custom_filter, type, flags);
1987 }
1988