Improve non-default routing for USB MIDI. Pass usb_midi_input/output from JackIO...
[calfbox.git] / sampler_layer.c
blob0e805246b02025cfa416936b6855510f3d1323ac
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>
36 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)
38 GSList *p = l->modulations;
39 while(p)
41 struct sampler_modulation *sm = p->data;
42 if (sm->src == src && sm->src2 == src2 && sm->dest == dest)
44 // do not overwrite locally set value with defaults
45 if (propagating_defaults && sm->has_value)
46 return;
47 sm->amount = amount;
48 sm->flags = flags;
49 sm->has_value = !propagating_defaults;
50 return;
52 p = g_slist_next(p);
54 struct sampler_modulation *sm = g_malloc0(sizeof(struct sampler_modulation));
55 sm->src = src;
56 sm->src2 = src2;
57 sm->dest = dest;
58 sm->amount = amount;
59 sm->flags = flags;
60 sm->has_value = !propagating_defaults;
61 l->modulations = g_slist_prepend(l->modulations, sm);
64 void sampler_layer_set_modulation1(struct sampler_layer *l, enum sampler_modsrc src, enum sampler_moddest dest, float amount, int flags)
66 sampler_layer_data_set_modulation(&l->data, src, smsrc_none, dest, amount, flags, FALSE);
69 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)
71 sampler_layer_data_set_modulation(&l->data, src, src2, dest, amount, flags, FALSE);
74 void sampler_layer_data_add_nif(struct sampler_layer_data *l, SamplerNoteInitFunc notefunc, int variant, float param, gboolean propagating_defaults)
76 GSList *p = l->nifs;
77 while(p)
79 struct sampler_noteinitfunc *nif = p->data;
80 if (nif->notefunc == notefunc && nif->variant == variant)
82 // do not overwrite locally set value with defaults
83 if (propagating_defaults && nif->has_value)
84 return;
85 nif->param = param;
86 nif->has_value = !propagating_defaults;
87 return;
89 p = g_slist_next(p);
91 struct sampler_noteinitfunc *nif = malloc(sizeof(struct sampler_noteinitfunc));
92 nif->notefunc = notefunc;
93 nif->variant = variant;
94 nif->param = param;
95 nif->has_value = !propagating_defaults;
96 l->nifs = g_slist_prepend(l->nifs, nif);
99 void sampler_layer_add_nif(struct sampler_layer *l, SamplerNoteInitFunc notefunc, int variant, float param)
101 sampler_layer_data_add_nif(&l->data, notefunc, variant, param, FALSE);
104 static gboolean sampler_layer_process_cmd(struct cbox_command_target *ct, struct cbox_command_target *fb, struct cbox_osc_command *cmd, GError **error)
106 struct sampler_layer *layer = ct->user_data;
107 if (!strcmp(cmd->command, "/status") && !strcmp(cmd->arg_types, ""))
109 if (!cbox_check_fb_channel(fb, cmd->command, error))
110 return FALSE;
112 if (!((!layer->parent_program || cbox_execute_on(fb, NULL, "/parent_program", "o", error, layer->parent_program)) &&
113 (!layer->parent_group || cbox_execute_on(fb, NULL, "/parent_group", "o", error, layer->parent_group)) &&
114 CBOX_OBJECT_DEFAULT_STATUS(layer, fb, error)))
115 return FALSE;
116 return TRUE;
118 if ((!strcmp(cmd->command, "/as_string") || !strcmp(cmd->command, "/as_string_full")) && !strcmp(cmd->arg_types, ""))
120 if (!cbox_check_fb_channel(fb, cmd->command, error))
121 return FALSE;
122 gchar *res = sampler_layer_to_string(layer, !strcmp(cmd->command, "/as_string_full"));
123 gboolean result = cbox_execute_on(fb, NULL, "/value", "s", error, res);
124 g_free(res);
125 return result;
127 if (!strcmp(cmd->command, "/set_param") && !strcmp(cmd->arg_types, "ss"))
129 const char *key = CBOX_ARG_S(cmd, 0);
130 const char *value = CBOX_ARG_S(cmd, 1);
131 if (sampler_layer_apply_param(layer, key, value, error))
133 sampler_update_layer(layer->module, layer);
134 sampler_update_program_layers(layer->module, layer->parent_program);
135 return TRUE;
137 return FALSE;
139 if (!strcmp(cmd->command, "/new_region") && !strcmp(cmd->arg_types, ""))
141 if (layer->parent_group)
143 g_set_error(error, CBOX_MODULE_ERROR, CBOX_MODULE_ERROR_FAILED, "Cannot create a region within a region");
144 return FALSE;
146 struct sampler_layer *l = sampler_layer_new(layer->module, layer->parent_program, layer);
147 sampler_layer_data_finalize(&l->data, l->parent_group ? &l->parent_group->data : NULL, layer->module);
148 sampler_layer_reset_switches(l, l->module);
149 sampler_update_layer(l->module, l);
151 sampler_program_add_layer(layer->parent_program, l);
152 sampler_update_program_layers(layer->module, layer->parent_program);
154 return cbox_execute_on(fb, NULL, "/uuid", "o", error, l);
156 if (!strcmp(cmd->command, "/get_children") && !strcmp(cmd->arg_types, ""))
158 if (!cbox_check_fb_channel(fb, cmd->command, error))
159 return FALSE;
160 GHashTableIter iter;
161 g_hash_table_iter_init(&iter, layer->child_layers);
162 gpointer key, value;
163 while(g_hash_table_iter_next(&iter, &key, &value))
165 if (!cbox_execute_on(fb, NULL, "/region", "o", error, key))
166 return FALSE;
168 return TRUE;
170 // otherwise, treat just like an command on normal (non-aux) output
171 return cbox_object_default_process_cmd(ct, fb, cmd, error);
176 #define PROC_FIELDS_INITIALISER(type, name, def_value) \
177 ld->name = def_value; \
178 ld->has_##name = 0;
179 #define PROC_FIELDS_INITIALISER_enum(type, name, def_value) \
180 PROC_FIELDS_INITIALISER(type, name, def_value)
181 #define PROC_FIELDS_INITIALISER_dBamp(type, name, def_value) \
182 ld->name = def_value; \
183 ld->name##_linearized = -1; \
184 ld->has_##name = 0;
185 #define PROC_FIELDS_INITIALISER_dahdsr(name, parname, index) \
186 DAHDSR_FIELDS(PROC_SUBSTRUCT_RESET_FIELD, name, ld); \
187 DAHDSR_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, ld)
188 #define PROC_FIELDS_INITIALISER_lfo(name, parname, index) \
189 LFO_FIELDS(PROC_SUBSTRUCT_RESET_FIELD, name, ld); \
190 LFO_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, ld)
191 #define PROC_FIELDS_INITIALISER_ccrange(name) \
192 ld->name##locc = 0; \
193 ld->name##hicc = 127; \
194 ld->name##cc_number = 0; \
195 ld->has_##name##locc = 0; \
196 ld->has_##name##hicc = 0;
198 CBOX_CLASS_DEFINITION_ROOT(sampler_layer)
200 struct sampler_layer *sampler_layer_new(struct sampler_module *m, struct sampler_program *parent_program, struct sampler_layer *parent_group)
202 struct sampler_layer *l = malloc(sizeof(struct sampler_layer));
203 struct cbox_document *doc = CBOX_GET_DOCUMENT(parent_program);
204 memset(l, 0, sizeof(struct sampler_layer));
205 CBOX_OBJECT_HEADER_INIT(l, sampler_layer, doc);
206 cbox_command_target_init(&l->cmd_target, sampler_layer_process_cmd, l);
208 l->module = m;
209 l->child_layers = g_hash_table_new(NULL, NULL);
210 if (parent_group)
212 sampler_layer_data_clone(&l->data, &parent_group->data, FALSE);
213 l->parent_program = parent_program;
214 l->parent_group = parent_group;
215 g_hash_table_add(parent_group->child_layers, l);
216 l->runtime = NULL;
217 CBOX_OBJECT_REGISTER(l);
218 return l;
220 l->parent_program = parent_program;
221 struct sampler_layer_data *ld = &l->data;
222 ld->waveform = NULL;
223 ld->has_waveform = FALSE;
225 SAMPLER_FIXED_FIELDS(PROC_FIELDS_INITIALISER)
227 ld->eff_freq = 44100;
228 ld->velcurve[0] = 0;
229 ld->velcurve[127] = 1;
230 for (int i = 1; i < 127; i++)
231 ld->velcurve[i] = -1;
232 ld->modulations = NULL;
233 ld->nifs = NULL;
234 ld->on_locc = 0;
235 ld->on_hicc = 127;
236 ld->on_cc_number = -1;
238 ld->eff_use_keyswitch = 0;
239 l->last_key = -1;
240 if (!parent_group)
242 sampler_layer_set_modulation1(l, 74, smdest_cutoff, 9600, 2);
243 sampler_layer_set_modulation1(l, 71, smdest_resonance, 12, 2);
244 sampler_layer_set_modulation(l, smsrc_pitchlfo, 1, smdest_pitch, 100, 0);
246 l->runtime = NULL;
247 l->unknown_keys = NULL;
248 CBOX_OBJECT_REGISTER(l);
249 return l;
252 #define PROC_FIELDS_CLONE(type, name, def_value) \
253 dst->name = src->name; \
254 dst->has_##name = copy_hasattr ? src->has_##name : FALSE;
255 #define PROC_FIELDS_CLONE_dBamp PROC_FIELDS_CLONE
256 #define PROC_FIELDS_CLONE_enum PROC_FIELDS_CLONE
257 #define PROC_FIELDS_CLONE_dahdsr(name, parname, index) \
258 DAHDSR_FIELDS(PROC_SUBSTRUCT_CLONE, name, dst, src) \
259 if (!copy_hasattr) \
260 DAHDSR_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, dst)
261 #define PROC_FIELDS_CLONE_lfo(name, parname, index) \
262 LFO_FIELDS(PROC_SUBSTRUCT_CLONE, name, dst, src) \
263 if (!copy_hasattr) \
264 LFO_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, dst)
265 #define PROC_FIELDS_CLONE_ccrange(name) \
266 dst->name##locc = src->name##locc; \
267 dst->name##hicc = src->name##hicc; \
268 dst->name##cc_number = src->name##cc_number; \
269 dst->has_##name##locc = copy_hasattr ? src->has_##name##locc : FALSE; \
270 dst->has_##name##hicc = copy_hasattr ? src->has_##name##hicc : FALSE;
272 void sampler_layer_data_clone(struct sampler_layer_data *dst, const struct sampler_layer_data *src, gboolean copy_hasattr)
274 dst->waveform = src->waveform;
275 if (dst->waveform)
276 cbox_waveform_ref(dst->waveform);
277 if (copy_hasattr)
278 dst->has_waveform = src->has_waveform;
279 SAMPLER_FIXED_FIELDS(PROC_FIELDS_CLONE)
280 memcpy(dst->velcurve, src->velcurve, 128 * sizeof(float));
281 dst->modulations = g_slist_copy(src->modulations);
282 for(GSList *mod = dst->modulations; mod; mod = mod->next)
284 struct sampler_modulation *srcm = mod->data;
285 struct sampler_modulation *dstm = g_malloc(sizeof(struct sampler_modulation));
286 memcpy(dstm, srcm, sizeof(struct sampler_modulation));
287 dstm->has_value = copy_hasattr ? srcm->has_value : FALSE;
288 mod->data = dstm;
290 dst->nifs = g_slist_copy(src->nifs);
291 for(GSList *nif = dst->nifs; nif; nif = nif->next)
293 struct sampler_noteinitfunc *dstn = g_malloc(sizeof(struct sampler_noteinitfunc));
294 struct sampler_noteinitfunc *srcn = nif->data;
295 memcpy(dstn, srcn, sizeof(struct sampler_noteinitfunc));
296 dstn->has_value = copy_hasattr ? srcn->has_value : FALSE;
297 nif->data = dstn;
301 #define PROC_FIELDS_CLONEPARENT(type, name, def_value) \
302 if (!l->has_##name) \
303 l->name = parent ? parent->name : def_value;
304 #define PROC_FIELDS_CLONEPARENT_dBamp PROC_FIELDS_CLONEPARENT
305 #define PROC_FIELDS_CLONEPARENT_enum PROC_FIELDS_CLONEPARENT
306 #define PROC_FIELDS_CLONEPARENT_dahdsr(name, parname, index) \
307 DAHDSR_FIELDS(PROC_SUBSTRUCT_CLONEPARENT, name, l)
308 #define PROC_FIELDS_CLONEPARENT_lfo(name, parname, index) \
309 LFO_FIELDS(PROC_SUBSTRUCT_CLONEPARENT, name, l)
310 #define PROC_FIELDS_CLONEPARENT_ccrange(name) \
311 if (!l->has_##name##locc) \
312 l->name##locc = parent ? parent->name##locc : 0; \
313 if (!l->has_##name##hicc) \
314 l->name##hicc = parent ? parent->name##hicc : 127; \
315 if (!l->has_##name##locc && !l->has_##name##hicc) \
316 l->name##cc_number = parent ? parent->name##cc_number : -1;
318 static void sampler_layer_data_getdefaults(struct sampler_layer_data *l, struct sampler_layer_data *parent)
320 if (!l->has_waveform)
321 l->waveform = parent ? parent->waveform : NULL;
322 SAMPLER_FIXED_FIELDS(PROC_FIELDS_CLONEPARENT)
323 // XXXKF: add handling for velcurve
324 if (parent)
326 // set NIFs used by parent
327 for(GSList *mod = parent->nifs; mod; mod = mod->next)
329 struct sampler_noteinitfunc *nif = mod->data;
330 sampler_layer_data_add_nif(l, nif->notefunc, nif->variant, nif->param, TRUE);
332 // set modulations used by parent
333 for(GSList *mod = parent->modulations; mod; mod = mod->next)
335 struct sampler_modulation *srcm = mod->data;
336 sampler_layer_data_set_modulation(l, srcm->src, srcm->src2, srcm->dest, srcm->amount, srcm->flags, TRUE);
341 void sampler_layer_set_waveform(struct sampler_layer *l, struct cbox_waveform *waveform)
343 l->data.has_waveform = waveform != NULL;
344 l->data.waveform = waveform;
347 #define PROC_FIELDS_FINALISER(type, name, def_value)
348 #define PROC_FIELDS_FINALISER_enum(type, name, def_value)
349 #define PROC_FIELDS_FINALISER_dBamp(type, name, def_value) \
350 l->name##_linearized = dB2gain(l->name);
351 #define PROC_FIELDS_FINALISER_dahdsr(name, parname, index) \
352 cbox_envelope_init_dahdsr(&l->name##_shape, &l->name, m->module.srate / CBOX_BLOCK_SIZE, 100.f, &l->name##_shape == &l->amp_env_shape);
353 #define PROC_FIELDS_FINALISER_lfo(name, parname, index) /* no finaliser required */
354 #define PROC_FIELDS_FINALISER_ccrange(name) /* no finaliser required */
356 void sampler_layer_data_finalize(struct sampler_layer_data *l, struct sampler_layer_data *parent, struct sampler_module *m)
358 SAMPLER_FIXED_FIELDS(PROC_FIELDS_FINALISER)
360 sampler_layer_data_getdefaults(l, parent);
361 l->eff_freq = (l->waveform && l->waveform->info.samplerate) ? l->waveform->info.samplerate : 44100;
362 // XXXKF should have a distinction between 'configured' and 'effective' loop start/end
363 if (l->loop_mode == slm_unknown)
365 if (l->waveform && l->waveform->has_loop)
366 l->loop_mode = slm_loop_continuous;
367 else
368 l->loop_mode = l->loop_end == 0 ? slm_no_loop : slm_loop_continuous;
371 if (l->loop_mode == slm_one_shot || l->loop_mode == slm_no_loop || l->loop_mode == slm_one_shot_chokeable)
372 l->loop_start = -1;
374 if ((l->loop_mode == slm_loop_continuous || l->loop_mode == slm_loop_sustain) && l->loop_start == -1)
375 l->loop_start = 0;
376 if ((l->loop_mode == slm_loop_continuous || l->loop_mode == slm_loop_sustain) && l->loop_start == 0 && l->waveform && l->waveform->has_loop)
377 l->loop_start = l->waveform->loop_start;
378 if (l->loop_end == 0 && l->waveform != NULL && l->waveform->has_loop)
379 l->loop_end = l->waveform->loop_end;
381 if (l->off_mode == som_unknown)
382 l->off_mode = l->off_by != 0 ? som_fast : som_normal;
384 // if no amp_velcurve_nnn setting, default to quadratic
385 if (l->velcurve_quadratic == -1)
386 l->velcurve_quadratic = 1;
388 if (l->key >= 0 && l->key <= 127)
389 l->lokey = l->hikey = l->pitch_keycenter = l->key;
391 // interpolate missing points in velcurve
392 int start = 0;
393 for (int i = 1; i < 128; i++)
395 if (l->velcurve[i] == -1)
396 continue;
397 float sv = l->velcurve[start];
398 float ev = l->velcurve[i];
399 if (l->velcurve_quadratic)
401 for (int j = start; j <= i; j++)
402 l->eff_velcurve[j] = sv + (ev - sv) * (j - start) * (j - start) / ((i - start) * (i - start));
404 else
406 for (int j = start; j <= i; j++)
407 l->eff_velcurve[j] = sv + (ev - sv) * (j - start) / (i - start);
409 start = i;
411 l->eff_use_keyswitch = ((l->sw_down != -1) || (l->sw_up != -1) || (l->sw_last != -1) || (l->sw_previous != -1));
414 void sampler_layer_reset_switches(struct sampler_layer *l, struct sampler_module *m)
416 l->last_key = l->data.sw_lokey;
417 l->current_seq_position = l->data.seq_position;
420 struct layer_foreach_struct
422 struct sampler_layer *layer;
423 const char *cfg_section;
426 static void layer_foreach_func(void *user_data, const char *key)
428 if (!strcmp(key, "file"))
429 key = "sample";
430 // import is handled in sampler_load_layer_overrides
431 if (!strcmp(key, "import"))
432 return;
433 struct layer_foreach_struct *lfs = user_data;
434 const char *value = cbox_config_get_string(lfs->cfg_section, key);
435 GError *error = NULL;
436 if (!sampler_layer_apply_param(lfs->layer, key, value, &error))
438 if (error)
439 g_warning("Error '%s', context: %s in section %s", error->message, key, lfs->cfg_section);
440 else
441 g_warning("Unknown sample layer parameter: %s in section %s", key, lfs->cfg_section);
445 void sampler_layer_load_overrides(struct sampler_layer *l, const char *cfg_section)
447 char *imp = cbox_config_get_string(cfg_section, "import");
448 if (imp)
449 sampler_layer_load_overrides(l, imp);
451 struct layer_foreach_struct lfs = {
452 .layer = l,
453 .cfg_section = cfg_section
455 cbox_config_foreach_key(layer_foreach_func, cfg_section, &lfs);
458 struct sampler_layer *sampler_layer_new_from_section(struct sampler_module *m, struct sampler_program *parent_program, const char *cfg_section)
460 struct sampler_layer *l = sampler_layer_new(m, parent_program, NULL);
461 sampler_layer_load_overrides(l, cfg_section);
462 sampler_layer_data_finalize(&l->data, l->parent_group ? &l->parent_group->data : NULL, m);
463 sampler_layer_reset_switches(l, m);
464 return l;
467 static int sfz_note_from_string(const char *note)
469 static const int semis[] = {9, 11, 0, 2, 4, 5, 7};
470 int pos;
471 int nn = tolower(note[0]);
472 int nv;
473 if (nn >= '0' && nn <= '9')
474 return atoi(note);
475 if (nn < 'a' && nn > 'g')
476 return -1;
477 nv = semis[nn - 'a'];
479 for (pos = 1; tolower(note[pos]) == 'b' || note[pos] == '#'; pos++)
480 nv += (note[pos] != '#') ? -1 : +1;
482 if ((note[pos] == '-' && note[pos + 1] == '1' && note[pos + 2] == '\0') || (note[pos] >= '0' && note[pos] <= '9' && note[pos + 1] == '\0'))
484 return nv + 12 * (1 + atoi(note + pos));
487 return -1;
490 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)
492 static const enum sampler_modsrc srcs[] = { smsrc_ampenv, smsrc_filenv, smsrc_pitchenv };
493 static const enum sampler_moddest dests[] = { smdest_gain, smdest_cutoff, smdest_pitch };
494 enum sampler_modsrc src = srcs[env_type];
495 enum sampler_moddest dest = dests[env_type];
496 float fvalue = atof(value);
498 #define PROC_SET_ENV_FIELD(name, index, def_value) \
499 if (!strcmp(key, #name)) {\
500 env->name = fvalue; \
501 has_fields->name = 1; \
502 return TRUE; \
504 DAHDSR_FIELDS(PROC_SET_ENV_FIELD)
505 if (!strcmp(key, "depth"))
506 sampler_layer_set_modulation1(layer, src, dest, atof(value), 0);
507 else if (!strcmp(key, "vel2delay"))
508 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 0, fvalue);
509 else if (!strcmp(key, "vel2attack"))
510 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 1, fvalue);
511 else if (!strcmp(key, "vel2hold"))
512 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 2, fvalue);
513 else if (!strcmp(key, "vel2decay"))
514 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 3, fvalue);
515 else if (!strcmp(key, "vel2sustain"))
516 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 4, fvalue);
517 else if (!strcmp(key, "vel2release"))
518 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 5, fvalue);
519 else if (!strcmp(key, "vel2depth"))
520 sampler_layer_set_modulation(layer, src, smsrc_vel, dest, atof(value), 0);
521 else if (!strncmp(key, "depthcc", 7))
523 int cc = atoi(key + 7);
524 if (cc > 0 && cc < 120)
525 sampler_layer_set_modulation(layer, src, cc, dest, fvalue, 0);
526 else
527 return FALSE;
529 else
530 return FALSE;
531 return TRUE;
534 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)
536 static const enum sampler_modsrc srcs[] = { smsrc_amplfo, smsrc_fillfo, smsrc_pitchlfo };
537 static const enum sampler_moddest dests[] = { smdest_gain, smdest_cutoff, smdest_pitch };
538 enum sampler_modsrc src = srcs[lfo_type];
539 enum sampler_moddest dest = dests[lfo_type];
541 #define PROC_SET_LFO_FIELD(name, index, def_value) \
542 if (!strcmp(key, #name)) {\
543 params->name = fvalue; \
544 has_fields->name = 1; \
545 return TRUE; \
547 float fvalue = atof(value);
548 LFO_FIELDS(PROC_SET_LFO_FIELD)
549 if (!strcmp(key, "depth"))
550 sampler_layer_set_modulation1(layer, src, dest, fvalue, 0);
551 else if (!strcmp(key, "depthchanaft"))
552 sampler_layer_set_modulation(layer, src, smsrc_chanaft, dest, fvalue, 0);
553 else if (!strcmp(key, "depthpolyaft"))
554 sampler_layer_set_modulation(layer, src, smsrc_polyaft, dest, fvalue, 0);
555 else if (!strncmp(key, "depthcc", 7))
557 int cc = atoi(key + 7);
558 if (cc > 0 && cc < 120)
559 sampler_layer_set_modulation(layer, src, cc, dest, fvalue, 0);
560 else
561 return FALSE;
563 else
564 return FALSE;
565 return TRUE;
568 #define PARSE_PARAM_midi_note_t(field, strname, valuestr) \
569 return ((l->data.field = sfz_note_from_string(value)), (l->data.has_##field = 1));
570 #define PARSE_PARAM_int(field, strname, valuestr) \
571 return ((l->data.field = atoi(value)), (l->data.has_##field = 1));
572 #define PARSE_PARAM_uint32_t(field, strname, valuestr) \
573 return ((l->data.field = (uint32_t)strtoul(value, NULL, 10)), (l->data.has_##field = 1));
574 #define PARSE_PARAM_float(field, strname, valuestr) \
575 return ((l->data.field = atof(value)), (l->data.has_##field = 1));
577 #define PROC_APPLY_PARAM(type, name, def_value) \
578 if (!strcmp(key, #name)) { \
579 PARSE_PARAM_##type(name, #name, value) \
581 #define PROC_APPLY_PARAM_dBamp(type, name, def_value) \
582 if (!strcmp(key, #name)) { \
583 return ((l->data.name = atof(value)), (l->data.has_##name = 1)); \
585 #define PROC_APPLY_PARAM_enum(enumtype, name, def_value) \
586 if (!strcmp(key, #name)) { \
587 if (!enumtype##_from_string(value, &l->data.name)) { \
588 g_set_error(error, CBOX_MODULE_ERROR, CBOX_MODULE_ERROR_FAILED, "Value %s is not a correct value for %s", value, #name); \
589 return FALSE; \
591 l->data.has_##name = 1; \
592 return TRUE; \
594 // LFO and envelope need special handling now
595 #define PROC_APPLY_PARAM_dahdsr(name, parname, index) \
596 if (!strncmp(key, #parname "_", sizeof(#parname))) \
597 return parse_envelope_param(l, &l->data.name, &l->data.has_##name, index, key + sizeof(#parname), value);
598 #define PROC_APPLY_PARAM_lfo(name, parname, index) \
599 if (!strncmp(key, #parname "_", sizeof(#parname))) \
600 return parse_lfo_param(l, &l->data.name, &l->data.has_##name, index, key + sizeof(#parname), value);
601 #define PROC_APPLY_PARAM_ccrange(name) /* handled separately in apply_param */
603 static void sampler_layer_apply_unknown(struct sampler_layer *l, const char *key, const char *value)
605 if (!l->unknown_keys)
606 l->unknown_keys = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
608 g_hash_table_insert(l->unknown_keys, g_strdup(key), g_strdup(value));
611 gboolean sampler_layer_apply_param(struct sampler_layer *l, const char *key, const char *value, GError **error)
613 try_now:
614 // XXXKF: this is seriously stupid code, this should use a hash table for
615 // fixed strings, or something else that doesn't explode O(N**2) with
616 // number of attributes. But premature optimization is a root of all evil.
618 SAMPLER_FIXED_FIELDS(PROC_APPLY_PARAM)
620 // XXXKF: to make things worse, some attributes have names different from
621 // C field names, or have multiple names, or don't map 1:1 to internal model
623 if (!strcmp(key, "sample"))
625 struct cbox_waveform *old_waveform = l->data.waveform;
626 gchar *value_copy = g_strdup(value);
627 gchar *filename = value_copy;
628 if (value[0] != '*')
630 for (int i = 0; value_copy[i]; i++)
632 if (value_copy[i] == '\\')
633 value_copy[i] = '/';
635 filename = g_build_filename(l->parent_program->sample_dir, value_copy, NULL);
636 g_free(value_copy);
638 struct cbox_waveform *wf = cbox_wavebank_get_waveform(l->parent_program->source_file, filename, error);
639 g_free(filename);
640 if (!wf)
641 return FALSE;
642 sampler_layer_set_waveform(l, wf);
643 if (old_waveform != NULL)
644 cbox_waveform_unref(old_waveform);
645 return TRUE;
647 else if (!strcmp(key, "lolev"))
648 l->data.lovel = atoi(value), l->data.has_lovel = 1;
649 else if (!strcmp(key, "hilev"))
650 l->data.hivel = atoi(value), l->data.has_hivel = 1;
651 else if (!strcmp(key, "benddown"))
652 l->data.bend_down = atoi(value), l->data.has_bend_down = 1;
653 else if (!strcmp(key, "bendup"))
654 l->data.bend_up = atoi(value), l->data.has_bend_up = 1;
655 else if (!strcmp(key, "loopstart"))
656 l->data.loop_start = atoi(value), l->data.has_loop_start = 1;
657 else if (!strcmp(key, "loopend"))
658 l->data.loop_end = atoi(value), l->data.has_loop_end = 1;
659 else if (!strcmp(key, "loopmode"))
661 key = "loop_mode";
662 goto try_now; // yes, goto, why not?
664 else if (!strcmp(key, "cutoff_chanaft"))
665 sampler_layer_set_modulation1(l, smsrc_chanaft, smdest_cutoff, atof(value), 0);
666 else if (!strcmp(key, "amp_random"))
667 sampler_layer_add_nif(l, sampler_nif_addrandom, 0, atof(value));
668 else if (!strcmp(key, "fil_random"))
669 sampler_layer_add_nif(l, sampler_nif_addrandom, 1, atof(value));
670 else if (!strcmp(key, "pitch_random"))
671 sampler_layer_add_nif(l, sampler_nif_addrandom, 2, atof(value));
672 else if (!strcmp(key, "pitch_veltrack"))
673 sampler_layer_add_nif(l, sampler_nif_vel2pitch, 0, atof(value));
674 else if (!strncmp(key, "delay_cc", 8))
676 int ccno = atoi(key + 8);
677 if (ccno > 0 && ccno < 120)
678 sampler_layer_add_nif(l, sampler_nif_cc2delay, ccno, atof(value));
679 else
680 goto unknown_key;
682 else if (!strncmp(key, "cutoff_cc", 9))
684 int ccno = atoi(key + 9);
685 if (ccno > 0 && ccno < 120)
686 sampler_layer_set_modulation1(l, ccno, smdest_cutoff, atof(value), 0);
687 else
688 goto unknown_key;
690 else if (!strncmp(key, "gain_cc", 7))
692 int ccno = atoi(key + 7);
693 if (ccno > 0 && ccno < 120)
694 sampler_layer_set_modulation1(l, ccno, smdest_gain, atof(value), 0);
695 else
696 goto unknown_key;
698 else if (!strncmp(key, "amp_velcurve_", 13))
700 // if not known yet, set to 0, it can always be overriden via velcurve_quadratic setting
701 if (l->data.velcurve_quadratic == -1)
702 l->data.velcurve_quadratic = 0;
703 int point = atoi(key + 13);
704 if (point >= 0 && point <= 127)
706 l->data.velcurve[point] = atof(value);
707 if (l->data.velcurve[point] < 0)
708 l->data.velcurve[point] = 0;
709 if (l->data.velcurve[point] > 1)
710 l->data.velcurve[point] = 1;
712 else
713 goto unknown_key;
715 else if (!strncmp(key, "on_locc", 7) || !strncmp(key, "on_hicc", 7))
717 int cc = atoi(key + 7);
718 if (cc > 0 && cc < 120)
720 if (*value)
722 l->data.on_cc_number = cc;
723 if (key[3] == 'l')
725 l->data.on_locc = atoi(value);
726 l->data.has_on_locc = TRUE;
728 else
730 l->data.on_hicc = atoi(value);
731 l->data.has_on_hicc = TRUE;
734 else
736 l->data.on_cc_number = -1;
737 l->data.has_on_locc = FALSE;
738 l->data.has_on_hicc = FALSE;
741 else
742 return FALSE;
744 else if (!strncmp(key, "locc", 4) || !strncmp(key, "hicc", 4))
746 int cc = atoi(key + 4);
747 if (cc > 0 && cc < 120)
749 if (*value)
751 l->data.cc_number = cc;
752 if (key[0] == 'l')
754 l->data.locc = atoi(value);
755 l->data.has_locc = TRUE;
757 else
759 l->data.hicc = atoi(value);
760 l->data.has_hicc = TRUE;
763 else
765 l->data.cc_number = -1;
766 l->data.has_locc = FALSE;
767 l->data.has_hicc = FALSE;
770 else
771 return FALSE;
773 else
774 goto unknown_key;
776 return TRUE;
777 unknown_key:
778 sampler_layer_apply_unknown(l, key, value);
779 g_warning("Unknown SFZ property key: '%s'", key);
780 return TRUE;
783 #define TYPE_PRINTF_uint32_t(name, def_value) \
784 if (show_inherited || l->has_##name) \
785 g_string_append_printf(outstr, " %s=%u", #name, (unsigned)(l->name));
786 #define TYPE_PRINTF_int(name, def_value) \
787 if (show_inherited || l->has_##name) \
788 g_string_append_printf(outstr, " %s=%d", #name, (int)(l->name));
789 #define TYPE_PRINTF_midi_note_t(name, def_value) \
790 if (show_inherited || l->has_##name) { \
791 int val = l->name; \
792 if (val == -1) \
793 g_string_append_printf(outstr, " %s=-1", #name); \
794 else \
795 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)); \
796 } else {}
797 #define TYPE_PRINTF_float(name, def_value) \
798 if (show_inherited || l->has_##name) \
799 g_string_append_printf(outstr, " %s=%g", #name, (float)(l->name));
801 #define PROC_FIELDS_TO_FILEPTR(type, name, def_value) \
802 TYPE_PRINTF_##type(name, def_value)
803 #define PROC_FIELDS_TO_FILEPTR_dBamp(type, name, def_value) \
804 if (show_inherited || l->has_##name) \
805 g_string_append_printf(outstr, " %s=%g", #name, (float)(l->name));
806 #define PROC_FIELDS_TO_FILEPTR_enum(enumtype, name, def_value) \
807 if ((show_inherited || l->has_##name) && (tmpstr = enumtype##_to_string(l->name)) != NULL) \
808 g_string_append_printf(outstr, " %s=%s", #name, tmpstr);
810 #define ENV_PARAM_OUTPUT(param, index, def_value, env, envfield, envname) \
811 if (show_inherited || l->has_##envfield.param) \
812 g_string_append_printf(outstr, " " #envname "_" #param "=%g", env.param);
814 #define PROC_FIELDS_TO_FILEPTR_dahdsr(name, parname, index) \
815 DAHDSR_FIELDS(ENV_PARAM_OUTPUT, l->name, name, parname)
816 #define PROC_FIELDS_TO_FILEPTR_lfo(name, parname, index) \
817 LFO_FIELDS(ENV_PARAM_OUTPUT, l->name, name, parname)
818 #define PROC_FIELDS_TO_FILEPTR_ccrange(name) \
819 if (l->has_##name##locc) \
820 g_string_append_printf(outstr, " " #name "locc%d=%d", l->name##cc_number, l->name##locc); \
821 if (l->has_##name##hicc) \
822 g_string_append_printf(outstr, " " #name "hicc%d=%d", l->name##cc_number, l->name##hicc);
824 gchar *sampler_layer_to_string(struct sampler_layer *lr, gboolean show_inherited)
826 struct sampler_layer_data *l = &lr->data;
827 GString *outstr = g_string_sized_new(200);
828 const char *tmpstr;
829 if ((show_inherited || l->has_waveform) && l->waveform && l->waveform->display_name)
830 g_string_append_printf(outstr, " sample=%s", l->waveform->display_name);
831 SAMPLER_FIXED_FIELDS(PROC_FIELDS_TO_FILEPTR)
833 static const char *addrandom_variants[] = { "amp", "fil", "pitch" };
834 static const char *modsrc_names[] = { "chanaft", "vel", "polyaft", "pitch", "pitcheg", "fileg", "ampeg", "pitchlfo", "fillfo", "amplfo", "" };
835 static const char *moddest_names[] = { "gain", "pitch", "cutoff", "resonance" };
836 for(GSList *nif = l->nifs; nif; nif = nif->next)
838 struct sampler_noteinitfunc *nd = nif->data;
839 if (!nd->has_value && !show_inherited)
840 continue;
841 #define PROC_ENVSTAGE_NAME(name, index, def_value) #name,
842 static const char *env_stages[] = { DAHDSR_FIELDS(PROC_ENVSTAGE_NAME) };
843 int v = nd->variant;
845 if (nd->notefunc == sampler_nif_addrandom && v >= 0 && v <= 2)
846 g_string_append_printf(outstr, " %s_random=%g", addrandom_variants[nd->variant], nd->param);
847 else if (nd->notefunc == sampler_nif_vel2pitch)
848 g_string_append_printf(outstr, " pitch_veltrack=%g", nd->param);
849 else if (nd->notefunc == sampler_nif_cc2delay && v >= 0 && v < 120)
850 g_string_append_printf(outstr, " delay_cc%d=%g", nd->variant, nd->param);
851 else if (nd->notefunc == sampler_nif_vel2env && v >= 0 && (v & 15) < 6 && (v >> 4) < 3)
852 g_string_append_printf(outstr, " %seg_vel2%s=%g", addrandom_variants[nd->variant >> 4], env_stages[1 + (v & 15)], nd->param);
854 for(GSList *mod = l->modulations; mod; mod = mod->next)
856 struct sampler_modulation *md = mod->data;
857 if (!md->has_value && !show_inherited)
858 continue;
860 if (md->src2 == smsrc_none)
862 if (md->src < 120)
864 g_string_append_printf(outstr, " %s_cc%d=%g", moddest_names[md->dest], md->src, md->amount);
865 continue;
867 if (md->src < 120 + sizeof(modsrc_names) / sizeof(modsrc_names[0]))
869 if ((md->src == smsrc_filenv && md->dest == smdest_cutoff) ||
870 (md->src == smsrc_pitchenv && md->dest == smdest_pitch))
871 g_string_append_printf(outstr, " %s_depth=%g", modsrc_names[md->src - 120], md->amount);
872 else
873 g_string_append_printf(outstr, " %s_%s=%g", moddest_names[md->dest], modsrc_names[md->src - 120], md->amount);
874 continue;
877 if ((md->src == smsrc_amplfo && md->dest == smdest_gain) ||
878 (md->src == smsrc_fillfo && md->dest == smdest_cutoff) ||
879 (md->src == smsrc_pitchlfo && md->dest == smdest_pitch))
881 switch(md->src2)
883 case smsrc_chanaft:
884 case smsrc_polyaft:
885 g_string_append_printf(outstr, " %slfo_depth%s=%g", moddest_names[md->dest], modsrc_names[md->src2 - 120], md->amount);
886 continue;
887 default:
888 if (md->src2 < 120)
890 g_string_append_printf(outstr, " %slfo_depthcc%d=%g", moddest_names[md->dest], md->src2, md->amount);
891 continue;
893 break;
895 break;
897 if ((md->src == smsrc_ampenv && md->dest == smdest_gain) ||
898 (md->src == smsrc_filenv && md->dest == smdest_cutoff) ||
899 (md->src == smsrc_pitchenv && md->dest == smdest_pitch))
901 if (md->src2 == smsrc_vel)
903 g_string_append_printf(outstr, " %seg_vel2depth=%g", moddest_names[md->dest], md->amount);
904 continue;
906 if (md->src2 < 120)
908 g_string_append_printf(outstr, " %s_depthcc%d=%g", modsrc_names[md->src - 120], md->src2, md->amount);
909 continue;
912 g_string_append_printf(outstr, " genericmod_from_%d_and_%d_to_%d=%g", md->src, md->src2, md->dest, md->amount);
915 if (lr->unknown_keys)
917 GHashTableIter hti;
918 gchar *key, *value;
919 g_hash_table_iter_init(&hti, lr->unknown_keys);
920 while(g_hash_table_iter_next(&hti, (gpointer *)&key, (gpointer *)&value))
921 g_string_append_printf(outstr, " %s=%s", key, value);
924 gchar *res = outstr->str;
925 g_string_free(outstr, FALSE);
926 return res;
929 void sampler_layer_dump(struct sampler_layer *l, FILE *f)
931 gchar *str = sampler_layer_to_string(l, FALSE);
932 fprintf(f, "%s\n", str);
935 void sampler_layer_data_close(struct sampler_layer_data *l)
937 g_slist_free_full(l->nifs, g_free);
938 g_slist_free_full(l->modulations, g_free);
939 if (l->waveform)
941 cbox_waveform_unref(l->waveform);
942 l->waveform = NULL;
946 void sampler_layer_data_destroy(struct sampler_layer_data *l)
948 sampler_layer_data_close(l);
949 free(l);
952 void sampler_layer_destroyfunc(struct cbox_objhdr *objhdr)
954 struct sampler_layer *l = CBOX_H2O(objhdr);
955 struct sampler_program *prg = l->parent_program;
956 struct sampler_module *m = l->module;
957 assert(g_hash_table_size(l->child_layers) == 0);
959 if (l->parent_group)
961 g_hash_table_remove(l->parent_group->child_layers, l);
962 if (prg && prg->rll)
964 sampler_program_delete_layer(prg, l);
965 sampler_update_program_layers(m, prg);
967 l->parent_group = NULL;
969 sampler_layer_data_close(&l->data);
970 if (l->runtime)
971 sampler_layer_data_destroy(l->runtime);
972 if (l->unknown_keys)
973 g_hash_table_destroy(l->unknown_keys);
974 if (l->child_layers)
975 g_hash_table_destroy(l->child_layers);
977 free(l);