Fix loading samples inherited from group level.
[calfbox.git] / sampler_layer.c
blob328ed6f869f0ce024bca0940b087022d41d1b8b6
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 // XXXKF needs a string argument perhaps
144 if (layer->parent_group)
146 g_set_error(error, CBOX_MODULE_ERROR, CBOX_MODULE_ERROR_FAILED, "Cannot create a region within a region");
147 return FALSE;
149 struct sampler_layer *l = sampler_layer_new(layer->module, layer->parent_program, layer);
150 sampler_layer_data_finalize(&l->data, l->parent_group ? &l->parent_group->data : NULL, layer->parent_program);
151 sampler_layer_reset_switches(l, l->module);
152 sampler_layer_update(l);
154 sampler_program_add_layer(layer->parent_program, l);
155 sampler_program_update_layers(layer->parent_program);
157 return cbox_execute_on(fb, NULL, "/uuid", "o", error, l);
159 if (!strcmp(cmd->command, "/get_children") && !strcmp(cmd->arg_types, ""))
161 if (!cbox_check_fb_channel(fb, cmd->command, error))
162 return FALSE;
163 GHashTableIter iter;
164 g_hash_table_iter_init(&iter, layer->child_layers);
165 gpointer key, value;
166 while(g_hash_table_iter_next(&iter, &key, &value))
168 if (!cbox_execute_on(fb, NULL, "/region", "o", error, key))
169 return FALSE;
171 return TRUE;
173 // otherwise, treat just like an command on normal (non-aux) output
174 return cbox_object_default_process_cmd(ct, fb, cmd, error);
179 #define PROC_FIELDS_INITIALISER(type, name, def_value) \
180 ld->name = def_value; \
181 ld->has_##name = 0;
182 #define PROC_FIELDS_INITIALISER_string(name) \
183 ld->name = NULL; \
184 ld->name##_changed = FALSE; \
185 ld->has_##name = 0;
186 #define PROC_FIELDS_INITIALISER_enum(type, name, def_value) \
187 PROC_FIELDS_INITIALISER(type, name, def_value)
188 #define PROC_FIELDS_INITIALISER_dBamp(type, name, def_value) \
189 ld->name = def_value; \
190 ld->name##_linearized = -1; \
191 ld->has_##name = 0;
192 #define PROC_FIELDS_INITIALISER_dahdsr(name, parname, index) \
193 DAHDSR_FIELDS(PROC_SUBSTRUCT_RESET_FIELD, name, ld); \
194 DAHDSR_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, ld)
195 #define PROC_FIELDS_INITIALISER_lfo(name, parname, index) \
196 LFO_FIELDS(PROC_SUBSTRUCT_RESET_FIELD, name, ld); \
197 LFO_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, ld)
198 #define PROC_FIELDS_INITIALISER_ccrange(name) \
199 ld->name##locc = 0; \
200 ld->name##hicc = 127; \
201 ld->name##cc_number = 0; \
202 ld->has_##name##locc = 0; \
203 ld->has_##name##hicc = 0;
205 CBOX_CLASS_DEFINITION_ROOT(sampler_layer)
207 struct sampler_layer *sampler_layer_new(struct sampler_module *m, struct sampler_program *parent_program, struct sampler_layer *parent_group)
209 struct sampler_layer *l = calloc(1, sizeof(struct sampler_layer));
210 struct cbox_document *doc = CBOX_GET_DOCUMENT(parent_program);
211 memset(l, 0, sizeof(struct sampler_layer));
212 CBOX_OBJECT_HEADER_INIT(l, sampler_layer, doc);
213 cbox_command_target_init(&l->cmd_target, sampler_layer_process_cmd, l);
215 l->module = m;
216 l->child_layers = g_hash_table_new(NULL, NULL);
217 if (parent_group)
219 sampler_layer_data_clone(&l->data, &parent_group->data, FALSE);
220 l->parent_program = parent_program;
221 l->parent_group = parent_group;
222 g_hash_table_add(parent_group->child_layers, l);
223 l->runtime = NULL;
224 CBOX_OBJECT_REGISTER(l);
225 return l;
227 l->parent_program = parent_program;
229 struct sampler_layer_data *ld = &l->data;
230 SAMPLER_FIXED_FIELDS(PROC_FIELDS_INITIALISER)
232 ld->eff_waveform = NULL;
233 ld->eff_freq = 44100;
234 ld->velcurve[0] = 0;
235 ld->velcurve[127] = 1;
236 for (int i = 1; i < 127; i++)
237 ld->velcurve[i] = -1;
238 ld->modulations = NULL;
239 ld->nifs = NULL;
240 ld->on_locc = 0;
241 ld->on_hicc = 127;
242 ld->on_cc_number = -1;
244 ld->eff_use_keyswitch = 0;
245 l->last_key = -1;
246 if (!parent_group)
248 sampler_layer_set_modulation1(l, 74, smdest_cutoff, 9600, 2);
249 sampler_layer_set_modulation1(l, 71, smdest_resonance, 12, 2);
250 sampler_layer_set_modulation(l, smsrc_pitchlfo, 1, smdest_pitch, 100, 0);
252 l->runtime = NULL;
253 l->unknown_keys = NULL;
254 CBOX_OBJECT_REGISTER(l);
255 return l;
258 #define PROC_FIELDS_CLONE(type, name, def_value) \
259 dst->name = src->name; \
260 dst->has_##name = copy_hasattr ? src->has_##name : FALSE;
261 #define PROC_FIELDS_CLONE_string(name) \
262 dst->name = src->name ? g_strdup(src->name) : NULL; \
263 dst->name##_changed = src->name##_changed; \
264 dst->has_##name = copy_hasattr ? src->has_##name : FALSE;
265 #define PROC_FIELDS_CLONE_dBamp PROC_FIELDS_CLONE
266 #define PROC_FIELDS_CLONE_enum PROC_FIELDS_CLONE
267 #define PROC_FIELDS_CLONE_dahdsr(name, parname, index) \
268 DAHDSR_FIELDS(PROC_SUBSTRUCT_CLONE, name, dst, src) \
269 if (!copy_hasattr) \
270 DAHDSR_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, dst)
271 #define PROC_FIELDS_CLONE_lfo(name, parname, index) \
272 LFO_FIELDS(PROC_SUBSTRUCT_CLONE, name, dst, src) \
273 if (!copy_hasattr) \
274 LFO_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, dst)
275 #define PROC_FIELDS_CLONE_ccrange(name) \
276 dst->name##locc = src->name##locc; \
277 dst->name##hicc = src->name##hicc; \
278 dst->name##cc_number = src->name##cc_number; \
279 dst->has_##name##locc = copy_hasattr ? src->has_##name##locc : FALSE; \
280 dst->has_##name##hicc = copy_hasattr ? src->has_##name##hicc : FALSE;
282 void sampler_layer_data_clone(struct sampler_layer_data *dst, const struct sampler_layer_data *src, gboolean copy_hasattr)
284 SAMPLER_FIXED_FIELDS(PROC_FIELDS_CLONE)
285 memcpy(dst->velcurve, src->velcurve, 128 * sizeof(float));
286 dst->modulations = g_slist_copy(src->modulations);
287 for(GSList *mod = dst->modulations; mod; mod = mod->next)
289 struct sampler_modulation *srcm = mod->data;
290 struct sampler_modulation *dstm = g_malloc(sizeof(struct sampler_modulation));
291 memcpy(dstm, srcm, sizeof(struct sampler_modulation));
292 dstm->has_value = copy_hasattr ? srcm->has_value : FALSE;
293 mod->data = dstm;
295 dst->nifs = g_slist_copy(src->nifs);
296 for(GSList *nif = dst->nifs; nif; nif = nif->next)
298 struct sampler_noteinitfunc *dstn = g_malloc(sizeof(struct sampler_noteinitfunc));
299 struct sampler_noteinitfunc *srcn = nif->data;
300 memcpy(dstn, srcn, sizeof(struct sampler_noteinitfunc));
301 dstn->has_value = copy_hasattr ? srcn->has_value : FALSE;
302 nif->data = dstn;
304 dst->eff_waveform = src->eff_waveform;
305 if (dst->eff_waveform)
306 cbox_waveform_ref(dst->eff_waveform);
309 #define PROC_FIELDS_CLONEPARENT(type, name, def_value) \
310 if (!l->has_##name) \
311 l->name = parent ? parent->name : def_value;
312 #define PROC_FIELDS_CLONEPARENT_string(name) \
313 if (!l->has_##name && (!l->name || !parent->name || strcmp(l->name, parent->name))) { \
314 g_free(l->name); \
315 l->name = parent && parent->name ? g_strdup(parent->name) : NULL; \
316 l->name##_changed = parent && parent->name##_changed; \
318 #define PROC_FIELDS_CLONEPARENT_dBamp PROC_FIELDS_CLONEPARENT
319 #define PROC_FIELDS_CLONEPARENT_enum PROC_FIELDS_CLONEPARENT
320 #define PROC_FIELDS_CLONEPARENT_dahdsr(name, parname, index) \
321 DAHDSR_FIELDS(PROC_SUBSTRUCT_CLONEPARENT, name, l)
322 #define PROC_FIELDS_CLONEPARENT_lfo(name, parname, index) \
323 LFO_FIELDS(PROC_SUBSTRUCT_CLONEPARENT, name, l)
324 #define PROC_FIELDS_CLONEPARENT_ccrange(name) \
325 if (!l->has_##name##locc) \
326 l->name##locc = parent ? parent->name##locc : 0; \
327 if (!l->has_##name##hicc) \
328 l->name##hicc = parent ? parent->name##hicc : 127; \
329 if (!l->has_##name##locc && !l->has_##name##hicc) \
330 l->name##cc_number = parent ? parent->name##cc_number : -1;
332 static void sampler_layer_data_getdefaults(struct sampler_layer_data *l, struct sampler_layer_data *parent)
334 SAMPLER_FIXED_FIELDS(PROC_FIELDS_CLONEPARENT)
335 // XXXKF: add handling for velcurve
336 if (parent)
338 // set NIFs used by parent
339 for(GSList *mod = parent->nifs; mod; mod = mod->next)
341 struct sampler_noteinitfunc *nif = mod->data;
342 sampler_layer_data_add_nif(l, nif->notefunc, nif->variant, nif->param, TRUE);
344 // set modulations used by parent
345 for(GSList *mod = parent->modulations; mod; mod = mod->next)
347 struct sampler_modulation *srcm = mod->data;
348 sampler_layer_data_set_modulation(l, srcm->src, srcm->src2, srcm->dest, srcm->amount, srcm->flags, TRUE);
353 #define PROC_FIELDS_FINALISER(type, name, def_value)
354 #define PROC_FIELDS_FINALISER_string(name)
355 #define PROC_FIELDS_FINALISER_enum(type, name, def_value)
356 #define PROC_FIELDS_FINALISER_dBamp(type, name, def_value) \
357 l->name##_linearized = dB2gain(l->name);
358 #define PROC_FIELDS_FINALISER_dahdsr(name, parname, index) \
359 cbox_envelope_init_dahdsr(&l->name##_shape, &l->name, m->module.srate / CBOX_BLOCK_SIZE, 100.f, &l->name##_shape == &l->amp_env_shape);
360 #define PROC_FIELDS_FINALISER_lfo(name, parname, index) /* no finaliser required */
361 #define PROC_FIELDS_FINALISER_ccrange(name) /* no finaliser required */
363 void sampler_layer_data_finalize(struct sampler_layer_data *l, struct sampler_layer_data *parent, struct sampler_program *p)
365 struct sampler_module *m = p->module;
366 SAMPLER_FIXED_FIELDS(PROC_FIELDS_FINALISER)
368 sampler_layer_data_getdefaults(l, parent);
370 // Handle change of sample in the prent group without override on region level
371 if (parent && (l->sample_changed || parent->sample_changed))
373 struct cbox_waveform *oldwf = l->eff_waveform;
374 if (l->sample && *l->sample)
376 GError *error;
377 l->eff_waveform = cbox_wavebank_get_waveform(p->name, p->sample_dir, l->sample, &error);
378 if (!l->eff_waveform)
380 g_warning("Cannot load waveform %s: %s", l->sample, error ? error->message : "unknown error");
381 g_error_free(error);
384 else
385 l->eff_waveform = NULL;
386 if (oldwf)
387 cbox_waveform_unref(oldwf);
388 l->sample_changed = FALSE;
391 l->eff_freq = (l->eff_waveform && l->eff_waveform->info.samplerate) ? l->eff_waveform->info.samplerate : 44100;
392 // XXXKF should have a distinction between 'configured' and 'effective' loop start/end
393 if (l->loop_mode == slm_unknown)
395 if (l->eff_waveform && l->eff_waveform->has_loop)
396 l->loop_mode = slm_loop_continuous;
397 else
398 l->loop_mode = l->loop_end == 0 ? slm_no_loop : slm_loop_continuous;
401 if (l->loop_mode == slm_one_shot || l->loop_mode == slm_no_loop || l->loop_mode == slm_one_shot_chokeable)
402 l->loop_start = -1;
404 if ((l->loop_mode == slm_loop_continuous || l->loop_mode == slm_loop_sustain) && l->loop_start == -1)
405 l->loop_start = 0;
406 if ((l->loop_mode == slm_loop_continuous || l->loop_mode == slm_loop_sustain) && l->loop_start == 0 && l->eff_waveform && l->eff_waveform->has_loop)
407 l->loop_start = l->eff_waveform->loop_start;
408 if (l->loop_end == 0 && l->eff_waveform != NULL && l->eff_waveform->has_loop)
409 l->loop_end = l->eff_waveform->loop_end;
411 if (l->off_mode == som_unknown)
412 l->off_mode = l->off_by != 0 ? som_fast : som_normal;
414 // if no amp_velcurve_nnn setting, default to quadratic
415 if (l->velcurve_quadratic == -1)
416 l->velcurve_quadratic = 1;
418 if (l->key >= 0 && l->key <= 127)
419 l->lokey = l->hikey = l->pitch_keycenter = l->key;
421 // interpolate missing points in velcurve
422 int start = 0;
423 for (int i = 1; i < 128; i++)
425 if (l->velcurve[i] == -1)
426 continue;
427 float sv = l->velcurve[start];
428 float ev = l->velcurve[i];
429 if (l->velcurve_quadratic)
431 for (int j = start; j <= i; j++)
432 l->eff_velcurve[j] = sv + (ev - sv) * (j - start) * (j - start) / ((i - start) * (i - start));
434 else
436 for (int j = start; j <= i; j++)
437 l->eff_velcurve[j] = sv + (ev - sv) * (j - start) / (i - start);
439 start = i;
441 l->eff_use_keyswitch = ((l->sw_down != -1) || (l->sw_up != -1) || (l->sw_last != -1) || (l->sw_previous != -1));
444 void sampler_layer_reset_switches(struct sampler_layer *l, struct sampler_module *m)
446 l->last_key = l->data.sw_lokey;
447 l->current_seq_position = l->data.seq_position;
450 struct layer_foreach_struct
452 struct sampler_layer *layer;
453 const char *cfg_section;
456 static void layer_foreach_func(void *user_data, const char *key)
458 if (!strcmp(key, "file"))
459 key = "sample";
460 // import is handled in sampler_load_layer_overrides
461 if (!strcmp(key, "import"))
462 return;
463 struct layer_foreach_struct *lfs = user_data;
464 const char *value = cbox_config_get_string(lfs->cfg_section, key);
465 GError *error = NULL;
466 if (!sampler_layer_apply_param(lfs->layer, key, value, &error))
468 if (error)
469 g_warning("Error '%s', context: %s in section %s", error->message, key, lfs->cfg_section);
470 else
471 g_warning("Unknown sample layer parameter: %s in section %s", key, lfs->cfg_section);
475 void sampler_layer_load_overrides(struct sampler_layer *l, const char *cfg_section)
477 char *imp = cbox_config_get_string(cfg_section, "import");
478 if (imp)
479 sampler_layer_load_overrides(l, imp);
481 struct layer_foreach_struct lfs = {
482 .layer = l,
483 .cfg_section = cfg_section
485 cbox_config_foreach_key(layer_foreach_func, cfg_section, &lfs);
488 struct sampler_layer *sampler_layer_new_from_section(struct sampler_module *m, struct sampler_program *parent_program, const char *cfg_section)
490 struct sampler_layer *l = sampler_layer_new(m, parent_program, NULL);
491 sampler_layer_load_overrides(l, cfg_section);
492 sampler_layer_data_finalize(&l->data, l->parent_group ? &l->parent_group->data : NULL, parent_program);
493 sampler_layer_reset_switches(l, m);
494 return l;
497 static int sfz_note_from_string(const char *note)
499 static const int semis[] = {9, 11, 0, 2, 4, 5, 7};
500 int pos;
501 int nn = tolower(note[0]);
502 int nv;
503 if (nn >= '0' && nn <= '9')
504 return atoi(note);
505 if (nn < 'a' && nn > 'g')
506 return -1;
507 nv = semis[nn - 'a'];
509 for (pos = 1; tolower(note[pos]) == 'b' || note[pos] == '#'; pos++)
510 nv += (note[pos] != '#') ? -1 : +1;
512 if ((note[pos] == '-' && note[pos + 1] == '1' && note[pos + 2] == '\0') || (note[pos] >= '0' && note[pos] <= '9' && note[pos + 1] == '\0'))
514 return nv + 12 * (1 + atoi(note + pos));
517 return -1;
520 static double atof_C(const char *value)
522 return g_ascii_strtod(value, NULL);
525 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)
527 static const enum sampler_modsrc srcs[] = { smsrc_ampenv, smsrc_filenv, smsrc_pitchenv };
528 static const enum sampler_moddest dests[] = { smdest_gain, smdest_cutoff, smdest_pitch };
529 enum sampler_modsrc src = srcs[env_type];
530 enum sampler_moddest dest = dests[env_type];
531 float fvalue = atof_C(value);
533 #define PROC_SET_ENV_FIELD(name, index, def_value) \
534 if (!strcmp(key, #name)) {\
535 env->name = fvalue; \
536 has_fields->name = 1; \
537 return TRUE; \
539 DAHDSR_FIELDS(PROC_SET_ENV_FIELD)
540 if (!strcmp(key, "depth"))
541 sampler_layer_set_modulation1(layer, src, dest, atof_C(value), 0);
542 else if (!strcmp(key, "vel2delay"))
543 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 0, fvalue);
544 else if (!strcmp(key, "vel2attack"))
545 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 1, fvalue);
546 else if (!strcmp(key, "vel2hold"))
547 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 2, fvalue);
548 else if (!strcmp(key, "vel2decay"))
549 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 3, fvalue);
550 else if (!strcmp(key, "vel2sustain"))
551 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 4, fvalue);
552 else if (!strcmp(key, "vel2release"))
553 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 5, fvalue);
554 else if (!strcmp(key, "vel2depth"))
555 sampler_layer_set_modulation(layer, src, smsrc_vel, dest, atof_C(value), 0);
556 else if (!strncmp(key, "depthcc", 7))
558 int cc = atoi(key + 7);
559 if (cc > 0 && cc < 120)
560 sampler_layer_set_modulation(layer, src, cc, dest, fvalue, 0);
561 else
562 return FALSE;
564 else
565 return FALSE;
566 return TRUE;
569 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)
571 static const enum sampler_modsrc srcs[] = { smsrc_amplfo, smsrc_fillfo, smsrc_pitchlfo };
572 static const enum sampler_moddest dests[] = { smdest_gain, smdest_cutoff, smdest_pitch };
573 enum sampler_modsrc src = srcs[lfo_type];
574 enum sampler_moddest dest = dests[lfo_type];
576 #define PROC_SET_LFO_FIELD(name, index, def_value) \
577 if (!strcmp(key, #name)) {\
578 params->name = fvalue; \
579 has_fields->name = 1; \
580 return TRUE; \
582 float fvalue = atof_C(value);
583 LFO_FIELDS(PROC_SET_LFO_FIELD)
584 if (!strcmp(key, "depth"))
585 sampler_layer_set_modulation1(layer, src, dest, fvalue, 0);
586 else if (!strcmp(key, "depthchanaft"))
587 sampler_layer_set_modulation(layer, src, smsrc_chanaft, dest, fvalue, 0);
588 else if (!strcmp(key, "depthpolyaft"))
589 sampler_layer_set_modulation(layer, src, smsrc_polyaft, dest, fvalue, 0);
590 else if (!strncmp(key, "depthcc", 7))
592 int cc = atoi(key + 7);
593 if (cc > 0 && cc < 120)
594 sampler_layer_set_modulation(layer, src, cc, dest, fvalue, 0);
595 else
596 return FALSE;
598 else
599 return FALSE;
600 return TRUE;
603 #define PARSE_PARAM_midi_note_t(field, strname, valuestr) \
604 return ((l->data.field = sfz_note_from_string(value)), (l->data.has_##field = 1));
605 #define PARSE_PARAM_int(field, strname, valuestr) \
606 return ((l->data.field = atoi(value)), (l->data.has_##field = 1));
607 #define PARSE_PARAM_uint32_t(field, strname, valuestr) \
608 return ((l->data.field = (uint32_t)strtoul(value, NULL, 10)), (l->data.has_##field = 1));
609 #define PARSE_PARAM_float(field, strname, valuestr) \
610 return ((l->data.field = atof_C(value)), (l->data.has_##field = 1));
612 #define PROC_APPLY_PARAM(type, name, def_value) \
613 if (!strcmp(key, #name)) { \
614 PARSE_PARAM_##type(name, #name, value) \
616 #define PROC_APPLY_PARAM_string(name) \
617 if (!strcmp(key, #name)) { \
618 if (l->data.name && value && !strcmp(l->data.name, value)) \
619 return (l->data.has_##name = 1); \
620 g_free(l->data.name); \
621 return ((l->data.name = g_strdup(value)), (l->data.name##_changed = 1), (l->data.has_##name = 1)); \
623 #define PROC_APPLY_PARAM_dBamp(type, name, def_value) \
624 if (!strcmp(key, #name)) { \
625 return ((l->data.name = atof_C(value)), (l->data.has_##name = 1)); \
627 #define PROC_APPLY_PARAM_enum(enumtype, name, def_value) \
628 if (!strcmp(key, #name)) { \
629 if (!enumtype##_from_string(value, &l->data.name)) { \
630 g_set_error(error, CBOX_MODULE_ERROR, CBOX_MODULE_ERROR_FAILED, "Value %s is not a correct value for %s", value, #name); \
631 return FALSE; \
633 l->data.has_##name = 1; \
634 return TRUE; \
636 // LFO and envelope need special handling now
637 #define PROC_APPLY_PARAM_dahdsr(name, parname, index) \
638 if (!strncmp(key, #parname "_", sizeof(#parname))) \
639 return parse_envelope_param(l, &l->data.name, &l->data.has_##name, index, key + sizeof(#parname), value);
640 #define PROC_APPLY_PARAM_lfo(name, parname, index) \
641 if (!strncmp(key, #parname "_", sizeof(#parname))) \
642 return parse_lfo_param(l, &l->data.name, &l->data.has_##name, index, key + sizeof(#parname), value);
643 #define PROC_APPLY_PARAM_ccrange(name) /* handled separately in apply_param */
645 static void sampler_layer_apply_unknown(struct sampler_layer *l, const char *key, const char *value)
647 if (!l->unknown_keys)
648 l->unknown_keys = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
650 g_hash_table_insert(l->unknown_keys, g_strdup(key), g_strdup(value));
653 gboolean sampler_layer_apply_param(struct sampler_layer *l, const char *key, const char *value, GError **error)
655 try_now:
656 // XXXKF: this is seriously stupid code, this should use a hash table for
657 // fixed strings, or something else that doesn't explode O(N**2) with
658 // number of attributes. But premature optimization is a root of all evil.
660 SAMPLER_FIXED_FIELDS(PROC_APPLY_PARAM)
662 // XXXKF: to make things worse, some attributes have names different from
663 // C field names, or have multiple names, or don't map 1:1 to internal model
665 if (!strcmp(key, "lolev"))
666 l->data.lovel = atoi(value), l->data.has_lovel = 1;
667 else if (!strcmp(key, "hilev"))
668 l->data.hivel = atoi(value), l->data.has_hivel = 1;
669 else if (!strcmp(key, "benddown"))
670 l->data.bend_down = atoi(value), l->data.has_bend_down = 1;
671 else if (!strcmp(key, "bendup"))
672 l->data.bend_up = atoi(value), l->data.has_bend_up = 1;
673 else if (!strcmp(key, "loopstart"))
674 l->data.loop_start = atoi(value), l->data.has_loop_start = 1;
675 else if (!strcmp(key, "loopend"))
676 l->data.loop_end = atoi(value), l->data.has_loop_end = 1;
677 else if (!strcmp(key, "cutoff_chanaft"))
678 sampler_layer_set_modulation1(l, smsrc_chanaft, smdest_cutoff, atof_C(value), 0);
679 else if (!strcmp(key, "amp_random"))
680 sampler_layer_add_nif(l, sampler_nif_addrandom, 0, atof_C(value));
681 else if (!strcmp(key, "fil_random"))
682 sampler_layer_add_nif(l, sampler_nif_addrandom, 1, atof_C(value));
683 else if (!strcmp(key, "pitch_random"))
684 sampler_layer_add_nif(l, sampler_nif_addrandom, 2, atof_C(value));
685 else if (!strcmp(key, "pitch_veltrack"))
686 sampler_layer_add_nif(l, sampler_nif_vel2pitch, 0, atof_C(value));
687 else if (!strncmp(key, "delay_cc", 8))
689 int ccno = atoi(key + 8);
690 if (ccno > 0 && ccno < 120)
691 sampler_layer_add_nif(l, sampler_nif_cc2delay, ccno, atof_C(value));
692 else
693 goto unknown_key;
695 else if (!strncmp(key, "cutoff_cc", 9))
697 int ccno = atoi(key + 9);
698 if (ccno > 0 && ccno < 120)
699 sampler_layer_set_modulation1(l, ccno, smdest_cutoff, atof_C(value), 0);
700 else
701 goto unknown_key;
703 else if (!strncmp(key, "gain_cc", 7))
705 int ccno = atoi(key + 7);
706 if (ccno > 0 && ccno < 120)
707 sampler_layer_set_modulation1(l, ccno, smdest_gain, atof_C(value), 0);
708 else
709 goto unknown_key;
711 else if (!strncmp(key, "amp_velcurve_", 13))
713 // if not known yet, set to 0, it can always be overriden via velcurve_quadratic setting
714 if (l->data.velcurve_quadratic == -1)
715 l->data.velcurve_quadratic = 0;
716 int point = atoi(key + 13);
717 if (point >= 0 && point <= 127)
719 l->data.velcurve[point] = atof_C(value);
720 if (l->data.velcurve[point] < 0)
721 l->data.velcurve[point] = 0;
722 if (l->data.velcurve[point] > 1)
723 l->data.velcurve[point] = 1;
725 else
726 goto unknown_key;
728 else if (!strncmp(key, "on_locc", 7) || !strncmp(key, "on_hicc", 7))
730 int cc = atoi(key + 7);
731 if (cc > 0 && cc < 120)
733 if (*value)
735 l->data.on_cc_number = cc;
736 if (key[3] == 'l')
738 l->data.on_locc = atoi(value);
739 l->data.has_on_locc = TRUE;
741 else
743 l->data.on_hicc = atoi(value);
744 l->data.has_on_hicc = TRUE;
747 else
749 l->data.on_cc_number = -1;
750 l->data.has_on_locc = FALSE;
751 l->data.has_on_hicc = FALSE;
754 else
755 return FALSE;
757 else if (!strncmp(key, "locc", 4) || !strncmp(key, "hicc", 4))
759 int cc = atoi(key + 4);
760 if (cc > 0 && cc < 120)
762 if (*value)
764 l->data.cc_number = cc;
765 if (key[0] == 'l')
767 l->data.locc = atoi(value);
768 l->data.has_locc = TRUE;
770 else
772 l->data.hicc = atoi(value);
773 l->data.has_hicc = TRUE;
776 else
778 l->data.cc_number = -1;
779 l->data.has_locc = FALSE;
780 l->data.has_hicc = FALSE;
783 else
784 return FALSE;
786 else if (!strcmp(key, "loopmode"))
788 key = "loop_mode";
789 goto try_now; // yes, goto, why not?
791 else if (!strcmp(key, "offby"))
793 key = "off_by";
794 goto try_now;
796 else
797 goto unknown_key;
799 return TRUE;
800 unknown_key:
801 sampler_layer_apply_unknown(l, key, value);
802 g_warning("Unknown SFZ property key: '%s'", key);
803 return TRUE;
806 #define TYPE_PRINTF_uint32_t(name, def_value) \
807 if (show_inherited || l->has_##name) \
808 g_string_append_printf(outstr, " %s=%u", #name, (unsigned)(l->name));
809 #define TYPE_PRINTF_int(name, def_value) \
810 if (show_inherited || l->has_##name) \
811 g_string_append_printf(outstr, " %s=%d", #name, (int)(l->name));
812 #define TYPE_PRINTF_midi_note_t(name, def_value) \
813 if (show_inherited || l->has_##name) { \
814 int val = l->name; \
815 if (val == -1) \
816 g_string_append_printf(outstr, " %s=-1", #name); \
817 else \
818 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)); \
819 } else {}
820 #define TYPE_PRINTF_float(name, def_value) \
821 if (show_inherited || l->has_##name) \
822 g_string_append_printf(outstr, " %s=%s", #name, g_ascii_dtostr(floatbuf, floatbufsize, l->name));
824 #define PROC_FIELDS_TO_FILEPTR(type, name, def_value) \
825 TYPE_PRINTF_##type(name, def_value)
826 #define PROC_FIELDS_TO_FILEPTR_string(name) \
827 if (show_inherited || l->has_##name) \
828 g_string_append_printf(outstr, " %s=%s", #name, l->name ? l->name : "");
829 #define PROC_FIELDS_TO_FILEPTR_dBamp(type, name, def_value) \
830 if (show_inherited || l->has_##name) \
831 g_string_append_printf(outstr, " %s=%s", #name, g_ascii_dtostr(floatbuf, floatbufsize, l->name));
832 #define PROC_FIELDS_TO_FILEPTR_enum(enumtype, name, def_value) \
833 if ((show_inherited || l->has_##name) && (tmpstr = enumtype##_to_string(l->name)) != NULL) \
834 g_string_append_printf(outstr, " %s=%s", #name, tmpstr);
836 #define ENV_PARAM_OUTPUT(param, index, def_value, env, envfield, envname) \
837 if (show_inherited || l->has_##envfield.param) \
838 g_string_append_printf(outstr, " " #envname "_" #param "=%s", g_ascii_dtostr(floatbuf, floatbufsize, env.param));
840 #define PROC_FIELDS_TO_FILEPTR_dahdsr(name, parname, index) \
841 DAHDSR_FIELDS(ENV_PARAM_OUTPUT, l->name, name, parname)
842 #define PROC_FIELDS_TO_FILEPTR_lfo(name, parname, index) \
843 LFO_FIELDS(ENV_PARAM_OUTPUT, l->name, name, parname)
844 #define PROC_FIELDS_TO_FILEPTR_ccrange(name) \
845 if (l->has_##name##locc) \
846 g_string_append_printf(outstr, " " #name "locc%d=%d", l->name##cc_number, l->name##locc); \
847 if (l->has_##name##hicc) \
848 g_string_append_printf(outstr, " " #name "hicc%d=%d", l->name##cc_number, l->name##hicc);
850 gchar *sampler_layer_to_string(struct sampler_layer *lr, gboolean show_inherited)
852 struct sampler_layer_data *l = &lr->data;
853 GString *outstr = g_string_sized_new(200);
854 const char *tmpstr;
855 char floatbuf[G_ASCII_DTOSTR_BUF_SIZE];
856 int floatbufsize = G_ASCII_DTOSTR_BUF_SIZE;
857 SAMPLER_FIXED_FIELDS(PROC_FIELDS_TO_FILEPTR)
859 static const char *addrandom_variants[] = { "amp", "fil", "pitch" };
860 static const char *modsrc_names[] = { "chanaft", "vel", "polyaft", "pitch", "pitcheg", "fileg", "ampeg", "pitchlfo", "fillfo", "amplfo", "" };
861 static const char *moddest_names[] = { "gain", "pitch", "cutoff", "resonance" };
862 for(GSList *nif = l->nifs; nif; nif = nif->next)
864 struct sampler_noteinitfunc *nd = nif->data;
865 if (!nd->has_value && !show_inherited)
866 continue;
867 #define PROC_ENVSTAGE_NAME(name, index, def_value) #name,
868 static const char *env_stages[] = { DAHDSR_FIELDS(PROC_ENVSTAGE_NAME) };
869 int v = nd->variant;
870 g_ascii_dtostr(floatbuf, floatbufsize, nd->param);
872 if (nd->notefunc == sampler_nif_addrandom && v >= 0 && v <= 2)
873 g_string_append_printf(outstr, " %s_random=%s", addrandom_variants[nd->variant], floatbuf);
874 else if (nd->notefunc == sampler_nif_vel2pitch)
875 g_string_append_printf(outstr, " pitch_veltrack=%s", floatbuf);
876 else if (nd->notefunc == sampler_nif_cc2delay && v >= 0 && v < 120)
877 g_string_append_printf(outstr, " delay_cc%d=%s", nd->variant, floatbuf);
878 else if (nd->notefunc == sampler_nif_vel2env && v >= 0 && (v & 15) < 6 && (v >> 4) < 3)
879 g_string_append_printf(outstr, " %seg_vel2%s=%s", addrandom_variants[nd->variant >> 4], env_stages[1 + (v & 15)], floatbuf);
881 for(GSList *mod = l->modulations; mod; mod = mod->next)
883 struct sampler_modulation *md = mod->data;
884 if (!md->has_value && !show_inherited)
885 continue;
886 g_ascii_dtostr(floatbuf, floatbufsize, md->amount);
888 if (md->src2 == smsrc_none)
890 if (md->src < 120)
892 g_string_append_printf(outstr, " %s_cc%d=%s", moddest_names[md->dest], md->src, floatbuf);
893 continue;
895 if (md->src < 120 + sizeof(modsrc_names) / sizeof(modsrc_names[0]))
897 if ((md->src == smsrc_filenv && md->dest == smdest_cutoff) ||
898 (md->src == smsrc_pitchenv && md->dest == smdest_pitch))
899 g_string_append_printf(outstr, " %s_depth=%s", modsrc_names[md->src - 120], floatbuf);
900 else
901 g_string_append_printf(outstr, " %s_%s=%s", moddest_names[md->dest], modsrc_names[md->src - 120], floatbuf);
902 continue;
905 if ((md->src == smsrc_amplfo && md->dest == smdest_gain) ||
906 (md->src == smsrc_fillfo && md->dest == smdest_cutoff) ||
907 (md->src == smsrc_pitchlfo && md->dest == smdest_pitch))
909 switch(md->src2)
911 case smsrc_chanaft:
912 case smsrc_polyaft:
913 g_string_append_printf(outstr, " %slfo_depth%s=%s", moddest_names[md->dest], modsrc_names[md->src2 - 120], floatbuf);
914 continue;
915 default:
916 if (md->src2 < 120)
918 g_string_append_printf(outstr, " %slfo_depthcc%d=%s", moddest_names[md->dest], md->src2, floatbuf);
919 continue;
921 break;
923 break;
925 if ((md->src == smsrc_ampenv && md->dest == smdest_gain) ||
926 (md->src == smsrc_filenv && md->dest == smdest_cutoff) ||
927 (md->src == smsrc_pitchenv && md->dest == smdest_pitch))
929 if (md->src2 == smsrc_vel)
931 g_string_append_printf(outstr, " %seg_vel2depth=%s", moddest_names[md->dest], floatbuf);
932 continue;
934 if (md->src2 < 120)
936 g_string_append_printf(outstr, " %s_depthcc%d=%s", modsrc_names[md->src - 120], md->src2, floatbuf);
937 continue;
940 g_string_append_printf(outstr, " genericmod_from_%d_and_%d_to_%d=%s", md->src, md->src2, md->dest, floatbuf);
943 if (lr->unknown_keys)
945 GHashTableIter hti;
946 gchar *key, *value;
947 g_hash_table_iter_init(&hti, lr->unknown_keys);
948 while(g_hash_table_iter_next(&hti, (gpointer *)&key, (gpointer *)&value))
949 g_string_append_printf(outstr, " %s=%s", key, value);
952 gchar *res = outstr->str;
953 g_string_free(outstr, FALSE);
954 return res;
957 void sampler_layer_dump(struct sampler_layer *l, FILE *f)
959 gchar *str = sampler_layer_to_string(l, FALSE);
960 fprintf(f, "%s\n", str);
963 void sampler_layer_data_close(struct sampler_layer_data *l)
965 g_slist_free_full(l->nifs, g_free);
966 g_slist_free_full(l->modulations, g_free);
967 if (l->eff_waveform)
969 cbox_waveform_unref(l->eff_waveform);
970 l->eff_waveform = NULL;
972 g_free(l->sample);
975 void sampler_layer_data_destroy(struct sampler_layer_data *l)
977 sampler_layer_data_close(l);
978 free(l);
981 void sampler_layer_destroyfunc(struct cbox_objhdr *objhdr)
983 struct sampler_layer *l = CBOX_H2O(objhdr);
984 struct sampler_program *prg = l->parent_program;
985 assert(g_hash_table_size(l->child_layers) == 0);
987 if (l->parent_group)
989 g_hash_table_remove(l->parent_group->child_layers, l);
990 if (prg && prg->rll)
992 sampler_program_delete_layer(prg, l);
993 sampler_program_update_layers(l->parent_program);
995 l->parent_group = NULL;
997 sampler_layer_data_close(&l->data);
998 if (l->runtime)
999 sampler_layer_data_destroy(l->runtime);
1000 if (l->unknown_keys)
1001 g_hash_table_destroy(l->unknown_keys);
1002 if (l->child_layers)
1003 g_hash_table_destroy(l->child_layers);
1005 free(l);
1008 //////////////////////////////////////////////////////////////////////////
1010 struct sampler_layer_update_cmd
1012 struct sampler_module *module;
1013 struct sampler_layer *layer;
1014 struct sampler_layer_data *new_data;
1015 struct sampler_layer_data *old_data;
1018 static int sampler_layer_update_cmd_prepare(void *data)
1020 struct sampler_layer_update_cmd *cmd = data;
1021 cmd->old_data = cmd->layer->runtime;
1022 cmd->new_data = calloc(1, sizeof(struct sampler_layer_data));
1024 sampler_layer_data_clone(cmd->new_data, &cmd->layer->data, TRUE);
1025 sampler_layer_data_finalize(cmd->new_data, cmd->layer->parent_group ? &cmd->layer->parent_group->data : NULL, cmd->layer->parent_program);
1026 if (cmd->layer->runtime == NULL)
1028 // initial update of the layer, so none of the voices need updating yet
1029 // because the layer hasn't been allocated to any voice
1030 cmd->layer->runtime = cmd->new_data;
1031 return 1;
1033 return 0;
1036 static int sampler_layer_update_cmd_execute(void *data)
1038 struct sampler_layer_update_cmd *cmd = data;
1040 for (int i = 0; i < 16; i++)
1042 FOREACH_VOICE(cmd->module->channels[i].voices_running, v)
1044 if (v->layer == cmd->old_data)
1045 v->layer = cmd->new_data;
1048 cmd->layer->runtime = cmd->new_data;
1049 return 10;
1052 static void sampler_layer_update_cmd_cleanup(void *data)
1054 struct sampler_layer_update_cmd *cmd = data;
1056 sampler_layer_data_destroy(cmd->old_data);
1059 void sampler_layer_update(struct sampler_layer *l)
1061 // if changing a group, update all child regions instead
1062 if (g_hash_table_size(l->child_layers))
1064 GHashTableIter iter;
1065 g_hash_table_iter_init(&iter, l->child_layers);
1066 gpointer key, value;
1067 while(g_hash_table_iter_next(&iter, &key, &value))
1069 sampler_layer_data_finalize(&((struct sampler_layer *)key)->data, &l->data, l->parent_program);
1070 sampler_layer_update((struct sampler_layer *)key);
1072 return;
1074 static struct cbox_rt_cmd_definition rtcmd = {
1075 .prepare = sampler_layer_update_cmd_prepare,
1076 .execute = sampler_layer_update_cmd_execute,
1077 .cleanup = sampler_layer_update_cmd_cleanup,
1080 struct sampler_layer_update_cmd lcmd;
1081 lcmd.module = l->module;
1082 lcmd.layer = l;
1083 lcmd.new_data = NULL;
1084 lcmd.old_data = NULL;
1086 // In order to be able to use the async call, it would be necessary to
1087 // identify old data by layer pointer, not layer data pointer. For now,
1088 // it might be good enough to just use sync calls for this.
1089 cbox_rt_execute_cmd_sync(l->module->module.rt, &rtcmd, &lcmd);