1 /* FluidSynth - A Software Synthesizer
3 * Copyright (C) 2003 Peter Hanappe and others.
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.
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.
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
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"
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
37 /* min vol envelope release (to stop clicks) in SoundFont timecents */
38 #define FLUID_MIN_VOLENVRELEASE -7200.0f /* ~16ms */
41 static const int32_t INT24_MAX = (1 << (16 + 8 - 1));
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);
47 fluid_voice_get_lower_boundary_for_attenuation(fluid_voice_t *voice);
49 #define UPDATE_RVOICE0(proc) \
51 fluid_rvoice_param_t param[MAX_EVENT_PARAMS]; \
52 fluid_rvoice_eventhandler_push(voice->eventhandler, proc, voice->rvoice, param); \
55 #define UPDATE_RVOICE_GENERIC_R1(proc, obj, rarg) \
57 fluid_rvoice_param_t param[MAX_EVENT_PARAMS]; \
58 param[0].real = rarg; \
59 fluid_rvoice_eventhandler_push(voice->eventhandler, proc, obj, param); \
62 #define UPDATE_RVOICE_GENERIC_I1(proc, obj, iarg) \
64 fluid_rvoice_param_t param[MAX_EVENT_PARAMS]; \
66 fluid_rvoice_eventhandler_push(voice->eventhandler, proc, obj, param); \
69 #define UPDATE_RVOICE_GENERIC_I2(proc, obj, iarg1, iarg2) \
71 fluid_rvoice_param_t param[MAX_EVENT_PARAMS]; \
74 fluid_rvoice_eventhandler_push(voice->eventhandler, proc, obj, param); \
77 #define UPDATE_RVOICE_GENERIC_IR(proc, obj, iarg, rarg) \
79 fluid_rvoice_param_t param[MAX_EVENT_PARAMS]; \
81 param[1].real = rarg; \
82 fluid_rvoice_eventhandler_push(voice->eventhandler, proc, obj, param); \
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)
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)
93 static FLUID_INLINE void
94 fluid_voice_update_volenv(fluid_voice_t *voice,
96 fluid_adsr_env_section_t section,
99 fluid_real_t increment,
103 fluid_rvoice_param_t param[MAX_EVENT_PARAMS];
105 param[0].i = section;
107 param[2].real = coeff;
108 param[3].real = increment;
114 fluid_rvoice_eventhandler_push(voice->eventhandler,
115 fluid_adsr_env_set_data,
116 &voice->rvoice->envlfo.volenv,
121 fluid_adsr_env_set_data(&voice->rvoice->envlfo.volenv, param);
125 static FLUID_INLINE void
126 fluid_voice_update_modenv(fluid_voice_t *voice,
128 fluid_adsr_env_section_t section,
131 fluid_real_t increment,
135 fluid_rvoice_param_t param[MAX_EVENT_PARAMS];
137 param[0].i = section;
139 param[2].real = coeff;
140 param[3].real = increment;
146 fluid_rvoice_eventhandler_push(voice->eventhandler,
147 fluid_adsr_env_set_data,
148 &voice->rvoice->envlfo.modenv,
153 fluid_adsr_env_set_data(&voice->rvoice->envlfo.modenv, param);
157 static FLUID_INLINE void fluid_voice_sample_unref(fluid_sample_t **sample)
161 fluid_sample_decr_ref(*sample);
167 * Swaps the current rvoice with the current overflow_rvoice
169 static void fluid_voice_swap_rvoice(fluid_voice_t *voice)
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;
179 static void fluid_voice_initialize_rvoice(fluid_voice_t *voice, fluid_real_t output_rate)
181 fluid_rvoice_param_t param[MAX_EVENT_PARAMS];
183 FLUID_MEMSET(voice->rvoice, 0, sizeof(fluid_rvoice_t));
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.
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);
199 param[0].i = FLUID_IIR_LOWPASS;
201 fluid_iir_filter_init(&voice->rvoice->resonant_filter, param);
203 param[0].i = FLUID_IIR_DISABLED;
204 fluid_iir_filter_init(&voice->rvoice->resonant_custom_filter, param);
206 param[0].real = output_rate;
207 fluid_rvoice_set_output_rate(voice->rvoice, param);
214 new_fluid_voice(fluid_rvoice_eventhandler_t *handler, fluid_real_t output_rate)
216 fluid_voice_t *voice;
217 voice = FLUID_NEW(fluid_voice_t);
221 FLUID_LOG(FLUID_ERR, "Out of memory");
225 voice->can_access_rvoice = TRUE;
226 voice->can_access_overflow_rvoice = TRUE;
228 voice->rvoice = FLUID_NEW(fluid_rvoice_t);
229 voice->overflow_rvoice = FLUID_NEW(fluid_rvoice_t);
231 if(voice->rvoice == NULL || voice->overflow_rvoice == NULL)
233 FLUID_LOG(FLUID_ERR, "Out of memory");
234 delete_fluid_voice(voice);
238 voice->status = FLUID_VOICE_CLEAN;
239 voice->chan = NO_CHANNEL;
242 voice->eventhandler = handler;
243 voice->channel = NULL;
244 voice->sample = NULL;
245 voice->output_rate = output_rate;
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);
259 delete_fluid_voice(fluid_voice_t *voice)
261 fluid_return_if_fail(voice != NULL);
263 if(!voice->can_access_rvoice || !voice->can_access_overflow_rvoice)
265 FLUID_LOG(FLUID_WARN, "Deleting voice %u which has locked rvoices!", voice->id);
268 FLUID_FREE(voice->overflow_rvoice);
269 FLUID_FREE(voice->rvoice);
275 * Initialize the synthesis process
276 * inst_zone, the Instrument Zone contains the sample, Keyrange,Velrange
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.
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)
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. */
293 if(!voice->can_access_rvoice)
295 if(voice->can_access_overflow_rvoice)
297 fluid_voice_swap_rvoice(voice);
301 FLUID_LOG(FLUID_ERR, "Internal error: Cannot access an rvoice in fluid_voice_init!");
306 /* We are now guaranteed to have access to the rvoice */
310 fluid_voice_off(voice);
313 voice->zone_range = inst_zone_range; /* Instrument zone range for legato */
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);
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;
332 i = fluid_channel_get_interp_method(channel);
333 UPDATE_RVOICE_I1(fluid_rvoice_set_interp_method, i);
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));
344 voice->synth_gain = gain;
346 /* avoid division by zero later*/
347 if(voice->synth_gain < 0.0000001)
349 voice->synth_gain = 0.0000001;
352 UPDATE_RVOICE_R1(fluid_rvoice_set_synth_gain, voice->synth_gain);
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);
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);
369 * Update sample rate.
370 * @note If the voice is active, it will be turned off.
373 fluid_voice_set_output_rate(fluid_voice_t *voice, fluid_real_t value)
375 if(fluid_voice_is_playing(voice))
377 fluid_voice_off(voice);
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);
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
393 fluid_voice_gen_set(fluid_voice_t *voice, int i, float val)
395 voice->gen[i].val = val;
396 voice->gen[i].flags = GEN_SET;
398 if(i == GEN_SAMPLEMODE)
400 UPDATE_RVOICE_I1(fluid_rvoice_set_samplemode, (int) val);
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
411 fluid_voice_gen_incr(fluid_voice_t *voice, int i, float val)
413 voice->gen[i].val += val;
414 voice->gen[i].flags = GEN_SET;
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
424 fluid_voice_gen_get(fluid_voice_t *voice, int gen)
426 return voice->gen[gen].val;
429 fluid_real_t fluid_voice_gen_value(const fluid_voice_t *voice, int num)
431 /* This is an extension to the SoundFont standard. More
432 * documentation is available at the fluid_synth_set_gen2()
434 if(voice->gen[num].flags == GEN_ABS_NRPN)
436 return (fluid_real_t) voice->gen[num].nrpn;
440 return (fluid_real_t)(voice->gen[num].val + voice->gen[num].mod + voice->gen[num].nrpn);
447 void fluid_voice_start(fluid_voice_t *voice)
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.*/
453 fluid_voice_calculate_runtime_synthesis_parameters(voice);
455 #ifdef WITH_PROFILING
456 voice->ref = fluid_profile_ref();
459 voice->status = FLUID_VOICE_ON;
461 /* Increment voice count */
462 voice->channel->synth->active_voice_count++;
466 * Calculate the amplitude of a voice.
468 * @param gain The gain value in the range [0.0 ; 1.0]
469 * @return An amplitude used by rvoice_mixer's buffers
471 static FLUID_INLINE fluid_real_t
472 fluid_voice_calculate_gain_amplitude(const fluid_voice_t *voice, fluid_real_t gain)
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);
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.
486 fluid_real_t fluid_voice_calculate_pitch(fluid_voice_t *voice, int key)
488 fluid_tuning_t *tuning;
489 fluid_real_t x, pitch;
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.
497 if(fluid_channel_has_tuning(voice->channel))
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;
506 pitch = voice->gen[GEN_SCALETUNE].val
507 * (key - voice->root_pitch / 100.0f) + voice->root_pitch;
514 fluid_voice_calculate_gen_pitch(fluid_voice_t *voice)
516 voice->gen[GEN_PITCH].val = fluid_voice_calculate_pitch(voice, fluid_voice_get_actual_key(voice));
521 * fluid_voice_calculate_runtime_synthesis_parameters
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
531 fluid_voice_calculate_runtime_synthesis_parameters(fluid_voice_t *voice)
536 static int const list_of_generators_to_initialize[] =
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 */
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 */
588 GEN_CUSTOM_BALANCE, /* --- */
589 GEN_CUSTOM_FILTERFC, /* --- */
590 GEN_CUSTOM_FILTERQ /* --- */
593 /* When the voice is made ready for the synthesis process, a lot of
594 * voice-internal parameters have to be calculated.
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
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.
608 * Note: The generators have been initialized with
609 * fluid_gen_set_default_values.
612 for(i = 0; i < voice->mod_count; i++)
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); */
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.
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.
635 /* Calculate the voice parameter(s) dependent on each generator. */
636 for(n = 0; n < FLUID_N_ELEMENTS(list_of_generators_to_initialize); n++)
638 fluid_voice_update_param(voice, list_of_generators_to_initialize[n]);
641 /* Start portamento if enabled */
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;
648 if(fluid_channel_is_valid_note(fromkey))
650 /* Send portamento parameters to the voice dsp */
651 fluid_voice_update_portamento(voice, fromkey, fluid_voice_get_actual_key(voice));
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));
662 * calculate_hold_decay_buffers
665 calculate_hold_decay_buffers(fluid_voice_t *voice, int gen_base,
666 int gen_key2base, int is_decay)
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
677 fluid_real_t timecents;
678 fluid_real_t seconds;
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.
688 timecents = (fluid_voice_gen_value(voice, gen_base) + fluid_voice_gen_value(voice, gen_key2base) * (60.0 - fluid_voice_get_actual_key(voice)));
693 /* SF 2.01 section 8.1.3 # 28, 36 */
694 if(timecents > 8000.0)
701 /* SF 2.01 section 8.1.3 # 27, 35 */
707 /* SF 2.01 section 8.1.2 # 27, 35:
708 * The most negative number indicates no hold time
710 if(timecents <= -32768.)
716 /* SF 2.01 section 8.1.3 # 27, 28, 35, 36 */
717 if(timecents < -12000.0)
719 timecents = -12000.0;
722 seconds = fluid_tc2sec(timecents);
723 /* Each DSP loop processes FLUID_BUFSIZE samples. */
725 /* round to next full number of buffers */
726 buffers = (int)(((fluid_real_t)voice->output_rate * seconds)
727 / (fluid_real_t)FLUID_BUFSIZE
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.
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).
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
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)
753 * This is only necessary after changing a generator of an already operating voice.
754 * Most applications will not need this function.
757 fluid_voice_update_param(fluid_voice_t *voice, int gen)
759 unsigned int count, z;
760 fluid_real_t x = fluid_voice_gen_value(voice, gen);
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);
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)));
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)));
782 case GEN_ATTENUATION:
783 voice->attenuation = x;
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);
792 /* The pitch is calculated from three different generators.
793 * Read comment in fluidsynth.h about GEN_PITCH.
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);
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));
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));
819 case GEN_OVERRIDEROOTKEY:
821 /* This is a non-realtime parameter. Therefore the .mod part of the generator
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).
827 if(voice->sample != NULL)
829 if(voice->gen[GEN_OVERRIDEROOTKEY].val > -1) //FIXME: use flag instead of -1
831 voice->root_pitch = voice->gen[GEN_OVERRIDEROOTKEY].val * 100.0f
832 - voice->sample->pitchadj;
836 voice->root_pitch = voice->sample->origpitch * 100.0f - voice->sample->pitchadj;
839 x = (fluid_ct2hz(voice->root_pitch) * ((fluid_real_t) voice->output_rate / voice->sample->samplerate));
843 if(voice->gen[GEN_OVERRIDEROOTKEY].val > -1) //FIXME: use flag instead of -1
845 voice->root_pitch = voice->gen[GEN_OVERRIDEROOTKEY].val * 100.0f;
849 voice->root_pitch = 0;
852 x = fluid_ct2hz(voice->root_pitch);
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);
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]
867 UPDATE_RVOICE_GENERIC_R1(fluid_iir_filter_set_fres, &voice->rvoice->resonant_filter, x);
871 UPDATE_RVOICE_GENERIC_R1(fluid_iir_filter_set_q, &voice->rvoice->resonant_filter, x);
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);
879 case GEN_CUSTOM_FILTERQ:
880 UPDATE_RVOICE_GENERIC_R1(fluid_iir_filter_set_q, &voice->rvoice->resonant_custom_filter, x);
883 case GEN_MODLFOTOPITCH:
884 fluid_clip(x, -12000.0, 12000.0);
885 UPDATE_RVOICE_R1(fluid_rvoice_set_modlfo_to_pitch, x);
888 case GEN_MODLFOTOVOL:
889 fluid_clip(x, -960.0, 960.0);
890 UPDATE_RVOICE_R1(fluid_rvoice_set_modlfo_to_vol, x);
893 case GEN_MODLFOTOFILTERFC:
894 fluid_clip(x, -12000, 12000);
895 UPDATE_RVOICE_R1(fluid_rvoice_set_modlfo_to_fc, x);
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);
905 /* - the frequency is converted into a delta value, per buffer of FLUID_BUFSIZE samples
906 * - the delay into a sample delay
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);
916 * - the frequency is converted into a delta value, per buffer of FLUID_BUFSIZE samples
917 * - the delay into a sample delay
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);
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);
930 case GEN_VIBLFOTOPITCH:
931 fluid_clip(x, -12000.0, 12000.0);
932 UPDATE_RVOICE_R1(fluid_rvoice_set_viblfo_to_pitch, x);
936 /* GEN_KEYNUM: SF2.01 page 46, item 46
938 * If this generator is active, it forces the key number to its
939 * value. Non-realtime controller.
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.
945 /* 2017-09-02: do not change the voice's key here, otherwise it will
946 * never be released on a noteoff event
949 x = fluid_voice_gen_value(voice, GEN_KEYNUM);
960 /* GEN_VELOCITY: SF2.01 page 46, item 47
962 * If this generator is active, it forces the velocity to its
963 * value. Non-realtime controller.
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.
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
973 x = fluid_voice_gen_value(voice, GEN_VELOCITY);
983 case GEN_MODENVTOPITCH:
984 fluid_clip(x, -12000.0, 12000.0);
985 UPDATE_RVOICE_R1(fluid_rvoice_set_modenv_to_pitch, x);
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
993 fluid_clip(x, -12000.0, 12000.0);
994 UPDATE_RVOICE_R1(fluid_rvoice_set_modenv_to_fc, x);
998 /* sample start and ends points
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.
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)
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);
1016 z = voice->sample->start + (int)start_fine + 32768 * (int)start_coar;
1017 UPDATE_RVOICE_I1(fluid_rvoice_set_start, z);
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)
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);
1029 z = voice->sample->end + (int)end_fine + 32768 * (int)end_coar;
1030 UPDATE_RVOICE_I1(fluid_rvoice_set_end, z);
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)
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);
1042 z = voice->sample->loopstart + (int)lstart_fine + 32768 * (int)lstart_coar;
1043 UPDATE_RVOICE_I1(fluid_rvoice_set_loopstart, z);
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)
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);
1055 z = voice->sample->loopend + (int)lend_fine + 32768 * (int)lend_coar;
1056 UPDATE_RVOICE_I1(fluid_rvoice_set_loopend, z);
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)
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
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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
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).
1164 * The update is done in three steps:
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.
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
1174 * - For every changed generator, convert its value to the correct
1175 * unit of the corresponding DSP parameter
1177 int fluid_voice_modulate(fluid_voice_t *voice, int cc, int ctrl)
1182 fluid_real_t modval;
1184 /* printf("Chan=%d, CC=%d, Src=%d, Val=%d\n", voice->channel->channum, cc, ctrl, val); */
1186 for(i = 0; i < voice->mod_count; i++)
1189 mod = &voice->mod[i];
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))
1196 gen = fluid_mod_get_dest(mod);
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++)
1203 if(fluid_mod_has_dest(&voice->mod[k], gen))
1205 modval += fluid_mod_get_value(&voice->mod[k], voice);
1209 fluid_gen_set_mod(&voice->gen[gen], modval);
1211 /* step 3: now that we have the new value of the generator,
1212 * recalculate the parameter values that are derived from the
1214 fluid_voice_update_param(voice, gen);
1222 * Update all the modulators. This function is called after a
1223 * ALL_CTRL_OFF MIDI message has been received (CC 121).
1226 int fluid_voice_modulate_all(fluid_voice_t *voice)
1230 fluid_real_t modval;
1232 /* Loop through all the modulators.
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,
1241 for(i = 0; i < voice->mod_count; i++)
1244 mod = &voice->mod[i];
1245 gen = fluid_mod_get_dest(mod);
1248 /* Accumulate the modulation values of all the modulators with
1249 * destination generator 'gen' */
1250 for(k = 0; k < voice->mod_count; k++)
1252 if(fluid_mod_has_dest(&voice->mod[k], gen))
1254 modval += fluid_mod_get_value(&voice->mod[k], voice);
1258 fluid_gen_set_mod(&voice->gen[gen], modval);
1260 /* Update the parameter values that are depend on the generator
1262 fluid_voice_update_param(voice, gen);
1268 /** legato update functions --------------------------------------------------*/
1269 /* Updates voice portamento parameters
1271 * @voice voice the synthesis voice
1272 * @fromkey the beginning pitch of portamento.
1273 * @tokey the ending pitch of portamento.
1275 * The function calculates pitch offset and increment, then these parameters
1276 * are send to the dsp.
1278 void fluid_voice_update_portamento(fluid_voice_t *voice, int fromkey, int tokey)
1281 fluid_channel_t *channel = voice->channel;
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;
1288 /* Calculates increment countinc */
1289 /* Increment is function of PortamentoTime (ms)*/
1290 unsigned int countinc = (unsigned int)(((fluid_real_t)voice->output_rate *
1292 (fluid_real_t)fluid_channel_portamentotime(channel)) /
1293 (fluid_real_t)FLUID_BUFSIZE + 0.5);
1295 /* Send portamento parameters to the voice dsp */
1296 UPDATE_RVOICE_GENERIC_IR(fluid_rvoice_set_portamento, voice->rvoice, countinc, pitchoffset);
1299 /*---------------------------------------------------------------*/
1300 /*legato mode 1: multi_retrigger
1302 * Modulates all generators dependent of key,vel.
1303 * Forces the voice envelopes in the attack section (legato mode 1).
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.
1309 void fluid_voice_update_multi_retrigger_attack(fluid_voice_t *voice,
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);
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);
1325 /* Updates pitch generator */
1326 fluid_voice_calculate_gen_pitch(voice);
1327 fluid_voice_update_param(voice, GEN_PITCH);
1329 /* updates adsr generator */
1330 UPDATE_RVOICE0(fluid_rvoice_multi_retrigger_attack);
1332 /** end of legato update functions */
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().
1342 fluid_voice_release(fluid_voice_t *voice)
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
1350 * fluid_voice_noteoff
1352 * Sending a noteoff event will advance the envelopes to section 5 (release).
1353 * The function is convenient for polyphonic or monophonic note
1356 fluid_voice_noteoff(fluid_voice_t *voice)
1358 fluid_channel_t *channel;
1360 fluid_profile(FLUID_PROF_VOICE_NOTE, voice->ref, 0, 0);
1362 channel = voice->channel;
1364 /* Sustain a note under Sostenuto pedal */
1365 if(fluid_channel_sostenuto(channel) &&
1366 channel->sostenuto_orderid > voice->id)
1368 // Sostenuto depressed after note
1369 voice->status = FLUID_VOICE_HELD_BY_SOSTENUTO;
1371 /* Or sustain a note under Sustain pedal */
1372 else if(fluid_channel_sustained(channel))
1374 voice->status = FLUID_VOICE_SUSTAINED;
1376 /* Or force the voice to release stage */
1379 fluid_voice_release(voice);
1384 * fluid_voice_kill_excl
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.
1396 fluid_voice_kill_excl(fluid_voice_t *voice)
1399 unsigned int at_tick;
1401 if(!fluid_voice_is_playing(voice))
1406 /* Turn off the exclusive class information for this voice,
1407 so that it doesn't get killed twice
1409 fluid_voice_gen_set(voice, GEN_EXCLUSIVECLASS, 0);
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);
1416 /* Speed up the modulation envelope */
1417 fluid_voice_gen_set(voice, GEN_MODENVRELEASE, -200);
1418 fluid_voice_update_param(voice, GEN_MODENVRELEASE);
1420 at_tick = fluid_channel_get_min_note_length_ticks(voice->channel);
1421 UPDATE_RVOICE_I1(fluid_rvoice_noteoff, at_tick);
1428 * Called by fluid_synth when the overflow rvoice can be reclaimed.
1430 void fluid_voice_overflow_rvoice_finished(fluid_voice_t *voice)
1432 voice->can_access_overflow_rvoice = 1;
1433 fluid_voice_sample_unref(&voice->overflow_rvoice->dsp.sample);
1439 * Force the voice into finished stage. Useful anywhere a voice
1440 * needs to be cancelled from MIDI API.
1442 void fluid_voice_off(fluid_voice_t *voice)
1444 UPDATE_RVOICE0(fluid_rvoice_voiceoff); /* request to finish the voice */
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().
1455 fluid_voice_stop(fluid_voice_t *voice)
1457 fluid_profile(FLUID_PROF_VOICE_RELEASE, voice->ref, 0, 0);
1459 voice->chan = NO_CHANNEL;
1461 if(voice->can_access_rvoice)
1463 fluid_voice_sample_unref(&voice->rvoice->dsp.sample);
1466 voice->status = FLUID_VOICE_OFF;
1467 voice->has_noteoff = 1;
1469 /* Decrement the reference count of the sample. */
1470 fluid_voice_sample_unref(&voice->sample);
1472 /* Decrement voice count */
1473 voice->channel->synth->active_voice_count--;
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.
1487 fluid_voice_add_mod(fluid_voice_t *voice, fluid_mod_t *mod, int mode)
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.
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 */
1506 FLUID_LOG(FLUID_WARN, "Ignoring invalid controller, using non-CC source %i.", mod->src1);
1510 if(mode == FLUID_VOICE_ADD)
1513 /* if identical modulator exists, add them */
1514 for(i = 0; i < voice->mod_count; i++)
1516 if(fluid_mod_test_identity(&voice->mod[i], mod))
1518 // printf("Adding modulator...\n");
1519 voice->mod[i].amount += mod->amount;
1525 else if(mode == FLUID_VOICE_OVERWRITE)
1528 /* if identical modulator exists, replace it (only the amount has to be changed) */
1529 for(i = 0; i < voice->mod_count; i++)
1531 if(fluid_mod_test_identity(&voice->mod[i], mod))
1533 // printf("Replacing modulator...amount is %f\n",mod->amount);
1534 voice->mod[i].amount = mod->amount;
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)
1545 fluid_mod_clone(&voice->mod[voice->mod_count++], mod);
1549 FLUID_LOG(FLUID_WARN, "Voice %i has more modulators than supported, ignoring.", voice->id);
1554 * Get the unique ID of the noteon-event.
1555 * @param voice Voice instance
1556 * @return Note on unique ID
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.
1563 * Before modifying an existing voice, check
1564 * - that its state is still 'playing'
1565 * - that the ID is still the same
1567 * Otherwise the voice has finished playing.
1569 unsigned int fluid_voice_get_id(const fluid_voice_t *voice)
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
1579 int fluid_voice_is_playing(const fluid_voice_t *voice)
1581 return (voice->status == FLUID_VOICE_ON)
1582 || fluid_voice_is_sustained(voice)
1583 || fluid_voice_is_sostenuto(voice);
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
1593 int fluid_voice_is_on(const fluid_voice_t *voice)
1595 return (voice->status == FLUID_VOICE_ON && !voice->has_noteoff);
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
1604 int fluid_voice_is_sustained(const fluid_voice_t *voice)
1606 return (voice->status == FLUID_VOICE_SUSTAINED);
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
1615 int fluid_voice_is_sostenuto(const fluid_voice_t *voice)
1617 return (voice->status == FLUID_VOICE_HELD_BY_SOSTENUTO);
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
1626 int fluid_voice_get_channel(const fluid_voice_t *voice)
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
1639 int fluid_voice_get_actual_key(const fluid_voice_t *voice)
1641 fluid_real_t x = fluid_voice_gen_value(voice, GEN_KEYNUM);
1649 return fluid_voice_get_key(voice);
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
1660 int fluid_voice_get_key(const fluid_voice_t *voice)
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
1673 int fluid_voice_get_actual_velocity(const fluid_voice_t *voice)
1675 fluid_real_t x = fluid_voice_gen_value(voice, GEN_VELOCITY);
1683 return fluid_voice_get_velocity(voice);
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
1694 int fluid_voice_get_velocity(const fluid_voice_t *voice)
1700 * fluid_voice_get_lower_boundary_for_attenuation
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.
1712 fluid_voice_get_lower_boundary_for_attenuation(fluid_voice_t *voice)
1716 fluid_real_t possible_att_reduction_cB = 0;
1717 fluid_real_t lower_bound;
1719 for(i = 0; i < voice->mod_count; i++)
1721 mod = &voice->mod[i];
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)))
1735 fluid_real_t current_val = fluid_mod_get_value(mod, voice);
1736 fluid_real_t v = fabs(mod->amount);
1738 if((mod->src1 == FLUID_MOD_PITCHWHEEL)
1739 || (mod->flags1 & FLUID_MOD_BIPOLAR)
1740 || (mod->flags2 & FLUID_MOD_BIPOLAR)
1741 || (mod->amount < 0))
1743 /* Can this modulator produce a negative contribution? */
1748 /* No negative value possible. But still, the minimum contribution is 0. */
1755 * - possible_att_reduction_cB += 4100
1759 possible_att_reduction_cB += (current_val - v);
1764 lower_bound = voice->attenuation - possible_att_reduction_cB;
1766 /* SF2.01 specs do not allow negative attenuation */
1778 int fluid_voice_set_param(fluid_voice_t *voice, int gen, fluid_real_t nrpn_value, int abs)
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);
1786 int fluid_voice_set_gain(fluid_voice_t *voice, fluid_real_t gain)
1788 fluid_real_t left, right, reverb, chorus;
1790 /* avoid division by zero*/
1791 if(gain < 0.0000001)
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);
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);
1814 * - determine the peak level
1815 * - Calculate, what factor will make the loop inaudible
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
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.
1830 fluid_voice_optimize_sample(fluid_sample_t *s)
1832 int32_t peak_max = 0;
1833 int32_t peak_min = 0;
1835 fluid_real_t normalized_amplitude_during_loop;
1839 /* ignore disabled samples */
1840 if(s->start == s->end)
1845 if(!s->amplitude_that_reaches_noise_floor_is_valid) /* Only once */
1848 for(i = s->loopstart; i < s->loopend; i++)
1850 int32_t val = fluid_rvoice_get_sample(s->data, s->data24, i);
1856 else if(val < peak_min)
1862 /* Determine the peak level */
1863 if(peak_max > -peak_min)
1874 /* Avoid division by zero */
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.
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;
1889 /* Store in sample */
1890 s->amplitude_that_reaches_noise_floor = (double)result;
1891 s->amplitude_that_reaches_noise_floor_is_valid = 1;
1893 printf("Sample peak detection: factor %f\n", (double)result);
1901 fluid_voice_get_overflow_prio(fluid_voice_t *voice,
1902 fluid_overflow_prio_t *score,
1903 unsigned int cur_time)
1905 float this_voice_prio = 0;
1908 /* Are we already overflowing? */
1909 if(!voice->can_access_overflow_rvoice)
1911 return OVERFLOW_PRIO_CANNOT_KILL;
1914 /* Is this voice on the drum channel?
1915 * Then it is very important.
1916 * Also skip the released and sustained scores.
1918 if(voice->channel->channel_type == CHANNEL_TYPE_DRUM)
1920 this_voice_prio += score->percussion;
1922 else if(voice->has_noteoff)
1925 this_voice_prio += score->released;
1927 else if(fluid_voice_is_sustained(voice) || fluid_voice_is_sostenuto(voice))
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.
1935 this_voice_prio += score->sustained;
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. */
1943 cur_time -= voice->start_time;
1947 cur_time = 1; // Avoid div by zero
1950 this_voice_prio += (score->age * voice->output_rate) / cur_time;
1953 /* take a rough estimate of loudness into account. Louder voices are more important. */
1956 fluid_real_t a = voice->attenuation;
1958 if(voice->has_noteoff)
1960 // FIXME: Should take into account where on the envelope we are...?
1965 a = 0.1; // Avoid div by zero
1968 this_voice_prio += score->volume / a;
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);
1975 if(channel < score->num_important_channels && score->important_channels[channel])
1977 this_voice_prio += score->important;
1980 return this_voice_prio;
1984 void fluid_voice_set_custom_filter(fluid_voice_t *voice, enum fluid_iir_filter_type type, enum fluid_iir_filter_flags flags)
1986 UPDATE_RVOICE_GENERIC_I2(fluid_iir_filter_init, &voice->rvoice->resonant_custom_filter, type, flags);