Buggy but almost working implementation of JACK transport control.
[calfbox.git] / sampler_layer.c
blob336f9860710772495608eca210dc2831407f1c58
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>
37 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)
39 GSList *p = l->modulations;
40 while(p)
42 struct sampler_modulation *sm = p->data;
43 if (sm->src == src && sm->src2 == src2 && sm->dest == dest)
45 // do not overwrite locally set value with defaults
46 if (propagating_defaults && sm->has_value)
47 return;
48 sm->amount = amount;
49 sm->flags = flags;
50 sm->has_value = !propagating_defaults;
51 return;
53 p = g_slist_next(p);
55 struct sampler_modulation *sm = g_malloc0(sizeof(struct sampler_modulation));
56 sm->src = src;
57 sm->src2 = src2;
58 sm->dest = dest;
59 sm->amount = amount;
60 sm->flags = flags;
61 sm->has_value = !propagating_defaults;
62 l->modulations = g_slist_prepend(l->modulations, sm);
65 void sampler_layer_set_modulation1(struct sampler_layer *l, enum sampler_modsrc src, enum sampler_moddest dest, float amount, int flags)
67 sampler_layer_data_set_modulation(&l->data, src, smsrc_none, dest, amount, flags, FALSE);
70 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)
72 sampler_layer_data_set_modulation(&l->data, src, src2, dest, amount, flags, FALSE);
75 void sampler_layer_data_add_nif(struct sampler_layer_data *l, SamplerNoteInitFunc notefunc, int variant, float param, gboolean propagating_defaults)
77 GSList *p = l->nifs;
78 while(p)
80 struct sampler_noteinitfunc *nif = p->data;
81 if (nif->notefunc == notefunc && nif->variant == variant)
83 // do not overwrite locally set value with defaults
84 if (propagating_defaults && nif->has_value)
85 return;
86 nif->param = param;
87 nif->has_value = !propagating_defaults;
88 return;
90 p = g_slist_next(p);
92 struct sampler_noteinitfunc *nif = malloc(sizeof(struct sampler_noteinitfunc));
93 nif->notefunc = notefunc;
94 nif->variant = variant;
95 nif->param = param;
96 nif->has_value = !propagating_defaults;
97 l->nifs = g_slist_prepend(l->nifs, nif);
100 void sampler_layer_add_nif(struct sampler_layer *l, SamplerNoteInitFunc notefunc, int variant, float param)
102 sampler_layer_data_add_nif(&l->data, notefunc, variant, param, FALSE);
105 static gboolean sampler_layer_process_cmd(struct cbox_command_target *ct, struct cbox_command_target *fb, struct cbox_osc_command *cmd, GError **error)
107 struct sampler_layer *layer = ct->user_data;
108 if (!strcmp(cmd->command, "/status") && !strcmp(cmd->arg_types, ""))
110 if (!cbox_check_fb_channel(fb, cmd->command, error))
111 return FALSE;
113 if (!((!layer->parent_program || cbox_execute_on(fb, NULL, "/parent_program", "o", error, layer->parent_program)) &&
114 (!layer->parent_group || cbox_execute_on(fb, NULL, "/parent_group", "o", error, layer->parent_group)) &&
115 CBOX_OBJECT_DEFAULT_STATUS(layer, fb, error)))
116 return FALSE;
117 return TRUE;
119 if ((!strcmp(cmd->command, "/as_string") || !strcmp(cmd->command, "/as_string_full")) && !strcmp(cmd->arg_types, ""))
121 if (!cbox_check_fb_channel(fb, cmd->command, error))
122 return FALSE;
123 gchar *res = sampler_layer_to_string(layer, !strcmp(cmd->command, "/as_string_full"));
124 gboolean result = cbox_execute_on(fb, NULL, "/value", "s", error, res);
125 g_free(res);
126 return result;
128 if (!strcmp(cmd->command, "/set_param") && !strcmp(cmd->arg_types, "ss"))
130 const char *key = CBOX_ARG_S(cmd, 0);
131 const char *value = CBOX_ARG_S(cmd, 1);
132 if (sampler_layer_apply_param(layer, key, value, error))
134 sampler_layer_update(layer);
135 sampler_program_update_layers(layer->parent_program);
136 return TRUE;
138 return FALSE;
140 if (!strcmp(cmd->command, "/new_region") && !strcmp(cmd->arg_types, ""))
142 // XXXKF needs a string argument perhaps
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->parent_program);
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_string(name) \
182 ld->name = NULL; \
183 ld->name##_changed = FALSE; \
184 ld->has_##name = 0;
185 #define PROC_FIELDS_INITIALISER_enum(type, name, def_value) \
186 PROC_FIELDS_INITIALISER(type, name, def_value)
187 #define PROC_FIELDS_INITIALISER_dBamp(type, name, def_value) \
188 ld->name = def_value; \
189 ld->name##_linearized = -1; \
190 ld->has_##name = 0;
191 #define PROC_FIELDS_INITIALISER_dahdsr(name, parname, index) \
192 DAHDSR_FIELDS(PROC_SUBSTRUCT_RESET_FIELD, name, ld); \
193 DAHDSR_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, ld)
194 #define PROC_FIELDS_INITIALISER_lfo(name, parname, index) \
195 LFO_FIELDS(PROC_SUBSTRUCT_RESET_FIELD, name, ld); \
196 LFO_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, ld)
197 #define PROC_FIELDS_INITIALISER_ccrange(name) \
198 ld->name##locc = 0; \
199 ld->name##hicc = 127; \
200 ld->name##cc_number = 0; \
201 ld->has_##name##locc = 0; \
202 ld->has_##name##hicc = 0;
204 CBOX_CLASS_DEFINITION_ROOT(sampler_layer)
206 struct sampler_layer *sampler_layer_new(struct sampler_module *m, struct sampler_program *parent_program, struct sampler_layer *parent_group)
208 struct sampler_layer *l = calloc(1, sizeof(struct sampler_layer));
209 struct cbox_document *doc = CBOX_GET_DOCUMENT(parent_program);
210 memset(l, 0, sizeof(struct sampler_layer));
211 CBOX_OBJECT_HEADER_INIT(l, sampler_layer, doc);
212 cbox_command_target_init(&l->cmd_target, sampler_layer_process_cmd, l);
214 l->module = m;
215 l->child_layers = g_hash_table_new(NULL, NULL);
216 if (parent_group)
218 sampler_layer_data_clone(&l->data, &parent_group->data, FALSE);
219 l->parent_program = parent_program;
220 l->parent_group = parent_group;
221 g_hash_table_replace(parent_group->child_layers, l, l);
222 l->runtime = NULL;
223 CBOX_OBJECT_REGISTER(l);
224 return l;
226 l->parent_program = parent_program;
228 struct sampler_layer_data *ld = &l->data;
229 SAMPLER_FIXED_FIELDS(PROC_FIELDS_INITIALISER)
231 ld->eff_waveform = NULL;
232 ld->eff_freq = 44100;
233 ld->velcurve[0] = 0;
234 ld->velcurve[127] = 1;
235 for (int i = 1; i < 127; i++)
236 ld->velcurve[i] = -1;
237 ld->modulations = NULL;
238 ld->nifs = NULL;
239 ld->on_locc = 0;
240 ld->on_hicc = 127;
241 ld->on_cc_number = -1;
243 ld->eff_use_keyswitch = 0;
244 l->last_key = -1;
245 if (!parent_group)
247 sampler_layer_set_modulation1(l, 74, smdest_cutoff, 9600, 2);
248 sampler_layer_set_modulation1(l, 71, smdest_resonance, 12, 2);
249 sampler_layer_set_modulation(l, smsrc_pitchlfo, 1, smdest_pitch, 100, 0);
251 l->runtime = NULL;
252 l->unknown_keys = NULL;
253 CBOX_OBJECT_REGISTER(l);
254 return l;
257 #define PROC_FIELDS_CLONE(type, name, def_value) \
258 dst->name = src->name; \
259 dst->has_##name = copy_hasattr ? src->has_##name : FALSE;
260 #define PROC_FIELDS_CLONE_string(name) \
261 dst->name = src->name ? g_strdup(src->name) : NULL; \
262 dst->name##_changed = src->name##_changed; \
263 dst->has_##name = copy_hasattr ? src->has_##name : FALSE;
264 #define PROC_FIELDS_CLONE_dBamp PROC_FIELDS_CLONE
265 #define PROC_FIELDS_CLONE_enum PROC_FIELDS_CLONE
266 #define PROC_FIELDS_CLONE_dahdsr(name, parname, index) \
267 DAHDSR_FIELDS(PROC_SUBSTRUCT_CLONE, name, dst, src) \
268 if (!copy_hasattr) \
269 DAHDSR_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, dst)
270 #define PROC_FIELDS_CLONE_lfo(name, parname, index) \
271 LFO_FIELDS(PROC_SUBSTRUCT_CLONE, name, dst, src) \
272 if (!copy_hasattr) \
273 LFO_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, dst)
274 #define PROC_FIELDS_CLONE_ccrange(name) \
275 dst->name##locc = src->name##locc; \
276 dst->name##hicc = src->name##hicc; \
277 dst->name##cc_number = src->name##cc_number; \
278 dst->has_##name##locc = copy_hasattr ? src->has_##name##locc : FALSE; \
279 dst->has_##name##hicc = copy_hasattr ? src->has_##name##hicc : FALSE;
281 void sampler_layer_data_clone(struct sampler_layer_data *dst, const struct sampler_layer_data *src, gboolean copy_hasattr)
283 SAMPLER_FIXED_FIELDS(PROC_FIELDS_CLONE)
284 memcpy(dst->velcurve, src->velcurve, 128 * sizeof(float));
285 dst->modulations = g_slist_copy(src->modulations);
286 for(GSList *mod = dst->modulations; mod; mod = mod->next)
288 struct sampler_modulation *srcm = mod->data;
289 struct sampler_modulation *dstm = g_malloc(sizeof(struct sampler_modulation));
290 memcpy(dstm, srcm, sizeof(struct sampler_modulation));
291 dstm->has_value = copy_hasattr ? srcm->has_value : FALSE;
292 mod->data = dstm;
294 dst->nifs = g_slist_copy(src->nifs);
295 for(GSList *nif = dst->nifs; nif; nif = nif->next)
297 struct sampler_noteinitfunc *dstn = g_malloc(sizeof(struct sampler_noteinitfunc));
298 struct sampler_noteinitfunc *srcn = nif->data;
299 memcpy(dstn, srcn, sizeof(struct sampler_noteinitfunc));
300 dstn->has_value = copy_hasattr ? srcn->has_value : FALSE;
301 nif->data = dstn;
303 dst->eff_waveform = src->eff_waveform;
304 if (dst->eff_waveform)
305 cbox_waveform_ref(dst->eff_waveform);
308 #define PROC_FIELDS_CLONEPARENT(type, name, def_value) \
309 if (!l->has_##name) \
310 l->name = parent ? parent->name : def_value;
311 #define PROC_FIELDS_CLONEPARENT_string(name) \
312 if (!l->has_##name && (!l->name || !parent->name || strcmp(l->name, parent->name))) { \
313 g_free(l->name); \
314 l->name = parent && parent->name ? g_strdup(parent->name) : NULL; \
315 l->name##_changed = parent && parent->name##_changed; \
317 #define PROC_FIELDS_CLONEPARENT_dBamp PROC_FIELDS_CLONEPARENT
318 #define PROC_FIELDS_CLONEPARENT_enum PROC_FIELDS_CLONEPARENT
319 #define PROC_FIELDS_CLONEPARENT_dahdsr(name, parname, index) \
320 DAHDSR_FIELDS(PROC_SUBSTRUCT_CLONEPARENT, name, l)
321 #define PROC_FIELDS_CLONEPARENT_lfo(name, parname, index) \
322 LFO_FIELDS(PROC_SUBSTRUCT_CLONEPARENT, name, l)
323 #define PROC_FIELDS_CLONEPARENT_ccrange(name) \
324 if (!l->has_##name##locc) \
325 l->name##locc = parent ? parent->name##locc : 0; \
326 if (!l->has_##name##hicc) \
327 l->name##hicc = parent ? parent->name##hicc : 127; \
328 if (!l->has_##name##locc && !l->has_##name##hicc) \
329 l->name##cc_number = parent ? parent->name##cc_number : -1;
331 static void sampler_layer_data_getdefaults(struct sampler_layer_data *l, struct sampler_layer_data *parent)
333 SAMPLER_FIXED_FIELDS(PROC_FIELDS_CLONEPARENT)
334 // XXXKF: add handling for velcurve
335 if (parent)
337 // set NIFs used by parent
338 for(GSList *mod = parent->nifs; mod; mod = mod->next)
340 struct sampler_noteinitfunc *nif = mod->data;
341 sampler_layer_data_add_nif(l, nif->notefunc, nif->variant, nif->param, TRUE);
343 // set modulations used by parent
344 for(GSList *mod = parent->modulations; mod; mod = mod->next)
346 struct sampler_modulation *srcm = mod->data;
347 sampler_layer_data_set_modulation(l, srcm->src, srcm->src2, srcm->dest, srcm->amount, srcm->flags, TRUE);
352 #define PROC_FIELDS_FINALISER(type, name, def_value)
353 #define PROC_FIELDS_FINALISER_string(name)
354 #define PROC_FIELDS_FINALISER_enum(type, name, def_value)
355 #define PROC_FIELDS_FINALISER_dBamp(type, name, def_value) \
356 l->name##_linearized = dB2gain(l->name);
357 #define PROC_FIELDS_FINALISER_dahdsr(name, parname, index) \
358 cbox_envelope_init_dahdsr(&l->name##_shape, &l->name, m->module.srate / CBOX_BLOCK_SIZE, 100.f, &l->name##_shape == &l->amp_env_shape);
359 #define PROC_FIELDS_FINALISER_lfo(name, parname, index) /* no finaliser required */
360 #define PROC_FIELDS_FINALISER_ccrange(name) /* no finaliser required */
362 void sampler_layer_data_finalize(struct sampler_layer_data *l, struct sampler_layer_data *parent, struct sampler_program *p)
364 struct sampler_module *m = p->module;
365 SAMPLER_FIXED_FIELDS(PROC_FIELDS_FINALISER)
367 sampler_layer_data_getdefaults(l, parent);
369 // Handle change of sample in the prent group without override on region level
370 if (parent && (l->sample_changed || parent->sample_changed))
372 struct cbox_waveform *oldwf = l->eff_waveform;
373 if (l->sample && *l->sample)
375 GError *error = NULL;
376 l->eff_waveform = cbox_wavebank_get_waveform(p->name, p->sample_dir, l->sample, &error);
377 if (!l->eff_waveform)
379 g_warning("Cannot load waveform %s: %s", l->sample, error ? error->message : "unknown error");
380 g_error_free(error);
383 else
384 l->eff_waveform = NULL;
385 if (oldwf)
386 cbox_waveform_unref(oldwf);
387 l->sample_changed = FALSE;
390 l->eff_freq = (l->eff_waveform && l->eff_waveform->info.samplerate) ? l->eff_waveform->info.samplerate : 44100;
391 // XXXKF should have a distinction between 'configured' and 'effective' loop start/end
392 if (l->loop_mode == slm_unknown)
394 if (l->eff_waveform && l->eff_waveform->has_loop)
395 l->loop_mode = slm_loop_continuous;
396 else
397 l->loop_mode = l->loop_end == 0 ? slm_no_loop : slm_loop_continuous;
400 if (l->loop_mode == slm_one_shot || l->loop_mode == slm_no_loop || l->loop_mode == slm_one_shot_chokeable)
401 l->loop_start = -1;
403 if ((l->loop_mode == slm_loop_continuous || l->loop_mode == slm_loop_sustain) && l->loop_start == -1)
404 l->loop_start = 0;
405 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)
406 l->loop_start = l->eff_waveform->loop_start;
407 if (l->loop_end == 0 && l->eff_waveform != NULL && l->eff_waveform->has_loop)
408 l->loop_end = l->eff_waveform->loop_end;
410 if (l->off_mode == som_unknown)
411 l->off_mode = l->off_by != 0 ? som_fast : som_normal;
413 // if no amp_velcurve_nnn setting, default to quadratic
414 if (l->velcurve_quadratic == -1)
415 l->velcurve_quadratic = 1;
417 if (l->key >= 0 && l->key <= 127)
418 l->lokey = l->hikey = l->pitch_keycenter = l->key;
420 // interpolate missing points in velcurve
421 int start = 0;
422 for (int i = 1; i < 128; i++)
424 if (l->velcurve[i] == -1)
425 continue;
426 float sv = l->velcurve[start];
427 float ev = l->velcurve[i];
428 if (l->velcurve_quadratic)
430 for (int j = start; j <= i; j++)
431 l->eff_velcurve[j] = sv + (ev - sv) * (j - start) * (j - start) / ((i - start) * (i - start));
433 else
435 for (int j = start; j <= i; j++)
436 l->eff_velcurve[j] = sv + (ev - sv) * (j - start) / (i - start);
438 start = i;
440 l->eff_use_keyswitch = ((l->sw_down != -1) || (l->sw_up != -1) || (l->sw_last != -1) || (l->sw_previous != -1));
442 // 'linearize' the virtual circular buffer - write 3 (or N) frames before end of the loop
443 // and 3 (N) frames at the start of the loop, and play it; in rare cases this will need to be
444 // repeated twice if output write pointer is close to CBOX_BLOCK_SIZE or playback rate is very low,
445 // but that's OK.
446 if (l->eff_waveform && l->eff_waveform->preloaded_frames == l->eff_waveform->info.frames)
448 int shift = l->eff_waveform->info.channels == 2 ? 1 : 0;
449 uint32_t halfscratch = MAX_INTERPOLATION_ORDER << shift;
450 memcpy(&l->scratch_loop[0], &l->eff_waveform->data[(l->loop_end - MAX_INTERPOLATION_ORDER) << shift], halfscratch * sizeof(int16_t) );
451 memcpy(&l->scratch_end[0], &l->eff_waveform->data[(l->loop_end - MAX_INTERPOLATION_ORDER) << shift], halfscratch * sizeof(int16_t) );
452 memset(l->scratch_end + halfscratch, 0, halfscratch * sizeof(int16_t));
453 if (l->loop_start != (uint32_t)-1)
454 memcpy(l->scratch_loop + halfscratch, &l->eff_waveform->data[l->loop_start << shift], halfscratch * sizeof(int16_t));
455 else
456 memset(l->scratch_loop + halfscratch, 0, halfscratch * sizeof(int16_t));
460 void sampler_layer_reset_switches(struct sampler_layer *l, struct sampler_module *m)
462 l->last_key = l->data.sw_lokey;
463 l->current_seq_position = l->data.seq_position;
466 struct layer_foreach_struct
468 struct sampler_layer *layer;
469 const char *cfg_section;
472 static void layer_foreach_func(void *user_data, const char *key)
474 if (!strcmp(key, "file"))
475 key = "sample";
476 // import is handled in sampler_load_layer_overrides
477 if (!strcmp(key, "import"))
478 return;
479 struct layer_foreach_struct *lfs = user_data;
480 const char *value = cbox_config_get_string(lfs->cfg_section, key);
481 GError *error = NULL;
482 if (!sampler_layer_apply_param(lfs->layer, key, value, &error))
484 if (error)
485 g_warning("Error '%s', context: %s in section %s", error->message, key, lfs->cfg_section);
486 else
487 g_warning("Unknown sample layer parameter: %s in section %s", key, lfs->cfg_section);
491 void sampler_layer_load_overrides(struct sampler_layer *l, const char *cfg_section)
493 char *imp = cbox_config_get_string(cfg_section, "import");
494 if (imp)
495 sampler_layer_load_overrides(l, imp);
497 struct layer_foreach_struct lfs = {
498 .layer = l,
499 .cfg_section = cfg_section
501 cbox_config_foreach_key(layer_foreach_func, cfg_section, &lfs);
504 struct sampler_layer *sampler_layer_new_from_section(struct sampler_module *m, struct sampler_program *parent_program, const char *cfg_section)
506 struct sampler_layer *l = sampler_layer_new(m, parent_program, NULL);
507 sampler_layer_load_overrides(l, cfg_section);
508 sampler_layer_data_finalize(&l->data, l->parent_group ? &l->parent_group->data : NULL, parent_program);
509 sampler_layer_reset_switches(l, m);
510 return l;
513 static int sfz_note_from_string(const char *note)
515 static const int semis[] = {9, 11, 0, 2, 4, 5, 7};
516 int pos;
517 int nn = tolower(note[0]);
518 int nv;
519 if (nn >= '0' && nn <= '9')
520 return atoi(note);
521 if (nn < 'a' && nn > 'g')
522 return -1;
523 nv = semis[nn - 'a'];
525 for (pos = 1; tolower(note[pos]) == 'b' || note[pos] == '#'; pos++)
526 nv += (note[pos] != '#') ? -1 : +1;
528 if ((note[pos] == '-' && note[pos + 1] == '1' && note[pos + 2] == '\0') || (note[pos] >= '0' && note[pos] <= '9' && note[pos + 1] == '\0'))
530 return nv + 12 * (1 + atoi(note + pos));
533 return -1;
536 static double atof_C(const char *value)
538 return g_ascii_strtod(value, NULL);
541 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)
543 static const enum sampler_modsrc srcs[] = { smsrc_ampenv, smsrc_filenv, smsrc_pitchenv };
544 static const enum sampler_moddest dests[] = { smdest_gain, smdest_cutoff, smdest_pitch };
545 enum sampler_modsrc src = srcs[env_type];
546 enum sampler_moddest dest = dests[env_type];
547 float fvalue = atof_C(value);
549 #define PROC_SET_ENV_FIELD(name, index, def_value) \
550 if (!strcmp(key, #name)) {\
551 env->name = fvalue; \
552 has_fields->name = 1; \
553 return TRUE; \
555 DAHDSR_FIELDS(PROC_SET_ENV_FIELD)
556 if (!strcmp(key, "depth"))
557 sampler_layer_set_modulation1(layer, src, dest, atof_C(value), 0);
558 else if (!strcmp(key, "vel2delay"))
559 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 0, fvalue);
560 else if (!strcmp(key, "vel2attack"))
561 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 1, fvalue);
562 else if (!strcmp(key, "vel2hold"))
563 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 2, fvalue);
564 else if (!strcmp(key, "vel2decay"))
565 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 3, fvalue);
566 else if (!strcmp(key, "vel2sustain"))
567 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 4, fvalue);
568 else if (!strcmp(key, "vel2release"))
569 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 5, fvalue);
570 else if (!strcmp(key, "vel2depth"))
571 sampler_layer_set_modulation(layer, src, smsrc_vel, dest, atof_C(value), 0);
572 else if (!strncmp(key, "depthcc", 7))
574 int cc = atoi(key + 7);
575 if (cc > 0 && cc < 120)
576 sampler_layer_set_modulation(layer, src, cc, dest, fvalue, 0);
577 else
578 return FALSE;
580 else
581 return FALSE;
582 return TRUE;
585 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)
587 static const enum sampler_modsrc srcs[] = { smsrc_amplfo, smsrc_fillfo, smsrc_pitchlfo };
588 static const enum sampler_moddest dests[] = { smdest_gain, smdest_cutoff, smdest_pitch };
589 enum sampler_modsrc src = srcs[lfo_type];
590 enum sampler_moddest dest = dests[lfo_type];
592 #define PROC_SET_LFO_FIELD(name, index, def_value) \
593 if (!strcmp(key, #name)) {\
594 params->name = fvalue; \
595 has_fields->name = 1; \
596 return TRUE; \
598 float fvalue = atof_C(value);
599 LFO_FIELDS(PROC_SET_LFO_FIELD)
600 if (!strcmp(key, "depth"))
601 sampler_layer_set_modulation1(layer, src, dest, fvalue, 0);
602 else if (!strcmp(key, "depthchanaft"))
603 sampler_layer_set_modulation(layer, src, smsrc_chanaft, dest, fvalue, 0);
604 else if (!strcmp(key, "depthpolyaft"))
605 sampler_layer_set_modulation(layer, src, smsrc_polyaft, dest, fvalue, 0);
606 else if (!strncmp(key, "depthcc", 7))
608 int cc = atoi(key + 7);
609 if (cc > 0 && cc < 120)
610 sampler_layer_set_modulation(layer, src, cc, dest, fvalue, 0);
611 else
612 return FALSE;
614 else
615 return FALSE;
616 return TRUE;
619 #define PARSE_PARAM_midi_note_t(field, strname, valuestr) \
620 return ((l->data.field = sfz_note_from_string(value)), (l->data.has_##field = 1));
621 #define PARSE_PARAM_int(field, strname, valuestr) \
622 return ((l->data.field = atoi(value)), (l->data.has_##field = 1));
623 #define PARSE_PARAM_uint32_t(field, strname, valuestr) \
624 return ((l->data.field = (uint32_t)strtoul(value, NULL, 10)), (l->data.has_##field = 1));
625 #define PARSE_PARAM_float(field, strname, valuestr) \
626 return ((l->data.field = atof_C(value)), (l->data.has_##field = 1));
628 #define PROC_APPLY_PARAM(type, name, def_value) \
629 if (!strcmp(key, #name)) { \
630 PARSE_PARAM_##type(name, #name, value) \
632 #define PROC_APPLY_PARAM_string(name) \
633 if (!strcmp(key, #name)) { \
634 if (l->data.name && value && !strcmp(l->data.name, value)) \
635 return (l->data.has_##name = 1); \
636 g_free(l->data.name); \
637 return ((l->data.name = g_strdup(value)), (l->data.name##_changed = 1), (l->data.has_##name = 1)); \
639 #define PROC_APPLY_PARAM_dBamp(type, name, def_value) \
640 if (!strcmp(key, #name)) { \
641 return ((l->data.name = atof_C(value)), (l->data.has_##name = 1)); \
643 #define PROC_APPLY_PARAM_enum(enumtype, name, def_value) \
644 if (!strcmp(key, #name)) { \
645 if (!enumtype##_from_string(value, &l->data.name)) { \
646 g_set_error(error, CBOX_MODULE_ERROR, CBOX_MODULE_ERROR_FAILED, "Value %s is not a correct value for %s", value, #name); \
647 return FALSE; \
649 l->data.has_##name = 1; \
650 return TRUE; \
652 // LFO and envelope need special handling now
653 #define PROC_APPLY_PARAM_dahdsr(name, parname, index) \
654 if (!strncmp(key, #parname "_", sizeof(#parname))) \
655 return parse_envelope_param(l, &l->data.name, &l->data.has_##name, index, key + sizeof(#parname), value);
656 #define PROC_APPLY_PARAM_lfo(name, parname, index) \
657 if (!strncmp(key, #parname "_", sizeof(#parname))) \
658 return parse_lfo_param(l, &l->data.name, &l->data.has_##name, index, key + sizeof(#parname), value);
659 #define PROC_APPLY_PARAM_ccrange(name) /* handled separately in apply_param */
661 static void sampler_layer_apply_unknown(struct sampler_layer *l, const char *key, const char *value)
663 if (!l->unknown_keys)
664 l->unknown_keys = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
666 g_hash_table_insert(l->unknown_keys, g_strdup(key), g_strdup(value));
669 gboolean sampler_layer_apply_param(struct sampler_layer *l, const char *key, const char *value, GError **error)
671 try_now:
672 // XXXKF: this is seriously stupid code, this should use a hash table for
673 // fixed strings, or something else that doesn't explode O(N**2) with
674 // number of attributes. But premature optimization is a root of all evil.
676 SAMPLER_FIXED_FIELDS(PROC_APPLY_PARAM)
678 // XXXKF: to make things worse, some attributes have names different from
679 // C field names, or have multiple names, or don't map 1:1 to internal model
681 if (!strcmp(key, "lolev"))
682 l->data.lovel = atoi(value), l->data.has_lovel = 1;
683 else if (!strcmp(key, "hilev"))
684 l->data.hivel = atoi(value), l->data.has_hivel = 1;
685 else if (!strcmp(key, "benddown"))
686 l->data.bend_down = atoi(value), l->data.has_bend_down = 1;
687 else if (!strcmp(key, "bendup"))
688 l->data.bend_up = atoi(value), l->data.has_bend_up = 1;
689 else if (!strcmp(key, "loopstart"))
690 l->data.loop_start = atoi(value), l->data.has_loop_start = 1;
691 else if (!strcmp(key, "loopend"))
692 l->data.loop_end = atoi(value), l->data.has_loop_end = 1;
693 else if (!strcmp(key, "cutoff_chanaft"))
694 sampler_layer_set_modulation1(l, smsrc_chanaft, smdest_cutoff, atof_C(value), 0);
695 else if (!strcmp(key, "amp_random"))
696 sampler_layer_add_nif(l, sampler_nif_addrandom, 0, atof_C(value));
697 else if (!strcmp(key, "fil_random"))
698 sampler_layer_add_nif(l, sampler_nif_addrandom, 1, atof_C(value));
699 else if (!strcmp(key, "pitch_random"))
700 sampler_layer_add_nif(l, sampler_nif_addrandom, 2, atof_C(value));
701 else if (!strcmp(key, "pitch_veltrack"))
702 sampler_layer_add_nif(l, sampler_nif_vel2pitch, 0, atof_C(value));
703 else if (!strncmp(key, "delay_cc", 8))
705 int ccno = atoi(key + 8);
706 if (ccno > 0 && ccno < 120)
707 sampler_layer_add_nif(l, sampler_nif_cc2delay, ccno, atof_C(value));
708 else
709 goto unknown_key;
711 else if (!strncmp(key, "cutoff_cc", 9))
713 int ccno = atoi(key + 9);
714 if (ccno > 0 && ccno < 120)
715 sampler_layer_set_modulation1(l, ccno, smdest_cutoff, atof_C(value), 0);
716 else
717 goto unknown_key;
719 else if (!strncmp(key, "gain_cc", 7))
721 int ccno = atoi(key + 7);
722 if (ccno > 0 && ccno < 120)
723 sampler_layer_set_modulation1(l, ccno, smdest_gain, atof_C(value), 0);
724 else
725 goto unknown_key;
727 else if (!strncmp(key, "amp_velcurve_", 13))
729 // if not known yet, set to 0, it can always be overriden via velcurve_quadratic setting
730 if (l->data.velcurve_quadratic == -1)
731 l->data.velcurve_quadratic = 0;
732 int point = atoi(key + 13);
733 if (point >= 0 && point <= 127)
735 l->data.velcurve[point] = atof_C(value);
736 if (l->data.velcurve[point] < 0)
737 l->data.velcurve[point] = 0;
738 if (l->data.velcurve[point] > 1)
739 l->data.velcurve[point] = 1;
741 else
742 goto unknown_key;
744 else if (!strncmp(key, "on_locc", 7) || !strncmp(key, "on_hicc", 7))
746 int cc = atoi(key + 7);
747 if (cc > 0 && cc < 120)
749 if (*value)
751 l->data.on_cc_number = cc;
752 if (key[3] == 'l')
754 l->data.on_locc = atoi(value);
755 l->data.has_on_locc = TRUE;
757 else
759 l->data.on_hicc = atoi(value);
760 l->data.has_on_hicc = TRUE;
763 else
765 l->data.on_cc_number = -1;
766 l->data.has_on_locc = FALSE;
767 l->data.has_on_hicc = FALSE;
770 else
771 return FALSE;
773 else if (!strncmp(key, "locc", 4) || !strncmp(key, "hicc", 4))
775 int cc = atoi(key + 4);
776 if (cc > 0 && cc < 120)
778 if (*value)
780 l->data.cc_number = cc;
781 if (key[0] == 'l')
783 l->data.locc = atoi(value);
784 l->data.has_locc = TRUE;
786 else
788 l->data.hicc = atoi(value);
789 l->data.has_hicc = TRUE;
792 else
794 l->data.cc_number = -1;
795 l->data.has_locc = FALSE;
796 l->data.has_hicc = FALSE;
799 else
800 return FALSE;
802 else if (!strcmp(key, "loopmode"))
804 key = "loop_mode";
805 goto try_now; // yes, goto, why not?
807 else if (!strcmp(key, "offby"))
809 key = "off_by";
810 goto try_now;
812 else
813 goto unknown_key;
815 return TRUE;
816 unknown_key:
817 sampler_layer_apply_unknown(l, key, value);
818 g_warning("Unknown SFZ property key: '%s'", key);
819 return TRUE;
822 #define TYPE_PRINTF_uint32_t(name, def_value) \
823 if (show_inherited || l->has_##name) \
824 g_string_append_printf(outstr, " %s=%u", #name, (unsigned)(l->name));
825 #define TYPE_PRINTF_int(name, def_value) \
826 if (show_inherited || l->has_##name) \
827 g_string_append_printf(outstr, " %s=%d", #name, (int)(l->name));
828 #define TYPE_PRINTF_midi_note_t(name, def_value) \
829 if (show_inherited || l->has_##name) { \
830 int val = l->name; \
831 if (val == -1) \
832 g_string_append_printf(outstr, " %s=-1", #name); \
833 else \
834 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)); \
835 } else {}
836 #define TYPE_PRINTF_float(name, def_value) \
837 if (show_inherited || l->has_##name) \
838 g_string_append_printf(outstr, " %s=%s", #name, g_ascii_dtostr(floatbuf, floatbufsize, l->name));
840 #define PROC_FIELDS_TO_FILEPTR(type, name, def_value) \
841 TYPE_PRINTF_##type(name, def_value)
842 #define PROC_FIELDS_TO_FILEPTR_string(name) \
843 if (show_inherited || l->has_##name) \
844 g_string_append_printf(outstr, " %s=%s", #name, l->name ? l->name : "");
845 #define PROC_FIELDS_TO_FILEPTR_dBamp(type, name, def_value) \
846 if (show_inherited || l->has_##name) \
847 g_string_append_printf(outstr, " %s=%s", #name, g_ascii_dtostr(floatbuf, floatbufsize, l->name));
848 #define PROC_FIELDS_TO_FILEPTR_enum(enumtype, name, def_value) \
849 if ((show_inherited || l->has_##name) && (tmpstr = enumtype##_to_string(l->name)) != NULL) \
850 g_string_append_printf(outstr, " %s=%s", #name, tmpstr);
852 #define ENV_PARAM_OUTPUT(param, index, def_value, env, envfield, envname) \
853 if (show_inherited || l->has_##envfield.param) \
854 g_string_append_printf(outstr, " " #envname "_" #param "=%s", g_ascii_dtostr(floatbuf, floatbufsize, env.param));
856 #define PROC_FIELDS_TO_FILEPTR_dahdsr(name, parname, index) \
857 DAHDSR_FIELDS(ENV_PARAM_OUTPUT, l->name, name, parname)
858 #define PROC_FIELDS_TO_FILEPTR_lfo(name, parname, index) \
859 LFO_FIELDS(ENV_PARAM_OUTPUT, l->name, name, parname)
860 #define PROC_FIELDS_TO_FILEPTR_ccrange(name) \
861 if (l->has_##name##locc) \
862 g_string_append_printf(outstr, " " #name "locc%d=%d", l->name##cc_number, l->name##locc); \
863 if (l->has_##name##hicc) \
864 g_string_append_printf(outstr, " " #name "hicc%d=%d", l->name##cc_number, l->name##hicc);
866 gchar *sampler_layer_to_string(struct sampler_layer *lr, gboolean show_inherited)
868 struct sampler_layer_data *l = &lr->data;
869 GString *outstr = g_string_sized_new(200);
870 const char *tmpstr;
871 char floatbuf[G_ASCII_DTOSTR_BUF_SIZE];
872 int floatbufsize = G_ASCII_DTOSTR_BUF_SIZE;
873 SAMPLER_FIXED_FIELDS(PROC_FIELDS_TO_FILEPTR)
875 static const char *addrandom_variants[] = { "amp", "fil", "pitch" };
876 static const char *modsrc_names[] = { "chanaft", "vel", "polyaft", "pitch", "pitcheg", "fileg", "ampeg", "pitchlfo", "fillfo", "amplfo", "" };
877 static const char *moddest_names[] = { "gain", "pitch", "cutoff", "resonance" };
878 for(GSList *nif = l->nifs; nif; nif = nif->next)
880 struct sampler_noteinitfunc *nd = nif->data;
881 if (!nd->has_value && !show_inherited)
882 continue;
883 #define PROC_ENVSTAGE_NAME(name, index, def_value) #name,
884 static const char *env_stages[] = { DAHDSR_FIELDS(PROC_ENVSTAGE_NAME) };
885 int v = nd->variant;
886 g_ascii_dtostr(floatbuf, floatbufsize, nd->param);
888 if (nd->notefunc == sampler_nif_addrandom && v >= 0 && v <= 2)
889 g_string_append_printf(outstr, " %s_random=%s", addrandom_variants[nd->variant], floatbuf);
890 else if (nd->notefunc == sampler_nif_vel2pitch)
891 g_string_append_printf(outstr, " pitch_veltrack=%s", floatbuf);
892 else if (nd->notefunc == sampler_nif_cc2delay && v >= 0 && v < 120)
893 g_string_append_printf(outstr, " delay_cc%d=%s", nd->variant, floatbuf);
894 else if (nd->notefunc == sampler_nif_vel2env && v >= 0 && (v & 15) < 6 && (v >> 4) < 3)
895 g_string_append_printf(outstr, " %seg_vel2%s=%s", addrandom_variants[nd->variant >> 4], env_stages[1 + (v & 15)], floatbuf);
897 for(GSList *mod = l->modulations; mod; mod = mod->next)
899 struct sampler_modulation *md = mod->data;
900 if (!md->has_value && !show_inherited)
901 continue;
902 g_ascii_dtostr(floatbuf, floatbufsize, md->amount);
904 if (md->src2 == smsrc_none)
906 if (md->src < 120)
908 g_string_append_printf(outstr, " %s_cc%d=%s", moddest_names[md->dest], md->src, floatbuf);
909 continue;
911 if (md->src < 120 + sizeof(modsrc_names) / sizeof(modsrc_names[0]))
913 if ((md->src == smsrc_filenv && md->dest == smdest_cutoff) ||
914 (md->src == smsrc_pitchenv && md->dest == smdest_pitch))
915 g_string_append_printf(outstr, " %s_depth=%s", modsrc_names[md->src - 120], floatbuf);
916 else
917 g_string_append_printf(outstr, " %s_%s=%s", moddest_names[md->dest], modsrc_names[md->src - 120], floatbuf);
918 continue;
921 if ((md->src == smsrc_amplfo && md->dest == smdest_gain) ||
922 (md->src == smsrc_fillfo && md->dest == smdest_cutoff) ||
923 (md->src == smsrc_pitchlfo && md->dest == smdest_pitch))
925 switch(md->src2)
927 case smsrc_chanaft:
928 case smsrc_polyaft:
929 g_string_append_printf(outstr, " %slfo_depth%s=%s", moddest_names[md->dest], modsrc_names[md->src2 - 120], floatbuf);
930 continue;
931 default:
932 if (md->src2 < 120)
934 g_string_append_printf(outstr, " %slfo_depthcc%d=%s", moddest_names[md->dest], md->src2, floatbuf);
935 continue;
937 break;
939 break;
941 if ((md->src == smsrc_ampenv && md->dest == smdest_gain) ||
942 (md->src == smsrc_filenv && md->dest == smdest_cutoff) ||
943 (md->src == smsrc_pitchenv && md->dest == smdest_pitch))
945 if (md->src2 == smsrc_vel)
947 g_string_append_printf(outstr, " %seg_vel2depth=%s", moddest_names[md->dest], floatbuf);
948 continue;
950 if (md->src2 < 120)
952 g_string_append_printf(outstr, " %s_depthcc%d=%s", modsrc_names[md->src - 120], md->src2, floatbuf);
953 continue;
956 g_string_append_printf(outstr, " genericmod_from_%d_and_%d_to_%d=%s", md->src, md->src2, md->dest, floatbuf);
959 if (lr->unknown_keys)
961 GHashTableIter hti;
962 gchar *key, *value;
963 g_hash_table_iter_init(&hti, lr->unknown_keys);
964 while(g_hash_table_iter_next(&hti, (gpointer *)&key, (gpointer *)&value))
965 g_string_append_printf(outstr, " %s=%s", key, value);
968 gchar *res = outstr->str;
969 g_string_free(outstr, FALSE);
970 return res;
973 void sampler_layer_dump(struct sampler_layer *l, FILE *f)
975 gchar *str = sampler_layer_to_string(l, FALSE);
976 fprintf(f, "%s\n", str);
979 void sampler_layer_data_close(struct sampler_layer_data *l)
981 g_slist_free_full(l->nifs, g_free);
982 g_slist_free_full(l->modulations, g_free);
983 if (l->eff_waveform)
985 cbox_waveform_unref(l->eff_waveform);
986 l->eff_waveform = NULL;
988 g_free(l->sample);
991 void sampler_layer_data_destroy(struct sampler_layer_data *l)
993 sampler_layer_data_close(l);
994 free(l);
997 void sampler_layer_destroyfunc(struct cbox_objhdr *objhdr)
999 struct sampler_layer *l = CBOX_H2O(objhdr);
1000 struct sampler_program *prg = l->parent_program;
1001 assert(g_hash_table_size(l->child_layers) == 0);
1003 if (l->parent_group)
1005 g_hash_table_remove(l->parent_group->child_layers, l);
1006 if (prg && prg->rll)
1008 sampler_program_delete_layer(prg, l);
1009 sampler_program_update_layers(l->parent_program);
1011 l->parent_group = NULL;
1013 sampler_layer_data_close(&l->data);
1014 if (l->runtime)
1015 sampler_layer_data_destroy(l->runtime);
1016 if (l->unknown_keys)
1017 g_hash_table_destroy(l->unknown_keys);
1018 if (l->child_layers)
1019 g_hash_table_destroy(l->child_layers);
1021 free(l);
1024 //////////////////////////////////////////////////////////////////////////
1026 struct sampler_layer_update_cmd
1028 struct sampler_module *module;
1029 struct sampler_layer *layer;
1030 struct sampler_layer_data *new_data;
1031 struct sampler_layer_data *old_data;
1034 static int sampler_layer_update_cmd_prepare(void *data)
1036 struct sampler_layer_update_cmd *cmd = data;
1037 cmd->old_data = cmd->layer->runtime;
1038 cmd->new_data = calloc(1, sizeof(struct sampler_layer_data));
1040 sampler_layer_data_clone(cmd->new_data, &cmd->layer->data, TRUE);
1041 sampler_layer_data_finalize(cmd->new_data, cmd->layer->parent_group ? &cmd->layer->parent_group->data : NULL, cmd->layer->parent_program);
1042 if (cmd->layer->runtime == NULL)
1044 // initial update of the layer, so none of the voices need updating yet
1045 // because the layer hasn't been allocated to any voice
1046 cmd->layer->runtime = cmd->new_data;
1047 return 1;
1049 return 0;
1052 static int sampler_layer_update_cmd_execute(void *data)
1054 struct sampler_layer_update_cmd *cmd = data;
1056 for (int i = 0; i < 16; i++)
1058 FOREACH_VOICE(cmd->module->channels[i].voices_running, v)
1060 if (v->layer == cmd->old_data)
1061 v->layer = cmd->new_data;
1064 cmd->layer->runtime = cmd->new_data;
1065 return 10;
1068 static void sampler_layer_update_cmd_cleanup(void *data)
1070 struct sampler_layer_update_cmd *cmd = data;
1072 sampler_layer_data_destroy(cmd->old_data);
1075 void sampler_layer_update(struct sampler_layer *l)
1077 // if changing a group, update all child regions instead
1078 if (g_hash_table_size(l->child_layers))
1080 GHashTableIter iter;
1081 g_hash_table_iter_init(&iter, l->child_layers);
1082 gpointer key, value;
1083 while(g_hash_table_iter_next(&iter, &key, &value))
1085 sampler_layer_data_finalize(&((struct sampler_layer *)key)->data, &l->data, l->parent_program);
1086 sampler_layer_update((struct sampler_layer *)key);
1088 return;
1090 static struct cbox_rt_cmd_definition rtcmd = {
1091 .prepare = sampler_layer_update_cmd_prepare,
1092 .execute = sampler_layer_update_cmd_execute,
1093 .cleanup = sampler_layer_update_cmd_cleanup,
1096 struct sampler_layer_update_cmd lcmd;
1097 lcmd.module = l->module;
1098 lcmd.layer = l;
1099 lcmd.new_data = NULL;
1100 lcmd.old_data = NULL;
1102 // In order to be able to use the async call, it would be necessary to
1103 // identify old data by layer pointer, not layer data pointer. For now,
1104 // it might be good enough to just use sync calls for this.
1105 cbox_rt_execute_cmd_sync(l->module->module.rt, &rtcmd, &lcmd);