Attempt to fix amplitude release time.
[calfbox.git] / sampler_layer.c
blob1f065ad70f2e03bd26e7a8373ec6d8bd2c127a1c
1 /*
2 Calf Box, an open source musical instrument.
3 Copyright (C) 2010-2011 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 "sfzloader.h"
27 #include <assert.h>
28 #include <errno.h>
29 #include <glib.h>
30 #include <math.h>
31 #include <memory.h>
32 #include <sndfile.h>
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <locale.h>
36 #include <xlocale.h>
38 static void sampler_layer_data_set_modulation(struct sampler_layer_data *l, enum sampler_modsrc src, enum sampler_modsrc src2, enum sampler_moddest dest, float amount, int flags, gboolean propagating_defaults)
40 GSList *p = l->modulations;
41 while(p)
43 struct sampler_modulation *sm = p->data;
44 if (sm->src == src && sm->src2 == src2 && sm->dest == dest)
46 // do not overwrite locally set value with defaults
47 if (propagating_defaults && sm->has_value)
48 return;
49 sm->amount = amount;
50 sm->flags = flags;
51 sm->has_value = !propagating_defaults;
52 return;
54 p = g_slist_next(p);
56 struct sampler_modulation *sm = g_malloc0(sizeof(struct sampler_modulation));
57 sm->src = src;
58 sm->src2 = src2;
59 sm->dest = dest;
60 sm->amount = amount;
61 sm->flags = flags;
62 sm->has_value = !propagating_defaults;
63 l->modulations = g_slist_prepend(l->modulations, sm);
66 void sampler_layer_set_modulation1(struct sampler_layer *l, enum sampler_modsrc src, enum sampler_moddest dest, float amount, int flags)
68 sampler_layer_data_set_modulation(&l->data, src, smsrc_none, dest, amount, flags, FALSE);
71 void sampler_layer_set_modulation(struct sampler_layer *l, enum sampler_modsrc src, enum sampler_modsrc src2, enum sampler_moddest dest, float amount, int flags)
73 sampler_layer_data_set_modulation(&l->data, src, src2, dest, amount, flags, FALSE);
76 void sampler_layer_data_add_nif(struct sampler_layer_data *l, SamplerNoteInitFunc notefunc, int variant, float param, gboolean propagating_defaults)
78 GSList *p = l->nifs;
79 while(p)
81 struct sampler_noteinitfunc *nif = p->data;
82 if (nif->notefunc == notefunc && nif->variant == variant)
84 // do not overwrite locally set value with defaults
85 if (propagating_defaults && nif->has_value)
86 return;
87 nif->param = param;
88 nif->has_value = !propagating_defaults;
89 return;
91 p = g_slist_next(p);
93 struct sampler_noteinitfunc *nif = malloc(sizeof(struct sampler_noteinitfunc));
94 nif->notefunc = notefunc;
95 nif->variant = variant;
96 nif->param = param;
97 nif->has_value = !propagating_defaults;
98 l->nifs = g_slist_prepend(l->nifs, nif);
101 void sampler_layer_add_nif(struct sampler_layer *l, SamplerNoteInitFunc notefunc, int variant, float param)
103 sampler_layer_data_add_nif(&l->data, notefunc, variant, param, FALSE);
106 static gboolean sampler_layer_process_cmd(struct cbox_command_target *ct, struct cbox_command_target *fb, struct cbox_osc_command *cmd, GError **error)
108 struct sampler_layer *layer = ct->user_data;
109 if (!strcmp(cmd->command, "/status") && !strcmp(cmd->arg_types, ""))
111 if (!cbox_check_fb_channel(fb, cmd->command, error))
112 return FALSE;
114 if (!((!layer->parent_program || cbox_execute_on(fb, NULL, "/parent_program", "o", error, layer->parent_program)) &&
115 (!layer->parent_group || cbox_execute_on(fb, NULL, "/parent_group", "o", error, layer->parent_group)) &&
116 CBOX_OBJECT_DEFAULT_STATUS(layer, fb, error)))
117 return FALSE;
118 return TRUE;
120 if ((!strcmp(cmd->command, "/as_string") || !strcmp(cmd->command, "/as_string_full")) && !strcmp(cmd->arg_types, ""))
122 if (!cbox_check_fb_channel(fb, cmd->command, error))
123 return FALSE;
124 gchar *res = sampler_layer_to_string(layer, !strcmp(cmd->command, "/as_string_full"));
125 gboolean result = cbox_execute_on(fb, NULL, "/value", "s", error, res);
126 g_free(res);
127 return result;
129 if (!strcmp(cmd->command, "/set_param") && !strcmp(cmd->arg_types, "ss"))
131 const char *key = CBOX_ARG_S(cmd, 0);
132 const char *value = CBOX_ARG_S(cmd, 1);
133 if (sampler_layer_apply_param(layer, key, value, error))
135 sampler_layer_update(layer);
136 sampler_program_update_layers(layer->parent_program);
137 return TRUE;
139 return FALSE;
141 if (!strcmp(cmd->command, "/new_region") && !strcmp(cmd->arg_types, ""))
143 if (layer->parent_group)
145 g_set_error(error, CBOX_MODULE_ERROR, CBOX_MODULE_ERROR_FAILED, "Cannot create a region within a region");
146 return FALSE;
148 struct sampler_layer *l = sampler_layer_new(layer->module, layer->parent_program, layer);
149 sampler_layer_data_finalize(&l->data, l->parent_group ? &l->parent_group->data : NULL, layer->module);
150 sampler_layer_reset_switches(l, l->module);
151 sampler_layer_update(l);
153 sampler_program_add_layer(layer->parent_program, l);
154 sampler_program_update_layers(layer->parent_program);
156 return cbox_execute_on(fb, NULL, "/uuid", "o", error, l);
158 if (!strcmp(cmd->command, "/get_children") && !strcmp(cmd->arg_types, ""))
160 if (!cbox_check_fb_channel(fb, cmd->command, error))
161 return FALSE;
162 GHashTableIter iter;
163 g_hash_table_iter_init(&iter, layer->child_layers);
164 gpointer key, value;
165 while(g_hash_table_iter_next(&iter, &key, &value))
167 if (!cbox_execute_on(fb, NULL, "/region", "o", error, key))
168 return FALSE;
170 return TRUE;
172 // otherwise, treat just like an command on normal (non-aux) output
173 return cbox_object_default_process_cmd(ct, fb, cmd, error);
178 #define PROC_FIELDS_INITIALISER(type, name, def_value) \
179 ld->name = def_value; \
180 ld->has_##name = 0;
181 #define PROC_FIELDS_INITIALISER_enum(type, name, def_value) \
182 PROC_FIELDS_INITIALISER(type, name, def_value)
183 #define PROC_FIELDS_INITIALISER_dBamp(type, name, def_value) \
184 ld->name = def_value; \
185 ld->name##_linearized = -1; \
186 ld->has_##name = 0;
187 #define PROC_FIELDS_INITIALISER_dahdsr(name, parname, index) \
188 DAHDSR_FIELDS(PROC_SUBSTRUCT_RESET_FIELD, name, ld); \
189 DAHDSR_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, ld)
190 #define PROC_FIELDS_INITIALISER_lfo(name, parname, index) \
191 LFO_FIELDS(PROC_SUBSTRUCT_RESET_FIELD, name, ld); \
192 LFO_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, ld)
193 #define PROC_FIELDS_INITIALISER_ccrange(name) \
194 ld->name##locc = 0; \
195 ld->name##hicc = 127; \
196 ld->name##cc_number = 0; \
197 ld->has_##name##locc = 0; \
198 ld->has_##name##hicc = 0;
200 CBOX_CLASS_DEFINITION_ROOT(sampler_layer)
202 struct sampler_layer *sampler_layer_new(struct sampler_module *m, struct sampler_program *parent_program, struct sampler_layer *parent_group)
204 struct sampler_layer *l = malloc(sizeof(struct sampler_layer));
205 struct cbox_document *doc = CBOX_GET_DOCUMENT(parent_program);
206 memset(l, 0, sizeof(struct sampler_layer));
207 CBOX_OBJECT_HEADER_INIT(l, sampler_layer, doc);
208 cbox_command_target_init(&l->cmd_target, sampler_layer_process_cmd, l);
210 l->module = m;
211 l->child_layers = g_hash_table_new(NULL, NULL);
212 if (parent_group)
214 sampler_layer_data_clone(&l->data, &parent_group->data, FALSE);
215 l->parent_program = parent_program;
216 l->parent_group = parent_group;
217 g_hash_table_add(parent_group->child_layers, l);
218 l->runtime = NULL;
219 CBOX_OBJECT_REGISTER(l);
220 return l;
222 l->parent_program = parent_program;
223 struct sampler_layer_data *ld = &l->data;
224 ld->waveform = NULL;
225 ld->has_waveform = FALSE;
227 SAMPLER_FIXED_FIELDS(PROC_FIELDS_INITIALISER)
229 ld->eff_freq = 44100;
230 ld->velcurve[0] = 0;
231 ld->velcurve[127] = 1;
232 for (int i = 1; i < 127; i++)
233 ld->velcurve[i] = -1;
234 ld->modulations = NULL;
235 ld->nifs = NULL;
236 ld->on_locc = 0;
237 ld->on_hicc = 127;
238 ld->on_cc_number = -1;
240 ld->eff_use_keyswitch = 0;
241 l->last_key = -1;
242 if (!parent_group)
244 sampler_layer_set_modulation1(l, 74, smdest_cutoff, 9600, 2);
245 sampler_layer_set_modulation1(l, 71, smdest_resonance, 12, 2);
246 sampler_layer_set_modulation(l, smsrc_pitchlfo, 1, smdest_pitch, 100, 0);
248 l->runtime = NULL;
249 l->unknown_keys = NULL;
250 CBOX_OBJECT_REGISTER(l);
251 return l;
254 #define PROC_FIELDS_CLONE(type, name, def_value) \
255 dst->name = src->name; \
256 dst->has_##name = copy_hasattr ? src->has_##name : FALSE;
257 #define PROC_FIELDS_CLONE_dBamp PROC_FIELDS_CLONE
258 #define PROC_FIELDS_CLONE_enum PROC_FIELDS_CLONE
259 #define PROC_FIELDS_CLONE_dahdsr(name, parname, index) \
260 DAHDSR_FIELDS(PROC_SUBSTRUCT_CLONE, name, dst, src) \
261 if (!copy_hasattr) \
262 DAHDSR_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, dst)
263 #define PROC_FIELDS_CLONE_lfo(name, parname, index) \
264 LFO_FIELDS(PROC_SUBSTRUCT_CLONE, name, dst, src) \
265 if (!copy_hasattr) \
266 LFO_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, dst)
267 #define PROC_FIELDS_CLONE_ccrange(name) \
268 dst->name##locc = src->name##locc; \
269 dst->name##hicc = src->name##hicc; \
270 dst->name##cc_number = src->name##cc_number; \
271 dst->has_##name##locc = copy_hasattr ? src->has_##name##locc : FALSE; \
272 dst->has_##name##hicc = copy_hasattr ? src->has_##name##hicc : FALSE;
274 void sampler_layer_data_clone(struct sampler_layer_data *dst, const struct sampler_layer_data *src, gboolean copy_hasattr)
276 dst->waveform = src->waveform;
277 if (dst->waveform)
278 cbox_waveform_ref(dst->waveform);
279 if (copy_hasattr)
280 dst->has_waveform = src->has_waveform;
281 SAMPLER_FIXED_FIELDS(PROC_FIELDS_CLONE)
282 memcpy(dst->velcurve, src->velcurve, 128 * sizeof(float));
283 dst->modulations = g_slist_copy(src->modulations);
284 for(GSList *mod = dst->modulations; mod; mod = mod->next)
286 struct sampler_modulation *srcm = mod->data;
287 struct sampler_modulation *dstm = g_malloc(sizeof(struct sampler_modulation));
288 memcpy(dstm, srcm, sizeof(struct sampler_modulation));
289 dstm->has_value = copy_hasattr ? srcm->has_value : FALSE;
290 mod->data = dstm;
292 dst->nifs = g_slist_copy(src->nifs);
293 for(GSList *nif = dst->nifs; nif; nif = nif->next)
295 struct sampler_noteinitfunc *dstn = g_malloc(sizeof(struct sampler_noteinitfunc));
296 struct sampler_noteinitfunc *srcn = nif->data;
297 memcpy(dstn, srcn, sizeof(struct sampler_noteinitfunc));
298 dstn->has_value = copy_hasattr ? srcn->has_value : FALSE;
299 nif->data = dstn;
303 #define PROC_FIELDS_CLONEPARENT(type, name, def_value) \
304 if (!l->has_##name) \
305 l->name = parent ? parent->name : def_value;
306 #define PROC_FIELDS_CLONEPARENT_dBamp PROC_FIELDS_CLONEPARENT
307 #define PROC_FIELDS_CLONEPARENT_enum PROC_FIELDS_CLONEPARENT
308 #define PROC_FIELDS_CLONEPARENT_dahdsr(name, parname, index) \
309 DAHDSR_FIELDS(PROC_SUBSTRUCT_CLONEPARENT, name, l)
310 #define PROC_FIELDS_CLONEPARENT_lfo(name, parname, index) \
311 LFO_FIELDS(PROC_SUBSTRUCT_CLONEPARENT, name, l)
312 #define PROC_FIELDS_CLONEPARENT_ccrange(name) \
313 if (!l->has_##name##locc) \
314 l->name##locc = parent ? parent->name##locc : 0; \
315 if (!l->has_##name##hicc) \
316 l->name##hicc = parent ? parent->name##hicc : 127; \
317 if (!l->has_##name##locc && !l->has_##name##hicc) \
318 l->name##cc_number = parent ? parent->name##cc_number : -1;
320 static void sampler_layer_data_getdefaults(struct sampler_layer_data *l, struct sampler_layer_data *parent)
322 if (!l->has_waveform)
323 l->waveform = parent ? parent->waveform : NULL;
324 SAMPLER_FIXED_FIELDS(PROC_FIELDS_CLONEPARENT)
325 // XXXKF: add handling for velcurve
326 if (parent)
328 // set NIFs used by parent
329 for(GSList *mod = parent->nifs; mod; mod = mod->next)
331 struct sampler_noteinitfunc *nif = mod->data;
332 sampler_layer_data_add_nif(l, nif->notefunc, nif->variant, nif->param, TRUE);
334 // set modulations used by parent
335 for(GSList *mod = parent->modulations; mod; mod = mod->next)
337 struct sampler_modulation *srcm = mod->data;
338 sampler_layer_data_set_modulation(l, srcm->src, srcm->src2, srcm->dest, srcm->amount, srcm->flags, TRUE);
343 void sampler_layer_set_waveform(struct sampler_layer *l, struct cbox_waveform *waveform)
345 l->data.has_waveform = waveform != NULL;
346 l->data.waveform = waveform;
349 #define PROC_FIELDS_FINALISER(type, name, def_value)
350 #define PROC_FIELDS_FINALISER_enum(type, name, def_value)
351 #define PROC_FIELDS_FINALISER_dBamp(type, name, def_value) \
352 l->name##_linearized = dB2gain(l->name);
353 #define PROC_FIELDS_FINALISER_dahdsr(name, parname, index) \
354 cbox_envelope_init_dahdsr(&l->name##_shape, &l->name, m->module.srate / CBOX_BLOCK_SIZE, 100.f, &l->name##_shape == &l->amp_env_shape);
355 #define PROC_FIELDS_FINALISER_lfo(name, parname, index) /* no finaliser required */
356 #define PROC_FIELDS_FINALISER_ccrange(name) /* no finaliser required */
358 void sampler_layer_data_finalize(struct sampler_layer_data *l, struct sampler_layer_data *parent, struct sampler_module *m)
360 SAMPLER_FIXED_FIELDS(PROC_FIELDS_FINALISER)
362 sampler_layer_data_getdefaults(l, parent);
363 l->eff_freq = (l->waveform && l->waveform->info.samplerate) ? l->waveform->info.samplerate : 44100;
364 // XXXKF should have a distinction between 'configured' and 'effective' loop start/end
365 if (l->loop_mode == slm_unknown)
367 if (l->waveform && l->waveform->has_loop)
368 l->loop_mode = slm_loop_continuous;
369 else
370 l->loop_mode = l->loop_end == 0 ? slm_no_loop : slm_loop_continuous;
373 if (l->loop_mode == slm_one_shot || l->loop_mode == slm_no_loop || l->loop_mode == slm_one_shot_chokeable)
374 l->loop_start = -1;
376 if ((l->loop_mode == slm_loop_continuous || l->loop_mode == slm_loop_sustain) && l->loop_start == -1)
377 l->loop_start = 0;
378 if ((l->loop_mode == slm_loop_continuous || l->loop_mode == slm_loop_sustain) && l->loop_start == 0 && l->waveform && l->waveform->has_loop)
379 l->loop_start = l->waveform->loop_start;
380 if (l->loop_end == 0 && l->waveform != NULL && l->waveform->has_loop)
381 l->loop_end = l->waveform->loop_end;
383 if (l->off_mode == som_unknown)
384 l->off_mode = l->off_by != 0 ? som_fast : som_normal;
386 // if no amp_velcurve_nnn setting, default to quadratic
387 if (l->velcurve_quadratic == -1)
388 l->velcurve_quadratic = 1;
390 if (l->key >= 0 && l->key <= 127)
391 l->lokey = l->hikey = l->pitch_keycenter = l->key;
393 // interpolate missing points in velcurve
394 int start = 0;
395 for (int i = 1; i < 128; i++)
397 if (l->velcurve[i] == -1)
398 continue;
399 float sv = l->velcurve[start];
400 float ev = l->velcurve[i];
401 if (l->velcurve_quadratic)
403 for (int j = start; j <= i; j++)
404 l->eff_velcurve[j] = sv + (ev - sv) * (j - start) * (j - start) / ((i - start) * (i - start));
406 else
408 for (int j = start; j <= i; j++)
409 l->eff_velcurve[j] = sv + (ev - sv) * (j - start) / (i - start);
411 start = i;
413 l->eff_use_keyswitch = ((l->sw_down != -1) || (l->sw_up != -1) || (l->sw_last != -1) || (l->sw_previous != -1));
416 void sampler_layer_reset_switches(struct sampler_layer *l, struct sampler_module *m)
418 l->last_key = l->data.sw_lokey;
419 l->current_seq_position = l->data.seq_position;
422 struct layer_foreach_struct
424 struct sampler_layer *layer;
425 const char *cfg_section;
428 static void layer_foreach_func(void *user_data, const char *key)
430 if (!strcmp(key, "file"))
431 key = "sample";
432 // import is handled in sampler_load_layer_overrides
433 if (!strcmp(key, "import"))
434 return;
435 struct layer_foreach_struct *lfs = user_data;
436 const char *value = cbox_config_get_string(lfs->cfg_section, key);
437 GError *error = NULL;
438 if (!sampler_layer_apply_param(lfs->layer, key, value, &error))
440 if (error)
441 g_warning("Error '%s', context: %s in section %s", error->message, key, lfs->cfg_section);
442 else
443 g_warning("Unknown sample layer parameter: %s in section %s", key, lfs->cfg_section);
447 void sampler_layer_load_overrides(struct sampler_layer *l, const char *cfg_section)
449 char *imp = cbox_config_get_string(cfg_section, "import");
450 if (imp)
451 sampler_layer_load_overrides(l, imp);
453 struct layer_foreach_struct lfs = {
454 .layer = l,
455 .cfg_section = cfg_section
457 cbox_config_foreach_key(layer_foreach_func, cfg_section, &lfs);
460 struct sampler_layer *sampler_layer_new_from_section(struct sampler_module *m, struct sampler_program *parent_program, const char *cfg_section)
462 struct sampler_layer *l = sampler_layer_new(m, parent_program, NULL);
463 sampler_layer_load_overrides(l, cfg_section);
464 sampler_layer_data_finalize(&l->data, l->parent_group ? &l->parent_group->data : NULL, m);
465 sampler_layer_reset_switches(l, m);
466 return l;
469 static int sfz_note_from_string(const char *note)
471 static const int semis[] = {9, 11, 0, 2, 4, 5, 7};
472 int pos;
473 int nn = tolower(note[0]);
474 int nv;
475 if (nn >= '0' && nn <= '9')
476 return atoi(note);
477 if (nn < 'a' && nn > 'g')
478 return -1;
479 nv = semis[nn - 'a'];
481 for (pos = 1; tolower(note[pos]) == 'b' || note[pos] == '#'; pos++)
482 nv += (note[pos] != '#') ? -1 : +1;
484 if ((note[pos] == '-' && note[pos + 1] == '1' && note[pos + 2] == '\0') || (note[pos] >= '0' && note[pos] <= '9' && note[pos + 1] == '\0'))
486 return nv + 12 * (1 + atoi(note + pos));
489 return -1;
492 static double atof_C(const char *value)
494 return g_ascii_strtod(value, NULL);
497 static gboolean parse_envelope_param(struct sampler_layer *layer, struct cbox_dahdsr *env, struct sampler_dahdsr_has_fields *has_fields, int env_type, const char *key, const char *value)
499 static const enum sampler_modsrc srcs[] = { smsrc_ampenv, smsrc_filenv, smsrc_pitchenv };
500 static const enum sampler_moddest dests[] = { smdest_gain, smdest_cutoff, smdest_pitch };
501 enum sampler_modsrc src = srcs[env_type];
502 enum sampler_moddest dest = dests[env_type];
503 float fvalue = atof_C(value);
505 #define PROC_SET_ENV_FIELD(name, index, def_value) \
506 if (!strcmp(key, #name)) {\
507 env->name = fvalue; \
508 has_fields->name = 1; \
509 return TRUE; \
511 DAHDSR_FIELDS(PROC_SET_ENV_FIELD)
512 if (!strcmp(key, "depth"))
513 sampler_layer_set_modulation1(layer, src, dest, atof_C(value), 0);
514 else if (!strcmp(key, "vel2delay"))
515 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 0, fvalue);
516 else if (!strcmp(key, "vel2attack"))
517 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 1, fvalue);
518 else if (!strcmp(key, "vel2hold"))
519 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 2, fvalue);
520 else if (!strcmp(key, "vel2decay"))
521 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 3, fvalue);
522 else if (!strcmp(key, "vel2sustain"))
523 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 4, fvalue);
524 else if (!strcmp(key, "vel2release"))
525 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 5, fvalue);
526 else if (!strcmp(key, "vel2depth"))
527 sampler_layer_set_modulation(layer, src, smsrc_vel, dest, atof_C(value), 0);
528 else if (!strncmp(key, "depthcc", 7))
530 int cc = atoi(key + 7);
531 if (cc > 0 && cc < 120)
532 sampler_layer_set_modulation(layer, src, cc, dest, fvalue, 0);
533 else
534 return FALSE;
536 else
537 return FALSE;
538 return TRUE;
541 static gboolean parse_lfo_param(struct sampler_layer *layer, struct sampler_lfo_params *params, struct sampler_lfo_has_fields *has_fields, int lfo_type, const char *key, const char *value)
543 static const enum sampler_modsrc srcs[] = { smsrc_amplfo, smsrc_fillfo, smsrc_pitchlfo };
544 static const enum sampler_moddest dests[] = { smdest_gain, smdest_cutoff, smdest_pitch };
545 enum sampler_modsrc src = srcs[lfo_type];
546 enum sampler_moddest dest = dests[lfo_type];
548 #define PROC_SET_LFO_FIELD(name, index, def_value) \
549 if (!strcmp(key, #name)) {\
550 params->name = fvalue; \
551 has_fields->name = 1; \
552 return TRUE; \
554 float fvalue = atof_C(value);
555 LFO_FIELDS(PROC_SET_LFO_FIELD)
556 if (!strcmp(key, "depth"))
557 sampler_layer_set_modulation1(layer, src, dest, fvalue, 0);
558 else if (!strcmp(key, "depthchanaft"))
559 sampler_layer_set_modulation(layer, src, smsrc_chanaft, dest, fvalue, 0);
560 else if (!strcmp(key, "depthpolyaft"))
561 sampler_layer_set_modulation(layer, src, smsrc_polyaft, dest, fvalue, 0);
562 else if (!strncmp(key, "depthcc", 7))
564 int cc = atoi(key + 7);
565 if (cc > 0 && cc < 120)
566 sampler_layer_set_modulation(layer, src, cc, dest, fvalue, 0);
567 else
568 return FALSE;
570 else
571 return FALSE;
572 return TRUE;
575 #define PARSE_PARAM_midi_note_t(field, strname, valuestr) \
576 return ((l->data.field = sfz_note_from_string(value)), (l->data.has_##field = 1));
577 #define PARSE_PARAM_int(field, strname, valuestr) \
578 return ((l->data.field = atoi(value)), (l->data.has_##field = 1));
579 #define PARSE_PARAM_uint32_t(field, strname, valuestr) \
580 return ((l->data.field = (uint32_t)strtoul(value, NULL, 10)), (l->data.has_##field = 1));
581 #define PARSE_PARAM_float(field, strname, valuestr) \
582 return ((l->data.field = atof_C(value)), (l->data.has_##field = 1));
584 #define PROC_APPLY_PARAM(type, name, def_value) \
585 if (!strcmp(key, #name)) { \
586 PARSE_PARAM_##type(name, #name, value) \
588 #define PROC_APPLY_PARAM_dBamp(type, name, def_value) \
589 if (!strcmp(key, #name)) { \
590 return ((l->data.name = atof_C(value)), (l->data.has_##name = 1)); \
592 #define PROC_APPLY_PARAM_enum(enumtype, name, def_value) \
593 if (!strcmp(key, #name)) { \
594 if (!enumtype##_from_string(value, &l->data.name)) { \
595 g_set_error(error, CBOX_MODULE_ERROR, CBOX_MODULE_ERROR_FAILED, "Value %s is not a correct value for %s", value, #name); \
596 return FALSE; \
598 l->data.has_##name = 1; \
599 return TRUE; \
601 // LFO and envelope need special handling now
602 #define PROC_APPLY_PARAM_dahdsr(name, parname, index) \
603 if (!strncmp(key, #parname "_", sizeof(#parname))) \
604 return parse_envelope_param(l, &l->data.name, &l->data.has_##name, index, key + sizeof(#parname), value);
605 #define PROC_APPLY_PARAM_lfo(name, parname, index) \
606 if (!strncmp(key, #parname "_", sizeof(#parname))) \
607 return parse_lfo_param(l, &l->data.name, &l->data.has_##name, index, key + sizeof(#parname), value);
608 #define PROC_APPLY_PARAM_ccrange(name) /* handled separately in apply_param */
610 static void sampler_layer_apply_unknown(struct sampler_layer *l, const char *key, const char *value)
612 if (!l->unknown_keys)
613 l->unknown_keys = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
615 g_hash_table_insert(l->unknown_keys, g_strdup(key), g_strdup(value));
618 gboolean sampler_layer_apply_param(struct sampler_layer *l, const char *key, const char *value, GError **error)
620 try_now:
621 // XXXKF: this is seriously stupid code, this should use a hash table for
622 // fixed strings, or something else that doesn't explode O(N**2) with
623 // number of attributes. But premature optimization is a root of all evil.
625 SAMPLER_FIXED_FIELDS(PROC_APPLY_PARAM)
627 // XXXKF: to make things worse, some attributes have names different from
628 // C field names, or have multiple names, or don't map 1:1 to internal model
630 if (!strcmp(key, "sample"))
632 struct cbox_waveform *old_waveform = l->data.waveform;
633 gchar *value_copy = g_strdup(value);
634 gchar *filename = value_copy;
635 if (value[0] != '*')
637 for (int i = 0; value_copy[i]; i++)
639 if (value_copy[i] == '\\')
640 value_copy[i] = '/';
642 filename = g_build_filename(l->parent_program->sample_dir, value_copy, NULL);
643 g_free(value_copy);
645 struct cbox_waveform *wf = cbox_wavebank_get_waveform(l->parent_program->source_file, filename, error);
646 g_free(filename);
647 if (!wf)
648 return FALSE;
649 sampler_layer_set_waveform(l, wf);
650 if (old_waveform != NULL)
651 cbox_waveform_unref(old_waveform);
652 return TRUE;
654 else if (!strcmp(key, "lolev"))
655 l->data.lovel = atoi(value), l->data.has_lovel = 1;
656 else if (!strcmp(key, "hilev"))
657 l->data.hivel = atoi(value), l->data.has_hivel = 1;
658 else if (!strcmp(key, "benddown"))
659 l->data.bend_down = atoi(value), l->data.has_bend_down = 1;
660 else if (!strcmp(key, "bendup"))
661 l->data.bend_up = atoi(value), l->data.has_bend_up = 1;
662 else if (!strcmp(key, "loopstart"))
663 l->data.loop_start = atoi(value), l->data.has_loop_start = 1;
664 else if (!strcmp(key, "loopend"))
665 l->data.loop_end = atoi(value), l->data.has_loop_end = 1;
666 else if (!strcmp(key, "loopmode"))
668 key = "loop_mode";
669 goto try_now; // yes, goto, why not?
671 else if (!strcmp(key, "cutoff_chanaft"))
672 sampler_layer_set_modulation1(l, smsrc_chanaft, smdest_cutoff, atof_C(value), 0);
673 else if (!strcmp(key, "amp_random"))
674 sampler_layer_add_nif(l, sampler_nif_addrandom, 0, atof_C(value));
675 else if (!strcmp(key, "fil_random"))
676 sampler_layer_add_nif(l, sampler_nif_addrandom, 1, atof_C(value));
677 else if (!strcmp(key, "pitch_random"))
678 sampler_layer_add_nif(l, sampler_nif_addrandom, 2, atof_C(value));
679 else if (!strcmp(key, "pitch_veltrack"))
680 sampler_layer_add_nif(l, sampler_nif_vel2pitch, 0, atof_C(value));
681 else if (!strncmp(key, "delay_cc", 8))
683 int ccno = atoi(key + 8);
684 if (ccno > 0 && ccno < 120)
685 sampler_layer_add_nif(l, sampler_nif_cc2delay, ccno, atof_C(value));
686 else
687 goto unknown_key;
689 else if (!strncmp(key, "cutoff_cc", 9))
691 int ccno = atoi(key + 9);
692 if (ccno > 0 && ccno < 120)
693 sampler_layer_set_modulation1(l, ccno, smdest_cutoff, atof_C(value), 0);
694 else
695 goto unknown_key;
697 else if (!strncmp(key, "gain_cc", 7))
699 int ccno = atoi(key + 7);
700 if (ccno > 0 && ccno < 120)
701 sampler_layer_set_modulation1(l, ccno, smdest_gain, atof_C(value), 0);
702 else
703 goto unknown_key;
705 else if (!strncmp(key, "amp_velcurve_", 13))
707 // if not known yet, set to 0, it can always be overriden via velcurve_quadratic setting
708 if (l->data.velcurve_quadratic == -1)
709 l->data.velcurve_quadratic = 0;
710 int point = atoi(key + 13);
711 if (point >= 0 && point <= 127)
713 l->data.velcurve[point] = atof_C(value);
714 if (l->data.velcurve[point] < 0)
715 l->data.velcurve[point] = 0;
716 if (l->data.velcurve[point] > 1)
717 l->data.velcurve[point] = 1;
719 else
720 goto unknown_key;
722 else if (!strncmp(key, "on_locc", 7) || !strncmp(key, "on_hicc", 7))
724 int cc = atoi(key + 7);
725 if (cc > 0 && cc < 120)
727 if (*value)
729 l->data.on_cc_number = cc;
730 if (key[3] == 'l')
732 l->data.on_locc = atoi(value);
733 l->data.has_on_locc = TRUE;
735 else
737 l->data.on_hicc = atoi(value);
738 l->data.has_on_hicc = TRUE;
741 else
743 l->data.on_cc_number = -1;
744 l->data.has_on_locc = FALSE;
745 l->data.has_on_hicc = FALSE;
748 else
749 return FALSE;
751 else if (!strncmp(key, "locc", 4) || !strncmp(key, "hicc", 4))
753 int cc = atoi(key + 4);
754 if (cc > 0 && cc < 120)
756 if (*value)
758 l->data.cc_number = cc;
759 if (key[0] == 'l')
761 l->data.locc = atoi(value);
762 l->data.has_locc = TRUE;
764 else
766 l->data.hicc = atoi(value);
767 l->data.has_hicc = TRUE;
770 else
772 l->data.cc_number = -1;
773 l->data.has_locc = FALSE;
774 l->data.has_hicc = FALSE;
777 else
778 return FALSE;
780 else
781 goto unknown_key;
783 return TRUE;
784 unknown_key:
785 sampler_layer_apply_unknown(l, key, value);
786 g_warning("Unknown SFZ property key: '%s'", key);
787 return TRUE;
790 #define TYPE_PRINTF_uint32_t(name, def_value) \
791 if (show_inherited || l->has_##name) \
792 g_string_append_printf(outstr, " %s=%u", #name, (unsigned)(l->name));
793 #define TYPE_PRINTF_int(name, def_value) \
794 if (show_inherited || l->has_##name) \
795 g_string_append_printf(outstr, " %s=%d", #name, (int)(l->name));
796 #define TYPE_PRINTF_midi_note_t(name, def_value) \
797 if (show_inherited || l->has_##name) { \
798 int val = l->name; \
799 if (val == -1) \
800 g_string_append_printf(outstr, " %s=-1", #name); \
801 else \
802 g_string_append_printf(outstr, " %s=%c%s%d", #name, "ccddeffggaab"[val%12], "\000#\000#\000\000#\000#\000#\000#\000"+(val%12), (val/12-1)); \
803 } else {}
804 #define TYPE_PRINTF_float(name, def_value) \
805 if (show_inherited || l->has_##name) \
806 g_string_append_printf(outstr, " %s=%s", #name, g_ascii_dtostr(floatbuf, floatbufsize, l->name));
808 #define PROC_FIELDS_TO_FILEPTR(type, name, def_value) \
809 TYPE_PRINTF_##type(name, def_value)
810 #define PROC_FIELDS_TO_FILEPTR_dBamp(type, name, def_value) \
811 if (show_inherited || l->has_##name) \
812 g_string_append_printf(outstr, " %s=%s", #name, g_ascii_dtostr(floatbuf, floatbufsize, l->name));
813 #define PROC_FIELDS_TO_FILEPTR_enum(enumtype, name, def_value) \
814 if ((show_inherited || l->has_##name) && (tmpstr = enumtype##_to_string(l->name)) != NULL) \
815 g_string_append_printf(outstr, " %s=%s", #name, tmpstr);
817 #define ENV_PARAM_OUTPUT(param, index, def_value, env, envfield, envname) \
818 if (show_inherited || l->has_##envfield.param) \
819 g_string_append_printf(outstr, " " #envname "_" #param "=%s", g_ascii_dtostr(floatbuf, floatbufsize, env.param));
821 #define PROC_FIELDS_TO_FILEPTR_dahdsr(name, parname, index) \
822 DAHDSR_FIELDS(ENV_PARAM_OUTPUT, l->name, name, parname)
823 #define PROC_FIELDS_TO_FILEPTR_lfo(name, parname, index) \
824 LFO_FIELDS(ENV_PARAM_OUTPUT, l->name, name, parname)
825 #define PROC_FIELDS_TO_FILEPTR_ccrange(name) \
826 if (l->has_##name##locc) \
827 g_string_append_printf(outstr, " " #name "locc%d=%d", l->name##cc_number, l->name##locc); \
828 if (l->has_##name##hicc) \
829 g_string_append_printf(outstr, " " #name "hicc%d=%d", l->name##cc_number, l->name##hicc);
831 gchar *sampler_layer_to_string(struct sampler_layer *lr, gboolean show_inherited)
833 struct sampler_layer_data *l = &lr->data;
834 GString *outstr = g_string_sized_new(200);
835 const char *tmpstr;
836 char floatbuf[G_ASCII_DTOSTR_BUF_SIZE];
837 int floatbufsize = G_ASCII_DTOSTR_BUF_SIZE;
838 if ((show_inherited || l->has_waveform) && l->waveform && l->waveform->display_name)
839 g_string_append_printf(outstr, " sample=%s", l->waveform->display_name);
840 SAMPLER_FIXED_FIELDS(PROC_FIELDS_TO_FILEPTR)
842 static const char *addrandom_variants[] = { "amp", "fil", "pitch" };
843 static const char *modsrc_names[] = { "chanaft", "vel", "polyaft", "pitch", "pitcheg", "fileg", "ampeg", "pitchlfo", "fillfo", "amplfo", "" };
844 static const char *moddest_names[] = { "gain", "pitch", "cutoff", "resonance" };
845 for(GSList *nif = l->nifs; nif; nif = nif->next)
847 struct sampler_noteinitfunc *nd = nif->data;
848 if (!nd->has_value && !show_inherited)
849 continue;
850 #define PROC_ENVSTAGE_NAME(name, index, def_value) #name,
851 static const char *env_stages[] = { DAHDSR_FIELDS(PROC_ENVSTAGE_NAME) };
852 int v = nd->variant;
853 g_ascii_dtostr(floatbuf, floatbufsize, nd->param);
855 if (nd->notefunc == sampler_nif_addrandom && v >= 0 && v <= 2)
856 g_string_append_printf(outstr, " %s_random=%s", addrandom_variants[nd->variant], floatbuf);
857 else if (nd->notefunc == sampler_nif_vel2pitch)
858 g_string_append_printf(outstr, " pitch_veltrack=%s", floatbuf);
859 else if (nd->notefunc == sampler_nif_cc2delay && v >= 0 && v < 120)
860 g_string_append_printf(outstr, " delay_cc%d=%s", nd->variant, floatbuf);
861 else if (nd->notefunc == sampler_nif_vel2env && v >= 0 && (v & 15) < 6 && (v >> 4) < 3)
862 g_string_append_printf(outstr, " %seg_vel2%s=%s", addrandom_variants[nd->variant >> 4], env_stages[1 + (v & 15)], floatbuf);
864 for(GSList *mod = l->modulations; mod; mod = mod->next)
866 struct sampler_modulation *md = mod->data;
867 if (!md->has_value && !show_inherited)
868 continue;
869 g_ascii_dtostr(floatbuf, floatbufsize, md->amount);
871 if (md->src2 == smsrc_none)
873 if (md->src < 120)
875 g_string_append_printf(outstr, " %s_cc%d=%s", moddest_names[md->dest], md->src, floatbuf);
876 continue;
878 if (md->src < 120 + sizeof(modsrc_names) / sizeof(modsrc_names[0]))
880 if ((md->src == smsrc_filenv && md->dest == smdest_cutoff) ||
881 (md->src == smsrc_pitchenv && md->dest == smdest_pitch))
882 g_string_append_printf(outstr, " %s_depth=%s", modsrc_names[md->src - 120], floatbuf);
883 else
884 g_string_append_printf(outstr, " %s_%s=%s", moddest_names[md->dest], modsrc_names[md->src - 120], floatbuf);
885 continue;
888 if ((md->src == smsrc_amplfo && md->dest == smdest_gain) ||
889 (md->src == smsrc_fillfo && md->dest == smdest_cutoff) ||
890 (md->src == smsrc_pitchlfo && md->dest == smdest_pitch))
892 switch(md->src2)
894 case smsrc_chanaft:
895 case smsrc_polyaft:
896 g_string_append_printf(outstr, " %slfo_depth%s=%s", moddest_names[md->dest], modsrc_names[md->src2 - 120], floatbuf);
897 continue;
898 default:
899 if (md->src2 < 120)
901 g_string_append_printf(outstr, " %slfo_depthcc%d=%s", moddest_names[md->dest], md->src2, floatbuf);
902 continue;
904 break;
906 break;
908 if ((md->src == smsrc_ampenv && md->dest == smdest_gain) ||
909 (md->src == smsrc_filenv && md->dest == smdest_cutoff) ||
910 (md->src == smsrc_pitchenv && md->dest == smdest_pitch))
912 if (md->src2 == smsrc_vel)
914 g_string_append_printf(outstr, " %seg_vel2depth=%s", moddest_names[md->dest], floatbuf);
915 continue;
917 if (md->src2 < 120)
919 g_string_append_printf(outstr, " %s_depthcc%d=%s", modsrc_names[md->src - 120], md->src2, floatbuf);
920 continue;
923 g_string_append_printf(outstr, " genericmod_from_%d_and_%d_to_%d=%s", md->src, md->src2, md->dest, floatbuf);
926 if (lr->unknown_keys)
928 GHashTableIter hti;
929 gchar *key, *value;
930 g_hash_table_iter_init(&hti, lr->unknown_keys);
931 while(g_hash_table_iter_next(&hti, (gpointer *)&key, (gpointer *)&value))
932 g_string_append_printf(outstr, " %s=%s", key, value);
935 gchar *res = outstr->str;
936 g_string_free(outstr, FALSE);
937 return res;
940 void sampler_layer_dump(struct sampler_layer *l, FILE *f)
942 gchar *str = sampler_layer_to_string(l, FALSE);
943 fprintf(f, "%s\n", str);
946 void sampler_layer_data_close(struct sampler_layer_data *l)
948 g_slist_free_full(l->nifs, g_free);
949 g_slist_free_full(l->modulations, g_free);
950 if (l->waveform)
952 cbox_waveform_unref(l->waveform);
953 l->waveform = NULL;
957 void sampler_layer_data_destroy(struct sampler_layer_data *l)
959 sampler_layer_data_close(l);
960 free(l);
963 void sampler_layer_destroyfunc(struct cbox_objhdr *objhdr)
965 struct sampler_layer *l = CBOX_H2O(objhdr);
966 struct sampler_program *prg = l->parent_program;
967 assert(g_hash_table_size(l->child_layers) == 0);
969 if (l->parent_group)
971 g_hash_table_remove(l->parent_group->child_layers, l);
972 if (prg && prg->rll)
974 sampler_program_delete_layer(prg, l);
975 sampler_program_update_layers(l->parent_program);
977 l->parent_group = NULL;
979 sampler_layer_data_close(&l->data);
980 if (l->runtime)
981 sampler_layer_data_destroy(l->runtime);
982 if (l->unknown_keys)
983 g_hash_table_destroy(l->unknown_keys);
984 if (l->child_layers)
985 g_hash_table_destroy(l->child_layers);
987 free(l);
990 //////////////////////////////////////////////////////////////////////////
992 struct sampler_layer_update_cmd
994 struct sampler_module *module;
995 struct sampler_layer *layer;
996 struct sampler_layer_data *new_data;
997 struct sampler_layer_data *old_data;
1000 static int sampler_layer_update_cmd_prepare(void *data)
1002 struct sampler_layer_update_cmd *cmd = data;
1003 cmd->old_data = cmd->layer->runtime;
1004 cmd->new_data = calloc(1, sizeof(struct sampler_layer_data));
1006 sampler_layer_data_clone(cmd->new_data, &cmd->layer->data, TRUE);
1007 sampler_layer_data_finalize(cmd->new_data, cmd->layer->parent_group ? &cmd->layer->parent_group->data : NULL, cmd->module);
1008 if (cmd->layer->runtime == NULL)
1010 // initial update of the layer, so none of the voices need updating yet
1011 // because the layer hasn't been allocated to any voice
1012 cmd->layer->runtime = cmd->new_data;
1013 return 1;
1015 return 0;
1018 static int sampler_layer_update_cmd_execute(void *data)
1020 struct sampler_layer_update_cmd *cmd = data;
1022 for (int i = 0; i < 16; i++)
1024 FOREACH_VOICE(cmd->module->channels[i].voices_running, v)
1026 if (v->layer == cmd->old_data)
1027 v->layer = cmd->new_data;
1030 cmd->layer->runtime = cmd->new_data;
1031 return 10;
1034 static void sampler_layer_update_cmd_cleanup(void *data)
1036 struct sampler_layer_update_cmd *cmd = data;
1038 sampler_layer_data_destroy(cmd->old_data);
1041 void sampler_layer_update(struct sampler_layer *l)
1043 // if changing a group, update all child regions instead
1044 if (g_hash_table_size(l->child_layers))
1046 GHashTableIter iter;
1047 g_hash_table_iter_init(&iter, l->child_layers);
1048 gpointer key, value;
1049 while(g_hash_table_iter_next(&iter, &key, &value))
1051 sampler_layer_data_finalize(&((struct sampler_layer *)key)->data, &l->data, l->module);
1052 sampler_layer_update((struct sampler_layer *)key);
1054 return;
1056 static struct cbox_rt_cmd_definition rtcmd = {
1057 .prepare = sampler_layer_update_cmd_prepare,
1058 .execute = sampler_layer_update_cmd_execute,
1059 .cleanup = sampler_layer_update_cmd_cleanup,
1062 struct sampler_layer_update_cmd lcmd;
1063 lcmd.module = l->module;
1064 lcmd.layer = l;
1065 lcmd.new_data = NULL;
1066 lcmd.old_data = NULL;
1068 // In order to be able to use the async call, it would be necessary to
1069 // identify old data by layer pointer, not layer data pointer. For now,
1070 // it might be good enough to just use sync calls for this.
1071 cbox_rt_execute_cmd_sync(l->module->module.rt, &rtcmd, &lcmd);