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