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 Library General Public License
7 * as published by the Free Software Foundation; either version 2 of
8 * the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Library General Public License for more details.
15 * You should have received a copy of the GNU Library General Public
16 * License along with this library; if not, write to the Free
17 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
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"
31 /* used for filter turn off optimization - if filter cutoff is above the
32 specified value and filter q is below the other value, turn filter off */
33 #define FLUID_MAX_AUDIBLE_FILTER_FC 19000.0f
34 #define FLUID_MIN_AUDIBLE_FILTER_Q 1.2f
36 /* min vol envelope release (to stop clicks) in SoundFont timecents */
37 #define FLUID_MIN_VOLENVRELEASE -7200.0f /* ~16ms */
39 static int fluid_voice_calculate_runtime_synthesis_parameters(fluid_voice_t* voice);
40 static int calculate_hold_decay_buffers(fluid_voice_t* voice, int gen_base,
41 int gen_key2base, int is_decay);
43 fluid_voice_get_lower_boundary_for_attenuation(fluid_voice_t* voice);
45 #define UPDATE_RVOICE0(proc) \
47 if (voice->can_access_rvoice) proc(voice->rvoice); \
48 else fluid_rvoice_eventhandler_push(voice->channel->synth->eventhandler, \
49 proc, voice->rvoice, 0, 0.0f); \
52 #define UPDATE_RVOICE_PTR(proc, obj) \
54 if (voice->can_access_rvoice) proc(voice->rvoice, obj); \
55 else fluid_rvoice_eventhandler_push_ptr(voice->channel->synth->eventhandler, \
56 proc, voice->rvoice, obj); \
60 #define UPDATE_RVOICE_GENERIC_R1(proc, obj, rarg) \
62 if (voice->can_access_rvoice) proc(obj, rarg); \
63 else fluid_rvoice_eventhandler_push(voice->channel->synth->eventhandler, \
64 proc, obj, 0, rarg); \
67 #define UPDATE_RVOICE_GENERIC_I1(proc, obj, iarg) \
69 if (voice->can_access_rvoice) proc(obj, iarg); \
70 else fluid_rvoice_eventhandler_push(voice->channel->synth->eventhandler, \
71 proc, obj, iarg, 0.0f); \
74 #define UPDATE_RVOICE_GENERIC_IR(proc, obj, iarg, rarg) \
76 if (voice->can_access_rvoice) proc(obj, iarg, rarg); \
77 else fluid_rvoice_eventhandler_push(voice->channel->synth->eventhandler, \
78 proc, obj, iarg, rarg); \
81 #define UPDATE_RVOICE_GENERIC_ALL(proc, obj, iarg, r1, r2, r3, r4, r5) \
83 if (voice->can_access_rvoice) proc(obj, iarg, r1, r2, r3, r4, r5); \
84 else fluid_rvoice_eventhandler_push5(voice->channel->synth->eventhandler, \
85 proc, obj, iarg, r1, r2, r3, r4, r5); \
89 #define UPDATE_RVOICE_VOLENV(section, arg1, arg2, arg3, arg4, arg5) \
91 fluid_adsr_env_set_data(&voice->volenv, section, arg1, arg2, arg3, arg4, arg5) \
92 UPDATE_RVOICE_GENERIC_ALL(fluid_adsr_env_set_data, &voice->rvoice->envlfo.volenv, section, arg1, arg2, arg3, arg4, arg5) \
95 #define UPDATE_RVOICE_MODENV(section, arg1, arg2, arg3, arg4, arg5) \
96 UPDATE_RVOICE_GENERIC_ALL(fluid_adsr_env_set_data, &voice->rvoice->envlfo.modenv, section, arg1, arg2, arg3, arg4, arg5)
98 #define UPDATE_RVOICE_R1(proc, arg1) UPDATE_RVOICE_GENERIC_R1(proc, voice->rvoice, arg1)
99 #define UPDATE_RVOICE_I1(proc, arg1) UPDATE_RVOICE_GENERIC_I1(proc, voice->rvoice, arg1)
100 #define UPDATE_RVOICE_FILTER1(proc, arg1) UPDATE_RVOICE_GENERIC_R1(proc, &voice->rvoice->resonant_filter, arg1)
102 #define UPDATE_RVOICE2(proc, iarg, rarg) UPDATE_RVOICE_GENERIC_IR(proc, voice->rvoice, iarg, rarg)
103 #define UPDATE_RVOICE_BUFFERS2(proc, iarg, rarg) UPDATE_RVOICE_GENERIC_IR(proc, &voice->rvoice->buffers, iarg, rarg)
104 #define UPDATE_RVOICE_ENVLFO_R1(proc, envp, rarg) UPDATE_RVOICE_GENERIC_R1(proc, &voice->rvoice->envlfo.envp, rarg)
105 #define UPDATE_RVOICE_ENVLFO_I1(proc, envp, iarg) UPDATE_RVOICE_GENERIC_I1(proc, &voice->rvoice->envlfo.envp, iarg)
108 fluid_voice_update_volenv(fluid_voice_t* voice,
109 fluid_adsr_env_section_t section,
112 fluid_real_t increment,
116 fluid_adsr_env_set_data(&voice->volenv, section, count, coeff, increment,
118 UPDATE_RVOICE_GENERIC_ALL(fluid_adsr_env_set_data,
119 &voice->rvoice->envlfo.volenv, section, count,
120 coeff, increment, min, max);
124 fluid_voice_update_modenv(fluid_voice_t* voice,
125 fluid_adsr_env_section_t section,
128 fluid_real_t increment,
132 UPDATE_RVOICE_GENERIC_ALL(fluid_adsr_env_set_data,
133 &voice->rvoice->envlfo.modenv, section, count,
134 coeff, increment, min, max);
137 static inline void fluid_sample_null_ptr(fluid_sample_t** sample)
139 if (*sample != NULL) {
140 fluid_sample_decr_ref(*sample);
146 * Swaps the current rvoice with the current overflow_rvoice
148 static void fluid_voice_swap_rvoice(fluid_voice_t* voice)
150 fluid_rvoice_t* rtemp = voice->rvoice;
151 int ctemp = voice->can_access_rvoice;
152 voice->rvoice = voice->overflow_rvoice;
153 voice->can_access_rvoice = voice->can_access_overflow_rvoice;
154 voice->overflow_rvoice = rtemp;
155 voice->can_access_overflow_rvoice = ctemp;
158 static void fluid_voice_initialize_rvoice(fluid_voice_t* voice)
160 FLUID_MEMSET(voice->rvoice, 0, sizeof(fluid_rvoice_t));
162 /* The 'sustain' and 'finished' segments of the volume / modulation
163 * envelope are constant. They are never affected by any modulator
164 * or generator. Therefore it is enough to initialize them once
165 * during the lifetime of the synth.
167 fluid_voice_update_volenv(voice, FLUID_VOICE_ENVSUSTAIN,
168 0xffffffff, 1.0f, 0.0f, -1.0f, 2.0f);
169 fluid_voice_update_volenv(voice, FLUID_VOICE_ENVFINISHED,
170 0xffffffff, 0.0f, 0.0f, -1.0f, 1.0f);
171 fluid_voice_update_modenv(voice, FLUID_VOICE_ENVSUSTAIN,
172 0xffffffff, 1.0f, 0.0f, -1.0f, 2.0f);
173 fluid_voice_update_modenv(voice, FLUID_VOICE_ENVFINISHED,
174 0xffffffff, 0.0f, 0.0f, -1.0f, 1.0f);
181 new_fluid_voice(fluid_real_t output_rate)
183 fluid_voice_t* voice;
184 voice = FLUID_NEW(fluid_voice_t);
186 FLUID_LOG(FLUID_ERR, "Out of memory");
189 voice->rvoice = FLUID_NEW(fluid_rvoice_t);
190 voice->overflow_rvoice = FLUID_NEW(fluid_rvoice_t);
191 if (voice->rvoice == NULL || voice->overflow_rvoice == NULL) {
192 FLUID_LOG(FLUID_ERR, "Out of memory");
193 FLUID_FREE(voice->rvoice);
198 voice->status = FLUID_VOICE_CLEAN;
199 voice->chan = NO_CHANNEL;
202 voice->channel = NULL;
203 voice->sample = NULL;
205 /* Initialize both the rvoice and overflow_rvoice */
206 voice->can_access_rvoice = 1;
207 voice->can_access_overflow_rvoice = 1;
208 fluid_voice_initialize_rvoice(voice);
209 fluid_voice_swap_rvoice(voice);
210 fluid_voice_initialize_rvoice(voice);
212 fluid_voice_set_output_rate(voice, output_rate);
221 delete_fluid_voice(fluid_voice_t* voice)
226 if (!voice->can_access_rvoice || !voice->can_access_overflow_rvoice) {
227 /* stop rvoice before deleting voice! */
230 FLUID_FREE(voice->overflow_rvoice);
231 FLUID_FREE(voice->rvoice);
238 * Initialize the synthesis process
241 fluid_voice_init(fluid_voice_t* voice, fluid_sample_t* sample,
242 fluid_channel_t* channel, int key, int vel, unsigned int id,
243 unsigned int start_time, fluid_real_t gain)
245 /* Note: The voice parameters will be initialized later, when the
246 * generators have been retrieved from the sound font. Here, only
247 * the 'working memory' of the voice (position in envelopes, history
248 * of IIR filters, position in sample etc) is initialized. */
251 if (!voice->can_access_rvoice) {
252 if (voice->can_access_overflow_rvoice)
253 fluid_voice_swap_rvoice(voice);
255 FLUID_LOG(FLUID_ERR, "Internal error: Cannot access an rvoice in fluid_voice_init!");
259 /* We are now guaranteed to have access to the rvoice */
262 fluid_voice_off(voice);
265 voice->chan = fluid_channel_get_num(channel);
266 voice->key = (unsigned char) key;
267 voice->vel = (unsigned char) vel;
268 voice->channel = channel;
269 voice->mod_count = 0;
270 voice->start_time = start_time;
272 voice->has_noteoff = 0;
273 UPDATE_RVOICE0(fluid_rvoice_reset);
275 /* Increment the reference count of the sample to prevent the
276 unloading of the soundfont while this voice is playing,
277 once for us and once for the rvoice. */
278 fluid_sample_incr_ref(sample);
279 UPDATE_RVOICE_PTR(fluid_rvoice_set_sample, sample);
280 fluid_sample_incr_ref(sample);
281 voice->sample = sample;
283 i = fluid_channel_get_interp_method(channel);
284 UPDATE_RVOICE_I1(fluid_rvoice_set_interp_method, i);
286 /* Set all the generators to their default value, according to SF
287 * 2.01 section 8.1.3 (page 48). The value of NRPN messages are
288 * copied from the channel to the voice's generators. The sound font
289 * loader overwrites them. The generator values are later converted
290 * into voice parameters in
291 * fluid_voice_calculate_runtime_synthesis_parameters. */
292 fluid_gen_init(&voice->gen[0], channel);
293 UPDATE_RVOICE_I1(fluid_rvoice_set_samplemode, _SAMPLEMODE(voice));
295 voice->synth_gain = gain;
296 /* avoid division by zero later*/
297 if (voice->synth_gain < 0.0000001){
298 voice->synth_gain = 0.0000001;
300 UPDATE_RVOICE_R1(fluid_rvoice_set_synth_gain, voice->synth_gain);
302 /* Set up buffer mapping, should be done more flexible in the future. */
303 i = channel->synth->audio_groups;
304 UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_mapping, 2, i*2 + SYNTH_REVERB_CHANNEL);
305 UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_mapping, 3, i*2 + SYNTH_CHORUS_CHANNEL);
306 i = 2 * (voice->chan % i);
307 UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_mapping, 0, i);
308 UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_mapping, 1, i+1);
315 * Update sample rate.
316 * NOTE: If the voice is active, it will be turned off.
319 fluid_voice_set_output_rate(fluid_voice_t* voice, fluid_real_t value)
322 fluid_voice_off(voice);
324 voice->output_rate = value;
325 UPDATE_RVOICE_R1(fluid_rvoice_set_output_rate, value);
326 /* Update the other rvoice as well */
327 fluid_voice_swap_rvoice(voice);
328 UPDATE_RVOICE_R1(fluid_rvoice_set_output_rate, value);
329 fluid_voice_swap_rvoice(voice);
336 * Set the value of a generator.
337 * @param voice Voice instance
338 * @param i Generator ID (#fluid_gen_type)
339 * @param val Generator value
342 fluid_voice_gen_set(fluid_voice_t* voice, int i, float val)
344 voice->gen[i].val = val;
345 voice->gen[i].flags = GEN_SET;
346 if (i == GEN_SAMPLEMODE)
347 UPDATE_RVOICE_I1(fluid_rvoice_set_samplemode, (int) val);
351 * Offset the value of a generator.
352 * @param voice Voice instance
353 * @param i Generator ID (#fluid_gen_type)
354 * @param val Value to add to the existing value
357 fluid_voice_gen_incr(fluid_voice_t* voice, int i, float val)
359 voice->gen[i].val += val;
360 voice->gen[i].flags = GEN_SET;
364 * Get the value of a generator.
365 * @param voice Voice instance
366 * @param gen Generator ID (#fluid_gen_type)
367 * @return Current generator value
370 fluid_voice_gen_get(fluid_voice_t* voice, int gen)
372 return voice->gen[gen].val;
375 fluid_real_t fluid_voice_gen_value(fluid_voice_t* voice, int num)
377 /* This is an extension to the SoundFont standard. More
378 * documentation is available at the fluid_synth_set_gen2()
380 if (voice->gen[num].flags == GEN_ABS_NRPN) {
381 return (fluid_real_t) voice->gen[num].nrpn;
383 return (fluid_real_t) (voice->gen[num].val + voice->gen[num].mod + voice->gen[num].nrpn);
389 * Synthesize a voice to a buffer.
391 * @param voice Voice to synthesize
392 * @param dsp_buf Audio buffer to synthesize to (#FLUID_BUFSIZE in length)
393 * @return Count of samples written to dsp_buf (can be 0)
395 * Panning, reverb and chorus are processed separately. The dsp interpolation
396 * routine is in (fluid_dsp_float.c).
399 fluid_voice_write (fluid_voice_t* voice, fluid_real_t *dsp_buf)
402 if (!voice->can_access_rvoice)
405 result = fluid_rvoice_write(voice->rvoice, dsp_buf);
410 if ((result < FLUID_BUFSIZE) && _PLAYING(voice)) /* Voice finished by itself */
411 fluid_voice_off(voice);
418 * Mix voice data to left/right (panning), reverb and chorus buffers.
419 * @param count Number of samples
420 * @param dsp_buf Source buffer
421 * @param voice Voice to mix
422 * @param left_buf Left audio buffer
423 * @param right_buf Right audio buffer
424 * @param reverb_buf Reverb buffer
425 * @param chorus_buf Chorus buffer
429 fluid_voice_mix (fluid_voice_t *voice, int count, fluid_real_t* dsp_buf,
430 fluid_real_t* left_buf, fluid_real_t* right_buf,
431 fluid_real_t* reverb_buf, fluid_real_t* chorus_buf)
433 fluid_rvoice_buffers_t buffers;
434 fluid_real_t* dest_buf[4] = {left_buf, right_buf, reverb_buf, chorus_buf};
436 fluid_rvoice_buffers_set_amp(&buffers, 0, voice->amp_left);
437 fluid_rvoice_buffers_set_amp(&buffers, 1, voice->amp_right);
438 fluid_rvoice_buffers_set_amp(&buffers, 2, voice->amp_reverb);
439 fluid_rvoice_buffers_set_amp(&buffers, 3, voice->amp_chorus);
441 fluid_rvoice_buffers_mix(&buffers, dsp_buf, count, dest_buf, 4);
443 fluid_check_fpe ("voice_mix");
451 void fluid_voice_start(fluid_voice_t* voice)
453 /* The maximum volume of the loop is calculated and cached once for each
454 * sample with its nominal loop settings. This happens, when the sample is used
455 * for the first time.*/
457 fluid_voice_calculate_runtime_synthesis_parameters(voice);
459 voice->ref = fluid_profile_ref();
461 voice->status = FLUID_VOICE_ON;
463 /* Increment voice count */
464 voice->channel->synth->active_voice_count++;
468 fluid_voice_calculate_gen_pitch(fluid_voice_t* voice)
470 fluid_tuning_t* tuning;
473 /* The GEN_PITCH is a hack to fit the pitch bend controller into the
474 * modulator paradigm. Now the nominal pitch of the key is set.
475 * Note about SCALETUNE: SF2.01 8.1.3 says, that this generator is a
476 * non-realtime parameter. So we don't allow modulation (as opposed
477 * to _GEN(voice, GEN_SCALETUNE) When the scale tuning is varied,
478 * one key remains fixed. Here C3 (MIDI number 60) is used.
480 if (fluid_channel_has_tuning(voice->channel)) {
481 tuning = fluid_channel_get_tuning (voice->channel);
482 x = fluid_tuning_get_pitch (tuning, (int)(voice->root_pitch / 100.0f));
483 voice->gen[GEN_PITCH].val = voice->gen[GEN_SCALETUNE].val / 100.0f *
484 (fluid_tuning_get_pitch (tuning, voice->key) - x) + x;
486 voice->gen[GEN_PITCH].val = voice->gen[GEN_SCALETUNE].val
487 * (voice->key - voice->root_pitch / 100.0f) + voice->root_pitch;
493 * fluid_voice_calculate_runtime_synthesis_parameters
495 * in this function we calculate the values of all the parameters. the
496 * parameters are converted to their most useful unit for the DSP
497 * algorithm, for example, number of samples instead of
498 * timecents. Some parameters keep their "perceptual" unit and
499 * conversion will be done in the DSP function. This is the case, for
500 * example, for the pitch since it is modulated by the controllers in
503 fluid_voice_calculate_runtime_synthesis_parameters(fluid_voice_t* voice)
507 int list_of_generators_to_initialize[35] = {
508 GEN_STARTADDROFS, /* SF2.01 page 48 #0 */
509 GEN_ENDADDROFS, /* #1 */
510 GEN_STARTLOOPADDROFS, /* #2 */
511 GEN_ENDLOOPADDROFS, /* #3 */
512 /* GEN_STARTADDRCOARSEOFS see comment below [1] #4 */
513 GEN_MODLFOTOPITCH, /* #5 */
514 GEN_VIBLFOTOPITCH, /* #6 */
515 GEN_MODENVTOPITCH, /* #7 */
516 GEN_FILTERFC, /* #8 */
517 GEN_FILTERQ, /* #9 */
518 GEN_MODLFOTOFILTERFC, /* #10 */
519 GEN_MODENVTOFILTERFC, /* #11 */
520 /* GEN_ENDADDRCOARSEOFS [1] #12 */
521 GEN_MODLFOTOVOL, /* #13 */
522 /* not defined #14 */
523 GEN_CHORUSSEND, /* #15 */
524 GEN_REVERBSEND, /* #16 */
526 /* not defined #18 */
527 /* not defined #19 */
528 /* not defined #20 */
529 GEN_MODLFODELAY, /* #21 */
530 GEN_MODLFOFREQ, /* #22 */
531 GEN_VIBLFODELAY, /* #23 */
532 GEN_VIBLFOFREQ, /* #24 */
533 GEN_MODENVDELAY, /* #25 */
534 GEN_MODENVATTACK, /* #26 */
535 GEN_MODENVHOLD, /* #27 */
536 GEN_MODENVDECAY, /* #28 */
537 /* GEN_MODENVSUSTAIN [1] #29 */
538 GEN_MODENVRELEASE, /* #30 */
539 /* GEN_KEYTOMODENVHOLD [1] #31 */
540 /* GEN_KEYTOMODENVDECAY [1] #32 */
541 GEN_VOLENVDELAY, /* #33 */
542 GEN_VOLENVATTACK, /* #34 */
543 GEN_VOLENVHOLD, /* #35 */
544 GEN_VOLENVDECAY, /* #36 */
545 /* GEN_VOLENVSUSTAIN [1] #37 */
546 GEN_VOLENVRELEASE, /* #38 */
547 /* GEN_KEYTOVOLENVHOLD [1] #39 */
548 /* GEN_KEYTOVOLENVDECAY [1] #40 */
549 /* GEN_STARTLOOPADDRCOARSEOFS [1] #45 */
550 GEN_KEYNUM, /* #46 */
551 GEN_VELOCITY, /* #47 */
552 GEN_ATTENUATION, /* #48 */
553 /* GEN_ENDLOOPADDRCOARSEOFS [1] #50 */
554 /* GEN_COARSETUNE [1] #51 */
555 /* GEN_FINETUNE [1] #52 */
556 GEN_OVERRIDEROOTKEY, /* #58 */
558 -1}; /* end-of-list marker */
560 /* When the voice is made ready for the synthesis process, a lot of
561 * voice-internal parameters have to be calculated.
563 * At this point, the sound font has already set the -nominal- value
564 * for all generators (excluding GEN_PITCH). Most generators can be
565 * modulated - they include a nominal value and an offset (which
566 * changes with velocity, note number, channel parameters like
567 * aftertouch, mod wheel...) Now this offset will be calculated as
570 * - Process each modulator once.
571 * - Calculate its output value.
572 * - Find the target generator.
573 * - Add the output value to the modulation value of the generator.
575 * Note: The generators have been initialized with
576 * fluid_gen_set_default_values.
579 for (i = 0; i < voice->mod_count; i++) {
580 fluid_mod_t* mod = &voice->mod[i];
581 fluid_real_t modval = fluid_mod_get_value(mod, voice->channel, voice);
582 int dest_gen_index = mod->dest;
583 fluid_gen_t* dest_gen = &voice->gen[dest_gen_index];
584 dest_gen->mod += modval;
585 /* fluid_dump_modulator(mod); */
588 /* Now the generators are initialized, nominal and modulation value.
589 * The voice parameters (which depend on generators) are calculated
590 * with fluid_voice_update_param. Processing the list of generator
591 * changes will calculate each voice parameter once.
593 * Note [1]: Some voice parameters depend on several generators. For
594 * example, the pitch depends on GEN_COARSETUNE, GEN_FINETUNE and
595 * GEN_PITCH. voice->pitch. Unnecessary recalculation is avoided
596 * by removing all but one generator from the list of voice
597 * parameters. Same with GEN_XXX and GEN_XXXCOARSE: the
598 * initialisation list contains only GEN_XXX.
601 /* Calculate the voice parameter(s) dependent on each generator. */
602 for (i = 0; list_of_generators_to_initialize[i] != -1; i++) {
603 fluid_voice_update_param(voice, list_of_generators_to_initialize[i]);
606 /* Make an estimate on how loud this voice can get at any time (attenuation). */
607 UPDATE_RVOICE_R1(fluid_rvoice_set_min_attenuation_cB,
608 fluid_voice_get_lower_boundary_for_attenuation(voice));
613 * calculate_hold_decay_buffers
616 calculate_hold_decay_buffers(fluid_voice_t* voice, int gen_base,
617 int gen_key2base, int is_decay)
621 * Returns the number of DSP loops, that correspond to the hold
622 * (is_decay=0) or decay (is_decay=1) time.
623 * gen_base=GEN_VOLENVHOLD, GEN_VOLENVDECAY, GEN_MODENVHOLD,
624 * GEN_MODENVDECAY gen_key2base=GEN_KEYTOVOLENVHOLD,
625 * GEN_KEYTOVOLENVDECAY, GEN_KEYTOMODENVHOLD, GEN_KEYTOMODENVDECAY
628 fluid_real_t timecents;
629 fluid_real_t seconds;
632 /* SF2.01 section 8.4.3 # 31, 32, 39, 40
633 * GEN_KEYTOxxxENVxxx uses key 60 as 'origin'.
634 * The unit of the generator is timecents per key number.
635 * If KEYTOxxxENVxxx is 100, a key one octave over key 60 (72)
636 * will cause (60-72)*100=-1200 timecents of time variation.
637 * The time is cut in half.
639 timecents = (_GEN(voice, gen_base) + _GEN(voice, gen_key2base) * (60.0 - voice->key));
643 /* SF 2.01 section 8.1.3 # 28, 36 */
644 if (timecents > 8000.0) {
648 /* SF 2.01 section 8.1.3 # 27, 35 */
649 if (timecents > 5000) {
652 /* SF 2.01 section 8.1.2 # 27, 35:
653 * The most negative number indicates no hold time
655 if (timecents <= -32768.) {
659 /* SF 2.01 section 8.1.3 # 27, 28, 35, 36 */
660 if (timecents < -12000.0) {
661 timecents = -12000.0;
664 seconds = fluid_tc2sec(timecents);
665 /* Each DSP loop processes FLUID_BUFSIZE samples. */
667 /* round to next full number of buffers */
668 buffers = (int)(((fluid_real_t)voice->output_rate * seconds)
669 / (fluid_real_t)FLUID_BUFSIZE
676 * The value of a generator (gen) has changed. (The different
677 * generators are listed in fluidsynth.h, or in SF2.01 page 48-49)
678 * Now the dependent 'voice' parameters are calculated.
680 * fluid_voice_update_param can be called during the setup of the
681 * voice (to calculate the initial value for a voice parameter), or
682 * during its operation (a generator has been changed due to
683 * real-time parameter modifications like pitch-bend).
685 * Note: The generator holds three values: The base value .val, an
686 * offset caused by modulators .mod, and an offset caused by the
687 * NRPN system. _GEN(voice, generator_enumerator) returns the sum
691 * Update all the synthesis parameters, which depend on generator \a gen.
692 * @param voice Voice instance
693 * @param gen Generator id (#fluid_gen_type)
695 * This is only necessary after changing a generator of an already operating voice.
696 * Most applications will not need this function.
699 fluid_voice_update_param(fluid_voice_t* voice, int gen)
704 unsigned int count, z;
705 // Alternate attenuation scale used by EMU10K1 cards when setting the attenuation at the preset or instrument level within the SoundFont bank.
706 static const float ALT_ATTENUATION_SCALE = 0.4;
711 /* range checking is done in the fluid_pan function */
712 voice->pan = _GEN(voice, GEN_PAN);
713 voice->amp_left = fluid_pan(voice->pan, 1) * voice->synth_gain / 32768.0f;
714 voice->amp_right = fluid_pan(voice->pan, 0) * voice->synth_gain / 32768.0f;
715 UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_amp, 0, voice->amp_left);
716 UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_amp, 1, voice->amp_right);
719 case GEN_ATTENUATION:
720 voice->attenuation = ((fluid_real_t)(voice)->gen[GEN_ATTENUATION].val*ALT_ATTENUATION_SCALE) +
721 (fluid_real_t)(voice)->gen[GEN_ATTENUATION].mod + (fluid_real_t)(voice)->gen[GEN_ATTENUATION].nrpn;
723 /* Range: SF2.01 section 8.1.3 # 48
724 * Motivation for range checking:
725 * OHPiano.SF2 sets initial attenuation to a whooping -96 dB */
726 fluid_clip(voice->attenuation, 0.0, 1440.0);
727 UPDATE_RVOICE_R1(fluid_rvoice_set_attenuation, voice->attenuation);
730 /* The pitch is calculated from three different generators.
731 * Read comment in fluidsynth.h about GEN_PITCH.
736 /* The testing for allowed range is done in 'fluid_ct2hz' */
737 voice->pitch = (_GEN(voice, GEN_PITCH)
738 + 100.0f * _GEN(voice, GEN_COARSETUNE)
739 + _GEN(voice, GEN_FINETUNE));
740 UPDATE_RVOICE_R1(fluid_rvoice_set_pitch, voice->pitch);
744 /* The generator unit is 'tenths of a percent'. */
745 voice->reverb_send = _GEN(voice, GEN_REVERBSEND) / 1000.0f;
746 fluid_clip(voice->reverb_send, 0.0, 1.0);
747 voice->amp_reverb = voice->reverb_send * voice->synth_gain / 32768.0f;
748 UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_amp, 2, voice->amp_reverb);
752 /* The generator unit is 'tenths of a percent'. */
753 voice->chorus_send = _GEN(voice, GEN_CHORUSSEND) / 1000.0f;
754 fluid_clip(voice->chorus_send, 0.0, 1.0);
755 voice->amp_chorus = voice->chorus_send * voice->synth_gain / 32768.0f;
756 UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_amp, 3, voice->amp_chorus);
759 case GEN_OVERRIDEROOTKEY:
760 /* This is a non-realtime parameter. Therefore the .mod part of the generator
762 * NOTE: origpitch sets MIDI root note while pitchadj is a fine tuning amount
763 * which offsets the original rate. This means that the fine tuning is
764 * inverted with respect to the root note (so subtract it, not add).
766 if (voice->sample != NULL) {
767 if (voice->gen[GEN_OVERRIDEROOTKEY].val > -1) //FIXME: use flag instead of -1
768 voice->root_pitch = voice->gen[GEN_OVERRIDEROOTKEY].val * 100.0f
769 - voice->sample->pitchadj;
771 voice->root_pitch = voice->sample->origpitch * 100.0f - voice->sample->pitchadj;
772 x = (fluid_ct2hz(voice->root_pitch) * ((fluid_real_t) voice->output_rate / voice->sample->samplerate));
774 if (voice->gen[GEN_OVERRIDEROOTKEY].val > -1) //FIXME: use flag instead of -1
775 voice->root_pitch = voice->gen[GEN_OVERRIDEROOTKEY].val * 100.0f;
777 voice->root_pitch = 0;
778 x = fluid_ct2hz(voice->root_pitch);
780 /* voice->pitch depends on voice->root_pitch, so calculate voice->pitch now */
781 fluid_voice_calculate_gen_pitch(voice);
782 UPDATE_RVOICE_R1(fluid_rvoice_set_root_pitch_hz, x);
787 /* The resonance frequency is converted from absolute cents to
788 * midicents .val and .mod are both used, this permits real-time
789 * modulation. The allowed range is tested in the 'fluid_ct2hz'
790 * function [PH,20021214]
792 x = _GEN(voice, GEN_FILTERFC);
793 UPDATE_RVOICE_FILTER1(fluid_iir_filter_set_fres, x);
797 /* The generator contains 'centibels' (1/10 dB) => divide by 10 to
799 q_dB = _GEN(voice, GEN_FILTERQ) / 10.0f;
801 /* Range: SF2.01 section 8.1.3 # 8 (convert from cB to dB => /10) */
802 fluid_clip(q_dB, 0.0f, 96.0f);
804 /* Short version: Modify the Q definition in a way, that a Q of 0
805 * dB leads to no resonance hump in the freq. response.
807 * Long version: From SF2.01, page 39, item 9 (initialFilterQ):
808 * "The gain at the cutoff frequency may be less than zero when
809 * zero is specified". Assume q_dB=0 / q_lin=1: If we would leave
810 * q as it is, then this results in a 3 dB hump slightly below
811 * fc. At fc, the gain is exactly the DC gain (0 dB). What is
812 * (probably) meant here is that the filter does not show a
813 * resonance hump for q_dB=0. In this case, the corresponding
814 * q_lin is 1/sqrt(2)=0.707. The filter should have 3 dB of
815 * attenuation at fc now. In this case Q_dB is the height of the
816 * resonance peak not over the DC gain, but over the frequency
817 * response of a non-resonant filter. This idea is implemented as
820 UPDATE_RVOICE_FILTER1(fluid_iir_filter_set_q_dB, q_dB);
824 case GEN_MODLFOTOPITCH:
825 x = _GEN(voice, GEN_MODLFOTOPITCH);
826 fluid_clip(x, -12000.0, 12000.0);
827 UPDATE_RVOICE_R1(fluid_rvoice_set_modlfo_to_pitch, x);
830 case GEN_MODLFOTOVOL:
831 x = _GEN(voice, GEN_MODLFOTOVOL);
832 fluid_clip(x, -960.0, 960.0);
833 UPDATE_RVOICE_R1(fluid_rvoice_set_modlfo_to_vol, x);
836 case GEN_MODLFOTOFILTERFC:
837 x = _GEN(voice, GEN_MODLFOTOFILTERFC);
838 fluid_clip(x, -12000, 12000);
839 UPDATE_RVOICE_R1(fluid_rvoice_set_modlfo_to_fc, x);
842 case GEN_MODLFODELAY:
843 x = _GEN(voice, GEN_MODLFODELAY);
844 fluid_clip(x, -12000.0f, 5000.0f);
845 z = (unsigned int) (voice->output_rate * fluid_tc2sec_delay(x));
846 UPDATE_RVOICE_ENVLFO_I1(fluid_lfo_set_delay, modlfo, z);
850 /* - the frequency is converted into a delta value, per buffer of FLUID_BUFSIZE samples
851 * - the delay into a sample delay
853 x = _GEN(voice, GEN_MODLFOFREQ);
854 fluid_clip(x, -16000.0f, 4500.0f);
855 x = (4.0f * FLUID_BUFSIZE * fluid_act2hz(x) / voice->output_rate);
856 UPDATE_RVOICE_ENVLFO_R1(fluid_lfo_set_incr, modlfo, x);
862 * - the frequency is converted into a delta value, per buffer of FLUID_BUFSIZE samples
863 * - the delay into a sample delay
865 x = _GEN(voice, GEN_VIBLFOFREQ);
866 fluid_clip(x, -16000.0f, 4500.0f);
867 x = 4.0f * FLUID_BUFSIZE * fluid_act2hz(x) / voice->output_rate;
868 UPDATE_RVOICE_ENVLFO_R1(fluid_lfo_set_incr, viblfo, x);
871 case GEN_VIBLFODELAY:
872 x = _GEN(voice,GEN_VIBLFODELAY);
873 fluid_clip(x, -12000.0f, 5000.0f);
874 z = (unsigned int) (voice->output_rate * fluid_tc2sec_delay(x));
875 UPDATE_RVOICE_ENVLFO_I1(fluid_lfo_set_delay, viblfo, z);
878 case GEN_VIBLFOTOPITCH:
879 x = _GEN(voice, GEN_VIBLFOTOPITCH);
880 fluid_clip(x, -12000.0, 12000.0);
881 UPDATE_RVOICE_R1(fluid_rvoice_set_viblfo_to_pitch, x);
885 /* GEN_KEYNUM: SF2.01 page 46, item 46
887 * If this generator is active, it forces the key number to its
888 * value. Non-realtime controller.
890 * There is a flag, which should indicate, whether a generator is
891 * enabled or not. But here we rely on the default value of -1.
893 x = _GEN(voice, GEN_KEYNUM);
900 /* GEN_VELOCITY: SF2.01 page 46, item 47
902 * If this generator is active, it forces the velocity to its
903 * value. Non-realtime controller.
905 * There is a flag, which should indicate, whether a generator is
906 * enabled or not. But here we rely on the default value of -1. */
907 x = _GEN(voice, GEN_VELOCITY);
913 case GEN_MODENVTOPITCH:
914 x = _GEN(voice, GEN_MODENVTOPITCH);
915 fluid_clip(x, -12000.0, 12000.0);
916 UPDATE_RVOICE_R1(fluid_rvoice_set_modenv_to_pitch, x);
919 case GEN_MODENVTOFILTERFC:
920 x = _GEN(voice,GEN_MODENVTOFILTERFC);
922 /* Range: SF2.01 section 8.1.3 # 1
923 * Motivation for range checking:
924 * Filter is reported to make funny noises now and then
926 fluid_clip(x, -12000.0, 12000.0);
927 UPDATE_RVOICE_R1(fluid_rvoice_set_modenv_to_fc, x);
931 /* sample start and ends points
933 * Range checking is initiated via the
934 * voice->check_sample_sanity flag,
935 * because it is impossible to check here:
936 * During the voice setup, all modulators are processed, while
937 * the voice is inactive. Therefore, illegal settings may
938 * occur during the setup (for example: First move the loop
939 * end point ahead of the loop start point => invalid, then
940 * move the loop start point forward => valid again.
942 case GEN_STARTADDROFS: /* SF2.01 section 8.1.3 # 0 */
943 case GEN_STARTADDRCOARSEOFS: /* SF2.01 section 8.1.3 # 4 */
944 if (voice->sample != NULL) {
945 z = (voice->sample->start
946 + (int) _GEN(voice, GEN_STARTADDROFS)
947 + 32768 * (int) _GEN(voice, GEN_STARTADDRCOARSEOFS));
948 UPDATE_RVOICE_I1(fluid_rvoice_set_start, z);
951 case GEN_ENDADDROFS: /* SF2.01 section 8.1.3 # 1 */
952 case GEN_ENDADDRCOARSEOFS: /* SF2.01 section 8.1.3 # 12 */
953 if (voice->sample != NULL) {
954 z = (voice->sample->end
955 + (int) _GEN(voice, GEN_ENDADDROFS)
956 + 32768 * (int) _GEN(voice, GEN_ENDADDRCOARSEOFS));
957 UPDATE_RVOICE_I1(fluid_rvoice_set_end, z);
960 case GEN_STARTLOOPADDROFS: /* SF2.01 section 8.1.3 # 2 */
961 case GEN_STARTLOOPADDRCOARSEOFS: /* SF2.01 section 8.1.3 # 45 */
962 if (voice->sample != NULL) {
963 z = (voice->sample->loopstart
964 + (int) _GEN(voice, GEN_STARTLOOPADDROFS)
965 + 32768 * (int) _GEN(voice, GEN_STARTLOOPADDRCOARSEOFS));
966 UPDATE_RVOICE_I1(fluid_rvoice_set_loopstart, z);
970 case GEN_ENDLOOPADDROFS: /* SF2.01 section 8.1.3 # 3 */
971 case GEN_ENDLOOPADDRCOARSEOFS: /* SF2.01 section 8.1.3 # 50 */
972 if (voice->sample != NULL) {
973 z = (voice->sample->loopend
974 + (int) _GEN(voice, GEN_ENDLOOPADDROFS)
975 + 32768 * (int) _GEN(voice, GEN_ENDLOOPADDRCOARSEOFS));
976 UPDATE_RVOICE_I1(fluid_rvoice_set_loopend, z);
980 /* Conversion functions differ in range limit */
981 #define NUM_BUFFERS_DELAY(_v) (unsigned int) (voice->output_rate * fluid_tc2sec_delay(_v) / FLUID_BUFSIZE)
982 #define NUM_BUFFERS_ATTACK(_v) (unsigned int) (voice->output_rate * fluid_tc2sec_attack(_v) / FLUID_BUFSIZE)
983 #define NUM_BUFFERS_RELEASE(_v) (unsigned int) (voice->output_rate * fluid_tc2sec_release(_v) / FLUID_BUFSIZE)
987 * - delay and hold times are converted to absolute number of samples
988 * - sustain is converted to its absolute value
989 * - attack, decay and release are converted to their increment per sample
991 case GEN_VOLENVDELAY: /* SF2.01 section 8.1.3 # 33 */
992 x = _GEN(voice, GEN_VOLENVDELAY);
993 fluid_clip(x, -12000.0f, 5000.0f);
994 count = NUM_BUFFERS_DELAY(x);
995 fluid_voice_update_volenv(voice, FLUID_VOICE_ENVDELAY,
996 count, 0.0f, 0.0f, -1.0f, 1.0f);
999 case GEN_VOLENVATTACK: /* SF2.01 section 8.1.3 # 34 */
1000 x = _GEN(voice, GEN_VOLENVATTACK);
1001 fluid_clip(x, -12000.0f, 8000.0f);
1002 count = 1 + NUM_BUFFERS_ATTACK(x);
1003 fluid_voice_update_volenv(voice, FLUID_VOICE_ENVATTACK,
1004 count, 1.0f, count ? 1.0f / count : 0.0f, -1.0f, 1.0f);
1007 case GEN_VOLENVHOLD: /* SF2.01 section 8.1.3 # 35 */
1008 case GEN_KEYTOVOLENVHOLD: /* SF2.01 section 8.1.3 # 39 */
1009 count = calculate_hold_decay_buffers(voice, GEN_VOLENVHOLD, GEN_KEYTOVOLENVHOLD, 0); /* 0 means: hold */
1010 fluid_voice_update_volenv(voice, FLUID_VOICE_ENVHOLD,
1011 count, 1.0f, 0.0f, -1.0f, 2.0f);
1014 case GEN_VOLENVDECAY: /* SF2.01 section 8.1.3 # 36 */
1015 case GEN_VOLENVSUSTAIN: /* SF2.01 section 8.1.3 # 37 */
1016 case GEN_KEYTOVOLENVDECAY: /* SF2.01 section 8.1.3 # 40 */
1017 y = 1.0f - 0.001f * _GEN(voice, GEN_VOLENVSUSTAIN);
1018 fluid_clip(y, 0.0f, 1.0f);
1019 count = calculate_hold_decay_buffers(voice, GEN_VOLENVDECAY, GEN_KEYTOVOLENVDECAY, 1); /* 1 for decay */
1020 fluid_voice_update_volenv(voice, FLUID_VOICE_ENVDECAY,
1021 count, 1.0f, count ? -1.0f / count : 0.0f, y, 2.0f);
1024 case GEN_VOLENVRELEASE: /* SF2.01 section 8.1.3 # 38 */
1025 x = _GEN(voice, GEN_VOLENVRELEASE);
1026 fluid_clip(x, FLUID_MIN_VOLENVRELEASE, 8000.0f);
1027 count = 1 + NUM_BUFFERS_RELEASE(x);
1028 fluid_voice_update_volenv(voice, FLUID_VOICE_ENVRELEASE,
1029 count, 1.0f, count ? -1.0f / count : 0.0f, 0.0f, 1.0f);
1032 /* Modulation envelope */
1033 case GEN_MODENVDELAY: /* SF2.01 section 8.1.3 # 25 */
1034 x = _GEN(voice, GEN_MODENVDELAY);
1035 fluid_clip(x, -12000.0f, 5000.0f);
1036 fluid_voice_update_modenv(voice, FLUID_VOICE_ENVDELAY,
1037 NUM_BUFFERS_DELAY(x), 0.0f, 0.0f, -1.0f, 1.0f);
1040 case GEN_MODENVATTACK: /* SF2.01 section 8.1.3 # 26 */
1041 x = _GEN(voice, GEN_MODENVATTACK);
1042 fluid_clip(x, -12000.0f, 8000.0f);
1043 count = 1 + NUM_BUFFERS_ATTACK(x);
1044 fluid_voice_update_modenv(voice, FLUID_VOICE_ENVATTACK,
1045 count, 1.0f, count ? 1.0f / count : 0.0f, -1.0f, 1.0f);
1048 case GEN_MODENVHOLD: /* SF2.01 section 8.1.3 # 27 */
1049 case GEN_KEYTOMODENVHOLD: /* SF2.01 section 8.1.3 # 31 */
1050 count = calculate_hold_decay_buffers(voice, GEN_MODENVHOLD, GEN_KEYTOMODENVHOLD, 0); /* 1 means: hold */
1051 fluid_voice_update_modenv(voice, FLUID_VOICE_ENVHOLD,
1052 count, 1.0f, 0.0f, -1.0f, 2.0f);
1055 case GEN_MODENVDECAY: /* SF 2.01 section 8.1.3 # 28 */
1056 case GEN_MODENVSUSTAIN: /* SF 2.01 section 8.1.3 # 29 */
1057 case GEN_KEYTOMODENVDECAY: /* SF 2.01 section 8.1.3 # 32 */
1058 count = calculate_hold_decay_buffers(voice, GEN_MODENVDECAY, GEN_KEYTOMODENVDECAY, 1); /* 1 for decay */
1059 y = 1.0f - 0.001f * _GEN(voice, GEN_MODENVSUSTAIN);
1060 fluid_clip(y, 0.0f, 1.0f);
1061 fluid_voice_update_modenv(voice, FLUID_VOICE_ENVDECAY,
1062 count, 1.0f, count ? -1.0f / count : 0.0f, y, 2.0f);
1065 case GEN_MODENVRELEASE: /* SF 2.01 section 8.1.3 # 30 */
1066 x = _GEN(voice, GEN_MODENVRELEASE);
1067 fluid_clip(x, -12000.0f, 8000.0f);
1068 count = 1 + NUM_BUFFERS_RELEASE(x);
1069 fluid_voice_update_modenv(voice, FLUID_VOICE_ENVRELEASE,
1070 count, 1.0f, count ? -1.0f / count : 0.0f, 0.0f, 2.0f);
1078 * Recalculate voice parameters for a given control.
1079 * @param voice the synthesis voice
1080 * @param cc flag to distinguish between a continous control and a channel control (pitch bend, ...)
1081 * @param ctrl the control number
1083 * In this implementation, I want to make sure that all controllers
1084 * are event based: the parameter values of the DSP algorithm should
1085 * only be updates when a controller event arrived and not at every
1086 * iteration of the audio cycle (which would probably be feasible if
1087 * the synth was made in silicon).
1089 * The update is done in three steps:
1091 * - first, we look for all the modulators that have the changed
1092 * controller as a source. This will yield a list of generators that
1093 * will be changed because of the controller event.
1095 * - For every changed generator, calculate its new value. This is the
1096 * sum of its original value plus the values of al the attached
1099 * - For every changed generator, convert its value to the correct
1100 * unit of the corresponding DSP parameter
1102 int fluid_voice_modulate(fluid_voice_t* voice, int cc, int ctrl)
1107 fluid_real_t modval;
1109 /* printf("Chan=%d, CC=%d, Src=%d, Val=%d\n", voice->channel->channum, cc, ctrl, val); */
1111 for (i = 0; i < voice->mod_count; i++) {
1113 mod = &voice->mod[i];
1115 /* step 1: find all the modulators that have the changed controller
1116 * as input source. */
1117 if (fluid_mod_has_source(mod, cc, ctrl)) {
1119 gen = fluid_mod_get_dest(mod);
1122 /* step 2: for every changed modulator, calculate the modulation
1123 * value of its associated generator */
1124 for (k = 0; k < voice->mod_count; k++) {
1125 if (fluid_mod_has_dest(&voice->mod[k], gen)) {
1126 modval += fluid_mod_get_value(&voice->mod[k], voice->channel, voice);
1130 fluid_gen_set_mod(&voice->gen[gen], modval);
1132 /* step 3: now that we have the new value of the generator,
1133 * recalculate the parameter values that are derived from the
1135 fluid_voice_update_param(voice, gen);
1142 * Update all the modulators. This function is called after a
1143 * ALL_CTRL_OFF MIDI message has been received (CC 121).
1146 int fluid_voice_modulate_all(fluid_voice_t* voice)
1150 fluid_real_t modval;
1152 /* Loop through all the modulators.
1154 FIXME: we should loop through the set of generators instead of
1155 the set of modulators. We risk to call 'fluid_voice_update_param'
1156 several times for the same generator if several modulators have
1157 that generator as destination. It's not an error, just a wast of
1158 energy (think polution, global warming, unhappy musicians,
1161 for (i = 0; i < voice->mod_count; i++) {
1163 mod = &voice->mod[i];
1164 gen = fluid_mod_get_dest(mod);
1167 /* Accumulate the modulation values of all the modulators with
1168 * destination generator 'gen' */
1169 for (k = 0; k < voice->mod_count; k++) {
1170 if (fluid_mod_has_dest(&voice->mod[k], gen)) {
1171 modval += fluid_mod_get_value(&voice->mod[k], voice->channel, voice);
1175 fluid_gen_set_mod(&voice->gen[gen], modval);
1177 /* Update the parameter values that are depend on the generator
1179 fluid_voice_update_param(voice, gen);
1186 Force the voice into release stage. Useful anywhere a voice
1187 needs to be damped even if pedals (sustain sostenuto) are depressed.
1188 See fluid_synth_damp_voices_by_sustain_LOCAL(),
1189 fluid_synth_damp_voices_by_sostenuto_LOCAL,
1190 fluid_voice_noteoff().
1193 fluid_voice_release(fluid_voice_t* voice)
1195 unsigned int at_tick = fluid_channel_get_min_note_length_ticks (voice->channel);
1196 UPDATE_RVOICE_I1(fluid_rvoice_noteoff, at_tick);
1197 voice->has_noteoff = 1; // voice is marked as noteoff occured
1201 * fluid_voice_noteoff
1204 fluid_voice_noteoff(fluid_voice_t* voice)
1206 fluid_channel_t* channel;
1208 fluid_profile(FLUID_PROF_VOICE_NOTE, voice->ref);
1210 channel = voice->channel;
1212 /* Sustain a note under Sostenuto pedal */
1213 if (fluid_channel_sostenuto(channel) &&
1214 channel->sostenuto_orderid > voice->id)
1215 { // Sostenuto depressed after note
1216 voice->status = FLUID_VOICE_HELD_BY_SOSTENUTO;
1218 /* Or sustain a note under Sustain pedal */
1219 else if (fluid_channel_sustained(channel)) {
1220 voice->status = FLUID_VOICE_SUSTAINED;
1222 /* Or force the voice to release stage */
1224 fluid_voice_release(voice);
1230 * fluid_voice_kill_excl
1232 * Percussion sounds can be mutually exclusive: for example, a 'closed
1233 * hihat' sound will terminate an 'open hihat' sound ringing at the
1234 * same time. This behaviour is modeled using 'exclusive classes',
1235 * turning on a voice with an exclusive class other than 0 will kill
1236 * all other voices having that exclusive class within the same preset
1237 * or channel. fluid_voice_kill_excl gets called, when 'voice' is to
1238 * be killed for that reason.
1242 fluid_voice_kill_excl(fluid_voice_t* voice){
1244 unsigned int at_tick;
1246 if (!_PLAYING(voice)) {
1250 /* Turn off the exclusive class information for this voice,
1251 so that it doesn't get killed twice
1253 fluid_voice_gen_set(voice, GEN_EXCLUSIVECLASS, 0);
1255 /* Speed up the volume envelope */
1256 /* The value was found through listening tests with hi-hat samples. */
1257 fluid_voice_gen_set(voice, GEN_VOLENVRELEASE, -200);
1258 fluid_voice_update_param(voice, GEN_VOLENVRELEASE);
1260 /* Speed up the modulation envelope */
1261 fluid_voice_gen_set(voice, GEN_MODENVRELEASE, -200);
1262 fluid_voice_update_param(voice, GEN_MODENVRELEASE);
1264 at_tick = fluid_channel_get_min_note_length_ticks (voice->channel);
1265 UPDATE_RVOICE_I1(fluid_rvoice_noteoff, at_tick);
1272 * Called by fluid_synth when the overflow rvoice can be reclaimed.
1274 void fluid_voice_overflow_rvoice_finished(fluid_voice_t* voice)
1276 voice->can_access_overflow_rvoice = 1;
1277 fluid_sample_null_ptr(&voice->overflow_rvoice->dsp.sample);
1285 * Turns off a voice, meaning that it is not processed
1286 * anymore by the DSP loop.
1289 fluid_voice_off(fluid_voice_t* voice)
1291 fluid_profile(FLUID_PROF_VOICE_RELEASE, voice->ref);
1293 voice->chan = NO_CHANNEL;
1294 UPDATE_RVOICE0(fluid_rvoice_voiceoff);
1296 if (voice->can_access_rvoice)
1297 fluid_sample_null_ptr(&voice->rvoice->dsp.sample);
1299 voice->status = FLUID_VOICE_OFF;
1300 voice->has_noteoff = 1;
1302 /* Decrement the reference count of the sample. */
1303 fluid_sample_null_ptr(&voice->sample);
1305 /* Decrement voice count */
1306 voice->channel->synth->active_voice_count--;
1312 * Adds a modulator to the voice.
1313 * @param voice Voice instance
1314 * @param mod Modulator info (copied)
1315 * @param mode Determines how to handle an existing identical modulator
1316 * #FLUID_VOICE_ADD to add (offset) the modulator amounts,
1317 * #FLUID_VOICE_OVERWRITE to replace the modulator,
1318 * #FLUID_VOICE_DEFAULT when adding a default modulator - no duplicate should
1319 * exist so don't check.
1322 fluid_voice_add_mod(fluid_voice_t* voice, fluid_mod_t* mod, int mode)
1327 * Some soundfonts come with a huge number of non-standard
1328 * controllers, because they have been designed for one particular
1329 * sound card. Discard them, maybe print a warning.
1332 if (((mod->flags1 & FLUID_MOD_CC) == 0)
1333 && ((mod->src1 != 0) /* SF2.01 section 8.2.1: Constant value */
1334 && (mod->src1 != 2) /* Note-on velocity */
1335 && (mod->src1 != 3) /* Note-on key number */
1336 && (mod->src1 != 10) /* Poly pressure */
1337 && (mod->src1 != 13) /* Channel pressure */
1338 && (mod->src1 != 14) /* Pitch wheel */
1339 && (mod->src1 != 16))) { /* Pitch wheel sensitivity */
1340 FLUID_LOG(FLUID_WARN, "Ignoring invalid controller, using non-CC source %i.", mod->src1);
1344 if (mode == FLUID_VOICE_ADD) {
1346 /* if identical modulator exists, add them */
1347 for (i = 0; i < voice->mod_count; i++) {
1348 if (fluid_mod_test_identity(&voice->mod[i], mod)) {
1349 // printf("Adding modulator...\n");
1350 voice->mod[i].amount += mod->amount;
1355 } else if (mode == FLUID_VOICE_OVERWRITE) {
1357 /* if identical modulator exists, replace it (only the amount has to be changed) */
1358 for (i = 0; i < voice->mod_count; i++) {
1359 if (fluid_mod_test_identity(&voice->mod[i], mod)) {
1360 // printf("Replacing modulator...amount is %f\n",mod->amount);
1361 voice->mod[i].amount = mod->amount;
1367 /* Add a new modulator (No existing modulator to add / overwrite).
1368 Also, default modulators (FLUID_VOICE_DEFAULT) are added without
1369 checking, if the same modulator already exists. */
1370 if (voice->mod_count < FLUID_NUM_MOD) {
1371 fluid_mod_clone(&voice->mod[voice->mod_count++], mod);
1376 * Get the unique ID of the noteon-event.
1377 * @param voice Voice instance
1378 * @return Note on unique ID
1380 * A SoundFont loader may store the voice processes it has created for
1381 * real-time control during the operation of a voice (for example: parameter
1382 * changes in SoundFont editor). The synth uses a pool of voices, which are
1383 * 'recycled' and never deallocated.
1385 * Before modifying an existing voice, check
1386 * - that its state is still 'playing'
1387 * - that the ID is still the same
1389 * Otherwise the voice has finished playing.
1391 unsigned int fluid_voice_get_id(fluid_voice_t* voice)
1397 * Check if a voice is still playing.
1398 * @param voice Voice instance
1399 * @return TRUE if playing, FALSE otherwise
1401 int fluid_voice_is_playing(fluid_voice_t* voice)
1403 return _PLAYING(voice);
1407 * fluid_voice_get_lower_boundary_for_attenuation
1411 * A lower boundary for the attenuation (as in 'the minimum
1412 * attenuation of this voice, with volume pedals, modulators
1413 * etc. resulting in minimum attenuation, cannot fall below x cB) is
1414 * calculated. This has to be called during fluid_voice_init, after
1415 * all modulators have been run on the voice once. Also,
1416 * voice->attenuation has to be initialized.
1419 fluid_voice_get_lower_boundary_for_attenuation(fluid_voice_t* voice)
1423 fluid_real_t possible_att_reduction_cB=0;
1424 fluid_real_t lower_bound;
1426 for (i = 0; i < voice->mod_count; i++) {
1427 mod = &voice->mod[i];
1429 /* Modulator has attenuation as target and can change over time? */
1430 if ((mod->dest == GEN_ATTENUATION)
1431 && ((mod->flags1 & FLUID_MOD_CC) || (mod->flags2 & FLUID_MOD_CC))) {
1433 fluid_real_t current_val = fluid_mod_get_value(mod, voice->channel, voice);
1434 fluid_real_t v = fabs(mod->amount);
1436 if ((mod->src1 == FLUID_MOD_PITCHWHEEL)
1437 || (mod->flags1 & FLUID_MOD_BIPOLAR)
1438 || (mod->flags2 & FLUID_MOD_BIPOLAR)
1439 || (mod->amount < 0)) {
1440 /* Can this modulator produce a negative contribution? */
1443 /* No negative value possible. But still, the minimum contribution is 0. */
1450 * - possible_att_reduction_cB += 4100
1452 if (current_val > v){
1453 possible_att_reduction_cB += (current_val - v);
1458 lower_bound = voice->attenuation-possible_att_reduction_cB;
1460 /* SF2.01 specs do not allow negative attenuation */
1461 if (lower_bound < 0) {
1470 int fluid_voice_set_param(fluid_voice_t* voice, int gen, fluid_real_t nrpn_value, int abs)
1472 voice->gen[gen].nrpn = nrpn_value;
1473 voice->gen[gen].flags = (abs)? GEN_ABS_NRPN : GEN_SET;
1474 fluid_voice_update_param(voice, gen);
1478 int fluid_voice_set_gain(fluid_voice_t* voice, fluid_real_t gain)
1480 /* avoid division by zero*/
1481 if (gain < 0.0000001){
1485 voice->synth_gain = gain;
1486 voice->amp_left = fluid_pan(voice->pan, 1) * gain / 32768.0f;
1487 voice->amp_right = fluid_pan(voice->pan, 0) * gain / 32768.0f;
1488 voice->amp_reverb = voice->reverb_send * gain / 32768.0f;
1489 voice->amp_chorus = voice->chorus_send * gain / 32768.0f;
1491 UPDATE_RVOICE_R1(fluid_rvoice_set_synth_gain, gain);
1492 UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_amp, 0, voice->amp_left);
1493 UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_amp, 1, voice->amp_right);
1494 UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_amp, 2, voice->amp_reverb);
1495 UPDATE_RVOICE_BUFFERS2(fluid_rvoice_buffers_set_amp, 3, voice->amp_chorus);
1501 * - determine the peak level
1502 * - Calculate, what factor will make the loop inaudible
1506 * Calculate the peak volume of a sample for voice off optimization.
1507 * @param s Sample to optimize
1508 * @return #FLUID_OK on success, #FLUID_FAILED otherwise
1510 * If the peak volume during the loop is known, then the voice can
1511 * be released earlier during the release phase. Otherwise, the
1512 * voice will operate (inaudibly), until the envelope is at the
1513 * nominal turnoff point. So it's a good idea to call
1514 * fluid_voice_optimize_sample() on each sample once.
1517 fluid_voice_optimize_sample(fluid_sample_t* s)
1519 signed short peak_max = 0;
1520 signed short peak_min = 0;
1522 fluid_real_t normalized_amplitude_during_loop;
1526 /* ignore ROM and other(?) invalid samples */
1527 if (!s->valid) return (FLUID_OK);
1529 if (!s->amplitude_that_reaches_noise_floor_is_valid){ /* Only once */
1531 for (i = (int)s->loopstart; i < (int) s->loopend; i ++){
1532 signed short val = s->data[i];
1533 if (val > peak_max) {
1535 } else if (val < peak_min) {
1540 /* Determine the peak level */
1541 if (peak_max >- peak_min){
1547 /* Avoid division by zero */
1551 /* Calculate what factor will make the loop inaudible
1552 * For example: Take a peak of 3277 (10 % of 32768). The
1553 * normalized amplitude is 0.1 (10 % of 32768). An amplitude
1554 * factor of 0.0001 (as opposed to the default 0.00001) will
1555 * drop this sample to the noise floor.
1558 /* 16 bits => 96+4=100 dB dynamic range => 0.00001 */
1559 normalized_amplitude_during_loop = ((fluid_real_t)peak)/32768.;
1560 result = FLUID_NOISE_FLOOR / normalized_amplitude_during_loop;
1562 /* Store in sample */
1563 s->amplitude_that_reaches_noise_floor = (double)result;
1564 s->amplitude_that_reaches_noise_floor_is_valid = 1;
1566 printf("Sample peak detection: factor %f\n", (double)result);
1573 fluid_voice_get_overflow_prio(fluid_voice_t* voice,
1574 fluid_overflow_prio_t* score,
1575 unsigned int cur_time)
1577 fluid_real_t this_voice_prio = 0;
1579 /* Are we already overflowing? */
1580 if (!voice->can_access_overflow_rvoice) {
1581 return OVERFLOW_PRIO_CANNOT_KILL;
1584 /* Is this voice on the drum channel?
1585 * Then it is very important.
1586 * Also skip the released and sustained scores.
1588 if (voice->channel->channel_type == CHANNEL_TYPE_DRUM){
1589 this_voice_prio += score->percussion;
1591 else if (voice->has_noteoff) {
1593 this_voice_prio += score->released;
1594 } else if (_SUSTAINED(voice) || _HELD_BY_SOSTENUTO(voice)) {
1595 /* This voice is still active, since the sustain pedal is held down.
1596 * Consider it less important than non-sustained channels.
1597 * This decision is somehow subjective. But usually the sustain pedal
1598 * is used to play 'more-voices-than-fingers', so it shouldn't hurt
1599 * if we kill one voice.
1601 this_voice_prio += score->sustained;
1604 /* We are not enthusiastic about releasing voices, which have just been started.
1605 * Otherwise hitting a chord may result in killing notes belonging to that very same
1606 * chord. So give newer voices a higher score. */
1608 cur_time -= voice->start_time;
1610 cur_time = 1; // Avoid div by zero
1611 this_voice_prio += (score->age * voice->output_rate) / cur_time;
1614 /* take a rough estimate of loudness into account. Louder voices are more important. */
1615 if (score->volume) {
1616 fluid_real_t a = voice->attenuation;
1617 if (voice->has_noteoff) {
1618 // FIXME: Should take into account where on the envelope we are...?
1621 a = 0.1; // Avoid div by zero
1622 this_voice_prio += score->volume / a;
1625 return this_voice_prio;