Make sure all voices are released when sampler is destroyed.
[calfbox.git] / sampler_voice.c
blob032a7d42bd8b431202718c9dc2d96a0fb72ab0f9
1 /*
2 Calf Box, an open source musical instrument.
3 Copyright (C) 2010-2013 Krzysztof Foltman
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
19 #include "config-api.h"
20 #include "dspmath.h"
21 #include "errors.h"
22 #include "midi.h"
23 #include "module.h"
24 #include "rt.h"
25 #include "sampler.h"
26 #include "sampler_impl.h"
27 #include "sfzloader.h"
28 #include "stm.h"
29 #include <assert.h>
30 #include <errno.h>
31 #include <glib.h>
32 #include <math.h>
33 #include <memory.h>
34 #include <sndfile.h>
35 #include <stdio.h>
36 #include <stdlib.h>
39 static void lfo_init(struct sampler_lfo *lfo, struct sampler_lfo_params *lfop, int srate, double srate_inv)
41 lfo->phase = 0;
42 lfo->age = 0;
43 lfo->delta = (uint32_t)(lfop->freq * 65536.0 * 65536.0 * CBOX_BLOCK_SIZE * srate_inv);
44 lfo->delay = (uint32_t)(lfop->delay * srate);
45 lfo->fade = (uint32_t)(lfop->fade * srate);
48 static inline float lfo_run(struct sampler_lfo *lfo)
50 if (lfo->age < lfo->delay)
52 lfo->age += CBOX_BLOCK_SIZE;
53 return 0.f;
56 const int FRAC_BITS = 32 - 11;
57 lfo->phase += lfo->delta;
58 uint32_t iphase = lfo->phase >> FRAC_BITS;
59 float frac = (lfo->phase & ((1 << FRAC_BITS) - 1)) * (1.0 / (1 << FRAC_BITS));
61 float v = sampler_sine_wave[iphase] + (sampler_sine_wave[iphase + 1] - sampler_sine_wave[iphase]) * frac;
62 if (lfo->fade && lfo->age < lfo->delay + lfo->fade)
64 v *= (lfo->age - lfo->delay) * 1.0 / lfo->fade;
65 lfo->age += CBOX_BLOCK_SIZE;
68 return v;
71 static gboolean is_4pole(struct sampler_layer_data *v)
73 if (v->cutoff == -1)
74 return FALSE;
75 return v->fil_type == sft_lp24 || v->fil_type == sft_hp24 || v->fil_type == sft_bp12;
78 static gboolean is_tail_finished(struct sampler_voice *v)
80 if (v->layer->cutoff == -1)
81 return TRUE;
82 double eps = 1.0 / 65536.0;
83 if (cbox_biquadf_is_audible(&v->filter_left, eps))
84 return FALSE;
85 if (cbox_biquadf_is_audible(&v->filter_right, eps))
86 return FALSE;
87 if (is_4pole(v->layer))
89 if (cbox_biquadf_is_audible(&v->filter_left2, eps))
90 return FALSE;
91 if (cbox_biquadf_is_audible(&v->filter_right2, eps))
92 return FALSE;
95 return TRUE;
98 static inline void mix_block_into_with_gain(cbox_sample_t **outputs, int oofs, float *src_left, float *src_right, float gain)
100 cbox_sample_t *dst_left = outputs[oofs];
101 cbox_sample_t *dst_right = outputs[oofs + 1];
102 for (size_t i = 0; i < CBOX_BLOCK_SIZE; i++)
104 dst_left[i] += gain * src_left[i];
105 dst_right[i] += gain * src_right[i];
109 ////////////////////////////////////////////////////////////////////////////////
111 void sampler_voice_activate(struct sampler_voice *v, enum sampler_player_type mode)
113 assert(v->gen.mode == spt_inactive);
114 sampler_voice_unlink(&v->program->module->voices_free, v);
115 assert(mode != spt_inactive);
116 assert(v->channel);
117 v->gen.mode = mode;
118 sampler_voice_link(&v->channel->voices_running, v);
121 void sampler_voice_start(struct sampler_voice *v, struct sampler_channel *c, struct sampler_layer_data *l, int note, int vel, int *exgroups, int *pexgroupcount)
123 struct sampler_module *m = c->module;
124 sampler_gen_reset(&v->gen);
126 v->age = 0;
127 if (l->trigger == stm_release)
129 // time since last 'note on' for that note
130 v->age = m->current_time - c->prev_note_start_time[note];
131 double age = v->age * m->module.srate_inv;
132 // if attenuation is more than 84dB, ignore the release trigger
133 if (age * l->rt_decay > 84)
134 return;
136 uint32_t end = l->eff_waveform->info.frames;
137 if (l->end != 0)
138 end = (l->end == -1) ? 0 : l->end;
139 v->last_waveform = l->eff_waveform;
140 v->gen.cur_sample_end = end;
141 if (end > l->eff_waveform->info.frames)
142 end = l->eff_waveform->info.frames;
144 if (end > l->eff_waveform->preloaded_frames)
146 // XXXKF allow looping
147 v->current_pipe = cbox_prefetch_stack_pop(m->pipe_stack, l->eff_waveform, -1, end);
148 if (!v->current_pipe)
149 g_warning("Prefetch pipe pool exhausted, no streaming playback will be possible");
152 v->output_pair_no = l->output % m->output_pairs;
153 v->serial_no = m->serial_no;
155 uint32_t pos = l->offset;
156 pos = l->offset;
157 if (l->offset_random)
158 pos += ((uint32_t)(rand() + (rand() << 16))) % l->offset_random;
159 if (pos >= end)
160 pos = end;
161 v->gen.bigpos = ((uint64_t)pos) << 32;
163 float delay = l->delay;
164 if (l->delay_random)
165 delay += rand() * (1.0 / RAND_MAX) * l->delay_random;
166 if (delay > 0)
167 v->delay = (int)(delay * m->module.srate);
168 else
169 v->delay = 0;
170 v->gen.loop_overlap = l->loop_overlap;
171 v->gen.loop_overlap_step = 1.0 / l->loop_overlap;
172 v->gain_fromvel = 1.0 + (l->eff_velcurve[vel] - 1.0) * l->amp_veltrack * 0.01;
173 v->gain_shift = 0.0;
174 v->note = note;
175 v->vel = vel;
176 v->pitch_shift = 0;
177 v->released = 0;
178 v->released_with_sustain = 0;
179 v->released_with_sostenuto = 0;
180 v->captured_sostenuto = 0;
181 v->channel = c;
182 v->layer = l;
183 v->play_count = 0;
184 v->program = c->program;
185 v->amp_env.shape = &l->amp_env_shape;
186 v->filter_env.shape = &l->filter_env_shape;
187 v->pitch_env.shape = &l->pitch_env_shape;
189 v->cutoff_shift = vel * l->fil_veltrack / 127.0 + (note - l->fil_keycenter) * l->fil_keytrack;
190 v->loop_mode = l->loop_mode;
191 v->off_by = l->off_by;
192 int auxes = (m->module.outputs - m->module.aux_offset) / 2;
193 if (l->effect1bus >= 1 && l->effect1bus < 1 + auxes)
194 v->send1bus = l->effect1bus;
195 else
196 v->send1bus = 0;
197 if (l->effect2bus >= 1 && l->effect2bus < 1 + auxes)
198 v->send2bus = l->effect2bus;
199 else
200 v->send2bus = 0;
201 v->send1gain = l->effect1 * 0.01;
202 v->send2gain = l->effect2 * 0.01;
203 if (l->group >= 1 && *pexgroupcount < MAX_RELEASED_GROUPS)
205 gboolean found = FALSE;
206 for (int j = 0; j < *pexgroupcount; j++)
208 if (exgroups[j] == l->group)
210 found = TRUE;
211 break;
214 if (!found)
216 exgroups[(*pexgroupcount)++] = l->group;
219 lfo_init(&v->amp_lfo, &l->amp_lfo, m->module.srate, m->module.srate_inv);
220 lfo_init(&v->filter_lfo, &l->filter_lfo, m->module.srate, m->module.srate_inv);
221 lfo_init(&v->pitch_lfo, &l->pitch_lfo, m->module.srate, m->module.srate_inv);
223 cbox_biquadf_reset(&v->filter_left);
224 cbox_biquadf_reset(&v->filter_right);
225 cbox_biquadf_reset(&v->filter_left2);
226 cbox_biquadf_reset(&v->filter_right2);
228 GSList *nif = v->layer->nifs;
229 while(nif)
231 struct sampler_noteinitfunc *p = nif->data;
232 p->notefunc(p, v);
233 nif = nif->next;
236 cbox_envelope_reset(&v->amp_env);
237 cbox_envelope_reset(&v->filter_env);
238 cbox_envelope_reset(&v->pitch_env);
240 sampler_voice_activate(v, l->eff_waveform->info.channels == 2 ? spt_stereo16 : spt_mono16);
242 if (v->current_pipe && v->gen.bigpos)
243 cbox_prefetch_pipe_consumed(v->current_pipe, v->gen.bigpos >> 32);
246 void sampler_voice_link(struct sampler_voice **pv, struct sampler_voice *v)
248 v->prev = NULL;
249 v->next = *pv;
250 if (*pv)
251 (*pv)->prev = v;
252 *pv = v;
255 void sampler_voice_unlink(struct sampler_voice **pv, struct sampler_voice *v)
257 if (*pv == v)
258 *pv = v->next;
259 if (v->prev)
260 v->prev->next = v->next;
261 if (v->next)
262 v->next->prev = v->prev;
263 v->prev = NULL;
264 v->next = NULL;
267 void sampler_voice_inactivate(struct sampler_voice *v, gboolean expect_active)
269 assert((v->gen.mode != spt_inactive) == expect_active);
270 sampler_voice_unlink(&v->channel->voices_running, v);
271 v->gen.mode = spt_inactive;
272 if (v->current_pipe)
274 cbox_prefetch_stack_push(v->program->module->pipe_stack, v->current_pipe);
275 v->current_pipe = NULL;
277 v->channel = NULL;
278 sampler_voice_link(&v->program->module->voices_free, v);
281 void sampler_voice_release(struct sampler_voice *v, gboolean is_polyaft)
283 if ((v->loop_mode == slm_one_shot_chokeable) != is_polyaft)
284 return;
285 if (v->delay >= v->age + CBOX_BLOCK_SIZE)
287 v->released = 1;
288 sampler_voice_inactivate(v, TRUE);
290 else
292 if (v->loop_mode != slm_one_shot && !v->layer->count)
293 v->released = 1;
297 void sampler_voice_process(struct sampler_voice *v, struct sampler_module *m, cbox_sample_t **outputs)
299 struct sampler_layer_data *l = v->layer;
300 assert(v->gen.mode != spt_inactive);
302 // if it's a DAHD envelope without sustain, consider the note finished
303 if (v->amp_env.cur_stage == 4 && v->amp_env.shape->stages[3].end_value == 0)
304 cbox_envelope_go_to(&v->amp_env, 15);
306 struct sampler_channel *c = v->channel;
307 v->age += CBOX_BLOCK_SIZE;
309 if (v->age < v->delay)
310 return;
312 if (v->last_waveform != v->layer->eff_waveform)
314 v->last_waveform = v->layer->eff_waveform;
315 if (v->layer->eff_waveform)
317 v->gen.mode = v->layer->eff_waveform->info.channels == 2 ? spt_stereo16 : spt_mono16;
318 v->gen.cur_sample_end = v->layer->eff_waveform->info.frames;
320 else
322 sampler_voice_inactivate(v, TRUE);
323 return;
326 // XXXKF I'm sacrificing sample accuracy for delays for now
327 v->delay = 0;
329 float pitch = (v->note - l->pitch_keycenter) * l->pitch_keytrack + l->tune + l->transpose * 100 + v->pitch_shift;
330 float modsrcs[smsrc_pernote_count];
331 modsrcs[smsrc_vel - smsrc_pernote_offset] = v->vel * (1.0 / 127.0);
332 modsrcs[smsrc_pitch - smsrc_pernote_offset] = pitch * (1.0 / 100.0);
333 modsrcs[smsrc_polyaft - smsrc_pernote_offset] = 0; // XXXKF not supported yet
334 modsrcs[smsrc_pitchenv - smsrc_pernote_offset] = cbox_envelope_get_next(&v->pitch_env, v->released) * 0.01f;
335 modsrcs[smsrc_filenv - smsrc_pernote_offset] = cbox_envelope_get_next(&v->filter_env, v->released) * 0.01f;
336 modsrcs[smsrc_ampenv - smsrc_pernote_offset] = cbox_envelope_get_next(&v->amp_env, v->released) * 0.01f;
338 modsrcs[smsrc_amplfo - smsrc_pernote_offset] = lfo_run(&v->amp_lfo);
339 modsrcs[smsrc_fillfo - smsrc_pernote_offset] = lfo_run(&v->filter_lfo);
340 modsrcs[smsrc_pitchlfo - smsrc_pernote_offset] = lfo_run(&v->pitch_lfo);
342 if (v->amp_env.cur_stage < 0)
344 if (is_tail_finished(v))
346 sampler_voice_inactivate(v, TRUE);
347 return;
351 float moddests[smdestcount];
352 moddests[smdest_gain] = 0;
353 moddests[smdest_pitch] = pitch;
354 moddests[smdest_cutoff] = v->cutoff_shift;
355 moddests[smdest_resonance] = 0;
356 GSList *mod = l->modulations;
357 if (l->trigger == stm_release)
358 moddests[smdest_gain] -= v->age * l->rt_decay * m->module.srate_inv;
360 if (c->pitchwheel)
361 moddests[smdest_pitch] += c->pitchwheel * (c->pitchwheel > 0 ? l->bend_up : l->bend_down) >> 13;
363 static const int modoffset[4] = {0, -1, -1, 1 };
364 static const int modscale[4] = {1, 1, 2, -2 };
365 while(mod)
367 struct sampler_modulation *sm = mod->data;
368 float value = 0.f, value2 = 1.f;
369 if (sm->src < smsrc_pernote_offset)
370 value = c->cc[sm->src] / 127.0;
371 else
372 value = modsrcs[sm->src - smsrc_pernote_offset];
373 value = modoffset[sm->flags & 3] + value * modscale[sm->flags & 3];
375 if (sm->src2 != smsrc_none)
377 if (sm->src2 < smsrc_pernote_offset)
378 value2 = c->cc[sm->src2] / 127.0;
379 else
380 value2 = modsrcs[sm->src2 - smsrc_pernote_offset];
382 value2 = modoffset[(sm->flags & 12) >> 2] + value2 * modscale[(sm->flags & 12) >> 2];
383 value *= value2;
385 moddests[sm->dest] += value * sm->amount;
387 mod = g_slist_next(mod);
390 double maxv = 127 << 7;
391 double freq = l->eff_freq * cent2factor(moddests[smdest_pitch]) ;
392 uint64_t freq64 = (uint64_t)(freq * 65536.0 * 65536.0 * m->module.srate_inv);
393 if (!v->current_pipe)
395 v->gen.sample_data = v->last_waveform->data;
396 if (v->last_waveform->levels)
398 // XXXKF: optimise later by caching last lookup value
399 // XXXKF: optimise later by using binary search
400 for (int i = 0; i < v->last_waveform->level_count; i++)
402 if (freq64 <= v->last_waveform->levels[i].max_rate)
404 v->gen.sample_data = v->last_waveform->levels[i].data;
405 break;
410 gboolean post_sustain = v->released && v->loop_mode == slm_loop_sustain;
411 uint32_t loop_start, loop_end;
412 if (v->layer->count > 0)
414 // End the loop on the last time
415 gboolean play_loop = (v->play_count < v->layer->count - 1);
416 loop_start = play_loop ? 0 : (uint32_t)-1;
417 loop_end = v->gen.cur_sample_end;
419 else
421 gboolean play_loop = v->layer->loop_end && (v->loop_mode == slm_loop_continuous || (v->loop_mode == slm_loop_sustain && !post_sustain)) && v->layer->on_cc_number == -1;
422 loop_start = play_loop ? v->layer->loop_start : (uint32_t)-1;
423 loop_end = play_loop ? v->layer->loop_end : v->gen.cur_sample_end;
426 if (v->current_pipe)
428 v->current_pipe->file_loop_end = loop_end;
429 v->current_pipe->file_loop_start = loop_start;
430 v->gen.sample_data = v->gen.loop_count ? v->current_pipe->data : v->last_waveform->data;
431 v->gen.streaming_buffer = v->current_pipe->data;
433 v->gen.loop_start = 0;
434 v->gen.loop_overlap = 0;
435 v->gen.loop_end = v->last_waveform->preloaded_frames;
436 v->gen.streaming_buffer_frames = v->current_pipe->buffer_loop_end;
438 else
440 v->gen.loop_start = loop_start;
441 v->gen.loop_end = loop_end;
442 v->gen.scratch = loop_start == (uint32_t)-1 ? v->layer->scratch_end : v->layer->scratch_loop;
446 v->gen.bigdelta = freq64;
447 float gain = modsrcs[smsrc_ampenv - smsrc_pernote_offset] * l->volume_linearized * v->gain_fromvel * sampler_channel_addcc(c, 7) * sampler_channel_addcc(c, 11) / (maxv * maxv);
448 if (moddests[smdest_gain] != 0.0)
449 gain *= dB2gain(moddests[smdest_gain]);
450 // http://drealm.info/sfz/plj-sfz.xhtml#amp "The overall gain must remain in the range -144 to 6 decibels."
451 if (gain > 2)
452 gain = 2;
453 float pan = (l->pan + 100) * (1.0 / 200.0) + (sampler_channel_addcc(c, 10) * 1.0 / maxv - 0.5) * 2;
454 if (pan < 0)
455 pan = 0;
456 if (pan > 1)
457 pan = 1;
458 v->gen.lgain = gain * (1 - pan) / 32768.0;
459 v->gen.rgain = gain * pan / 32768.0;
460 if (l->cutoff != -1)
462 float cutoff = l->cutoff * cent2factor(moddests[smdest_cutoff]);
463 if (cutoff < 20)
464 cutoff = 20;
465 if (cutoff > m->module.srate * 0.45)
466 cutoff = m->module.srate * 0.45;
467 //float resonance = v->resonance*pow(32.0,c->cc[71]/maxv);
468 float resonance = l->resonance_linearized * dB2gain(moddests[smdest_resonance]);
469 if (resonance < 0.7)
470 resonance = 0.7;
471 if (resonance > 32)
472 resonance = 32;
473 // XXXKF this is found experimentally and probably far off from correct formula
474 if (is_4pole(v->layer))
475 resonance = sqrt(resonance / 0.707) * 0.5;
476 switch(l->fil_type)
478 case sft_lp12:
479 case sft_lp24:
480 cbox_biquadf_set_lp_rbj(&v->filter_coeffs, cutoff, resonance, m->module.srate);
481 break;
482 case sft_hp12:
483 case sft_hp24:
484 cbox_biquadf_set_hp_rbj(&v->filter_coeffs, cutoff, resonance, m->module.srate);
485 break;
486 case sft_bp6:
487 case sft_bp12:
488 cbox_biquadf_set_bp_rbj(&v->filter_coeffs, cutoff, resonance, m->module.srate);
489 break;
490 case sft_lp6:
491 cbox_biquadf_set_1plp(&v->filter_coeffs, cutoff, m->module.srate);
492 break;
493 case sft_hp6:
494 cbox_biquadf_set_1php(&v->filter_coeffs, cutoff, m->module.srate);
495 break;
496 default:
497 assert(0);
501 float left[CBOX_BLOCK_SIZE], right[CBOX_BLOCK_SIZE];
503 uint32_t samples = 0;
506 if (v->current_pipe)
508 uint32_t limit = cbox_prefetch_pipe_get_remaining(v->current_pipe) - 4;
509 if (!limit)
510 v->gen.mode = spt_inactive;
511 else
513 samples = sampler_gen_sample_playback(&v->gen, left, right, limit);
514 cbox_prefetch_pipe_consumed(v->current_pipe, v->gen.consumed);
515 v->gen.consumed = 0;
518 else
520 v->play_count = v->gen.loop_count;
521 samples = sampler_gen_sample_playback(&v->gen, left, right, (uint32_t)-1);
524 for (int i = samples; i < CBOX_BLOCK_SIZE; i++)
525 left[i] = right[i] = 0.f;
526 if (l->cutoff != -1)
528 cbox_biquadf_process(&v->filter_left, &v->filter_coeffs, left);
529 if (is_4pole(v->layer))
530 cbox_biquadf_process(&v->filter_left2, &v->filter_coeffs, left);
531 cbox_biquadf_process(&v->filter_right, &v->filter_coeffs, right);
532 if (is_4pole(v->layer))
533 cbox_biquadf_process(&v->filter_right2, &v->filter_coeffs, right);
535 mix_block_into_with_gain(outputs, v->output_pair_no * 2, left, right, 1.0);
536 if ((v->send1bus > 0 && v->send1gain != 0) || (v->send2bus > 0 && v->send2gain != 0))
538 if (v->send1bus > 0 && v->send1gain != 0)
540 int oofs = m->module.aux_offset + (v->send1bus - 1) * 2;
541 mix_block_into_with_gain(outputs, oofs, left, right, v->send1gain);
543 if (v->send2bus > 0 && v->send2gain != 0)
545 int oofs = m->module.aux_offset + (v->send2bus - 1) * 2;
546 mix_block_into_with_gain(outputs, oofs, left, right, v->send2gain);
549 if (v->gen.mode == spt_inactive)
550 sampler_voice_inactivate(v, FALSE);