Attempt to scale current position according to changes in envelope stage times.
[calfbox.git] / sampler_layer.c
blob4370a33863e55628d2d9b0edf7dc689fd2ad7a56
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_eq(name, parname, index) \
198 EQ_FIELDS(PROC_SUBSTRUCT_RESET_FIELD, name, ld); \
199 EQ_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, ld)
200 #define PROC_FIELDS_INITIALISER_ccrange(name) \
201 ld->name##locc = 0; \
202 ld->name##hicc = 127; \
203 ld->name##cc_number = 0; \
204 ld->has_##name##locc = 0; \
205 ld->has_##name##hicc = 0;
207 CBOX_CLASS_DEFINITION_ROOT(sampler_layer)
209 struct sampler_layer *sampler_layer_new(struct sampler_module *m, struct sampler_program *parent_program, struct sampler_layer *parent_group)
211 struct sampler_layer *l = calloc(1, sizeof(struct sampler_layer));
212 struct cbox_document *doc = CBOX_GET_DOCUMENT(parent_program);
213 memset(l, 0, sizeof(struct sampler_layer));
214 CBOX_OBJECT_HEADER_INIT(l, sampler_layer, doc);
215 cbox_command_target_init(&l->cmd_target, sampler_layer_process_cmd, l);
217 l->module = m;
218 l->child_layers = g_hash_table_new(NULL, NULL);
219 if (parent_group)
221 sampler_layer_data_clone(&l->data, &parent_group->data, FALSE);
222 l->parent_program = parent_program;
223 l->parent_group = parent_group;
224 g_hash_table_replace(parent_group->child_layers, l, l);
225 l->runtime = NULL;
226 CBOX_OBJECT_REGISTER(l);
227 return l;
229 l->parent_program = parent_program;
231 struct sampler_layer_data *ld = &l->data;
232 SAMPLER_FIXED_FIELDS(PROC_FIELDS_INITIALISER)
234 ld->eff_waveform = NULL;
235 ld->eff_freq = 44100;
236 ld->velcurve[0] = 0;
237 ld->velcurve[127] = 1;
238 for (int i = 1; i < 127; i++)
239 ld->velcurve[i] = -1;
240 ld->modulations = NULL;
241 ld->nifs = NULL;
242 ld->on_locc = 0;
243 ld->on_hicc = 127;
244 ld->on_cc_number = -1;
246 ld->eff_use_keyswitch = 0;
247 l->last_key = -1;
248 if (!parent_group)
250 sampler_layer_set_modulation1(l, 74, smdest_cutoff, 9600, 2);
251 sampler_layer_set_modulation1(l, 71, smdest_resonance, 12, 2);
252 sampler_layer_set_modulation(l, smsrc_pitchlfo, 1, smdest_pitch, 100, 0);
254 l->runtime = NULL;
255 l->unknown_keys = NULL;
256 CBOX_OBJECT_REGISTER(l);
257 return l;
260 #define PROC_FIELDS_CLONE(type, name, def_value) \
261 dst->name = src->name; \
262 dst->has_##name = copy_hasattr ? src->has_##name : FALSE;
263 #define PROC_FIELDS_CLONE_string(name) \
264 dst->name = src->name ? g_strdup(src->name) : NULL; \
265 dst->name##_changed = src->name##_changed; \
266 dst->has_##name = copy_hasattr ? src->has_##name : FALSE;
267 #define PROC_FIELDS_CLONE_dBamp PROC_FIELDS_CLONE
268 #define PROC_FIELDS_CLONE_enum PROC_FIELDS_CLONE
269 #define PROC_FIELDS_CLONE_dahdsr(name, parname, index) \
270 DAHDSR_FIELDS(PROC_SUBSTRUCT_CLONE, name, dst, src) \
271 if (!copy_hasattr) \
272 DAHDSR_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, dst)
273 #define PROC_FIELDS_CLONE_lfo(name, parname, index) \
274 LFO_FIELDS(PROC_SUBSTRUCT_CLONE, name, dst, src) \
275 if (!copy_hasattr) \
276 LFO_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, dst)
277 #define PROC_FIELDS_CLONE_eq(name, parname, index) \
278 EQ_FIELDS(PROC_SUBSTRUCT_CLONE, name, dst, src) \
279 if (!copy_hasattr) \
280 EQ_FIELDS(PROC_SUBSTRUCT_RESET_HAS_FIELD, name, dst)
281 #define PROC_FIELDS_CLONE_ccrange(name) \
282 dst->name##locc = src->name##locc; \
283 dst->name##hicc = src->name##hicc; \
284 dst->name##cc_number = src->name##cc_number; \
285 dst->has_##name##locc = copy_hasattr ? src->has_##name##locc : FALSE; \
286 dst->has_##name##hicc = copy_hasattr ? src->has_##name##hicc : FALSE;
288 void sampler_layer_data_clone(struct sampler_layer_data *dst, const struct sampler_layer_data *src, gboolean copy_hasattr)
290 SAMPLER_FIXED_FIELDS(PROC_FIELDS_CLONE)
291 memcpy(dst->velcurve, src->velcurve, 128 * sizeof(float));
292 dst->modulations = g_slist_copy(src->modulations);
293 for(GSList *mod = dst->modulations; mod; mod = mod->next)
295 struct sampler_modulation *srcm = mod->data;
296 struct sampler_modulation *dstm = g_malloc(sizeof(struct sampler_modulation));
297 memcpy(dstm, srcm, sizeof(struct sampler_modulation));
298 dstm->has_value = copy_hasattr ? srcm->has_value : FALSE;
299 mod->data = dstm;
301 dst->nifs = g_slist_copy(src->nifs);
302 for(GSList *nif = dst->nifs; nif; nif = nif->next)
304 struct sampler_noteinitfunc *dstn = g_malloc(sizeof(struct sampler_noteinitfunc));
305 struct sampler_noteinitfunc *srcn = nif->data;
306 memcpy(dstn, srcn, sizeof(struct sampler_noteinitfunc));
307 dstn->has_value = copy_hasattr ? srcn->has_value : FALSE;
308 nif->data = dstn;
310 dst->eff_waveform = src->eff_waveform;
311 if (dst->eff_waveform)
312 cbox_waveform_ref(dst->eff_waveform);
315 #define PROC_FIELDS_CLONEPARENT(type, name, def_value) \
316 if (!l->has_##name) \
317 l->name = parent ? parent->name : def_value;
318 #define PROC_FIELDS_CLONEPARENT_string(name) \
319 if (!l->has_##name && (!l->name || !parent->name || strcmp(l->name, parent->name))) { \
320 g_free(l->name); \
321 l->name = parent && parent->name ? g_strdup(parent->name) : NULL; \
322 l->name##_changed = parent && parent->name##_changed; \
324 #define PROC_FIELDS_CLONEPARENT_dBamp PROC_FIELDS_CLONEPARENT
325 #define PROC_FIELDS_CLONEPARENT_enum PROC_FIELDS_CLONEPARENT
326 #define PROC_FIELDS_CLONEPARENT_dahdsr(name, parname, index) \
327 DAHDSR_FIELDS(PROC_SUBSTRUCT_CLONEPARENT, name, l)
328 #define PROC_FIELDS_CLONEPARENT_lfo(name, parname, index) \
329 LFO_FIELDS(PROC_SUBSTRUCT_CLONEPARENT, name, l)
330 #define PROC_FIELDS_CLONEPARENT_eq(name, parname, index) \
331 EQ_FIELDS(PROC_SUBSTRUCT_CLONEPARENT, name, l)
332 #define PROC_FIELDS_CLONEPARENT_ccrange(name) \
333 if (!l->has_##name##locc) \
334 l->name##locc = parent ? parent->name##locc : 0; \
335 if (!l->has_##name##hicc) \
336 l->name##hicc = parent ? parent->name##hicc : 127; \
337 if (!l->has_##name##locc && !l->has_##name##hicc) \
338 l->name##cc_number = parent ? parent->name##cc_number : -1;
340 static void sampler_layer_data_getdefaults(struct sampler_layer_data *l, struct sampler_layer_data *parent)
342 SAMPLER_FIXED_FIELDS(PROC_FIELDS_CLONEPARENT)
343 // XXXKF: add handling for velcurve
344 if (parent)
346 // set NIFs used by parent
347 for(GSList *mod = parent->nifs; mod; mod = mod->next)
349 struct sampler_noteinitfunc *nif = mod->data;
350 sampler_layer_data_add_nif(l, nif->notefunc, nif->variant, nif->param, TRUE);
352 // set modulations used by parent
353 for(GSList *mod = parent->modulations; mod; mod = mod->next)
355 struct sampler_modulation *srcm = mod->data;
356 sampler_layer_data_set_modulation(l, srcm->src, srcm->src2, srcm->dest, srcm->amount, srcm->flags, TRUE);
361 #define PROC_FIELDS_FINALISER(type, name, def_value)
362 #define PROC_FIELDS_FINALISER_string(name)
363 #define PROC_FIELDS_FINALISER_enum(type, name, def_value)
364 #define PROC_FIELDS_FINALISER_dBamp(type, name, def_value) \
365 l->name##_linearized = dB2gain(l->name);
366 #define PROC_FIELDS_FINALISER_dahdsr(name, parname, index) \
367 cbox_envelope_init_dahdsr(&l->name##_shape, &l->name, m->module.srate / CBOX_BLOCK_SIZE, 100.f, &l->name##_shape == &l->amp_env_shape);
368 #define PROC_FIELDS_FINALISER_lfo(name, parname, index) /* no finaliser required */
369 #define PROC_FIELDS_FINALISER_eq(name, parname, index) l->name.effective_freq = (l->name.freq ? l->name.freq : 5 * powf(10.f, 1 + (index)));
370 #define PROC_FIELDS_FINALISER_ccrange(name) /* no finaliser required */
372 void sampler_layer_data_finalize(struct sampler_layer_data *l, struct sampler_layer_data *parent, struct sampler_program *p)
374 struct sampler_module *m = p->module;
375 SAMPLER_FIXED_FIELDS(PROC_FIELDS_FINALISER)
377 sampler_layer_data_getdefaults(l, parent);
379 // Handle change of sample in the prent group without override on region level
380 if (parent && (l->sample_changed || parent->sample_changed))
382 struct cbox_waveform *oldwf = l->eff_waveform;
383 if (l->sample && *l->sample)
385 GError *error = NULL;
386 l->eff_waveform = cbox_wavebank_get_waveform(p->name, p->tarfile, p->sample_dir, l->sample, &error);
387 if (!l->eff_waveform)
389 g_warning("Cannot load waveform %s: %s", l->sample, error ? error->message : "unknown error");
390 g_error_free(error);
393 else
394 l->eff_waveform = NULL;
395 if (oldwf)
396 cbox_waveform_unref(oldwf);
397 l->sample_changed = FALSE;
400 l->eff_freq = (l->eff_waveform && l->eff_waveform->info.samplerate) ? l->eff_waveform->info.samplerate : 44100;
401 // XXXKF should have a distinction between 'configured' and 'effective' loop start/end
402 if (l->loop_mode == slm_unknown)
404 if (l->eff_waveform && l->eff_waveform->has_loop)
405 l->loop_mode = slm_loop_continuous;
406 else
407 l->loop_mode = l->loop_end == 0 ? slm_no_loop : slm_loop_continuous;
410 if (l->loop_mode == slm_one_shot || l->loop_mode == slm_no_loop || l->loop_mode == slm_one_shot_chokeable)
411 l->loop_start = -1;
413 if ((l->loop_mode == slm_loop_continuous || l->loop_mode == slm_loop_sustain) && l->loop_start == -1)
414 l->loop_start = 0;
415 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)
416 l->loop_start = l->eff_waveform->loop_start;
417 if (l->loop_end == 0 && l->eff_waveform != NULL && l->eff_waveform->has_loop)
418 l->loop_end = l->eff_waveform->loop_end;
420 if (l->off_mode == som_unknown)
421 l->off_mode = l->off_by != 0 ? som_fast : som_normal;
423 // if no amp_velcurve_nnn setting, default to quadratic
424 if (l->velcurve_quadratic == -1)
425 l->velcurve_quadratic = 1;
427 if (l->key >= 0 && l->key <= 127)
428 l->lokey = l->hikey = l->pitch_keycenter = l->key;
430 // interpolate missing points in velcurve
431 int start = 0;
432 for (int i = 1; i < 128; i++)
434 if (l->velcurve[i] == -1)
435 continue;
436 float sv = l->velcurve[start];
437 float ev = l->velcurve[i];
438 if (l->velcurve_quadratic)
440 for (int j = start; j <= i; j++)
441 l->eff_velcurve[j] = sv + (ev - sv) * (j - start) * (j - start) / ((i - start) * (i - start));
443 else
445 for (int j = start; j <= i; j++)
446 l->eff_velcurve[j] = sv + (ev - sv) * (j - start) / (i - start);
448 start = i;
450 l->eff_use_keyswitch = ((l->sw_down != -1) || (l->sw_up != -1) || (l->sw_last != -1) || (l->sw_previous != -1));
452 // 'linearize' the virtual circular buffer - write 3 (or N) frames before end of the loop
453 // and 3 (N) frames at the start of the loop, and play it; in rare cases this will need to be
454 // repeated twice if output write pointer is close to CBOX_BLOCK_SIZE or playback rate is very low,
455 // but that's OK.
456 if (l->eff_waveform && l->eff_waveform->preloaded_frames == l->eff_waveform->info.frames)
458 int shift = l->eff_waveform->info.channels == 2 ? 1 : 0;
459 uint32_t halfscratch = MAX_INTERPOLATION_ORDER << shift;
460 memcpy(&l->scratch_loop[0], &l->eff_waveform->data[(l->loop_end - MAX_INTERPOLATION_ORDER) << shift], halfscratch * sizeof(int16_t) );
461 memcpy(&l->scratch_end[0], &l->eff_waveform->data[(l->loop_end - MAX_INTERPOLATION_ORDER) << shift], halfscratch * sizeof(int16_t) );
462 memset(l->scratch_end + halfscratch, 0, halfscratch * sizeof(int16_t));
463 if (l->loop_start != (uint32_t)-1)
464 memcpy(l->scratch_loop + halfscratch, &l->eff_waveform->data[l->loop_start << shift], halfscratch * sizeof(int16_t));
465 else
466 memset(l->scratch_loop + halfscratch, 0, halfscratch * sizeof(int16_t));
468 if (sampler_layer_data_is_4pole(l))
469 l->resonance_scaled = sqrtf(l->resonance_linearized / 0.707f) * 0.5f;
470 else
471 l->resonance_scaled = l->resonance_linearized;
472 if (l->cutoff < 20)
473 l->logcutoff = -1;
474 else
475 l->logcutoff = 1200.0 * log(l->cutoff / 440.0) / log(2) + 5700.0;
477 l->eq_bitmask = ((l->eq1.gain != 0 || l->eq1.vel2gain != 0) ? 1 : 0)
478 | ((l->eq2.gain != 0 || l->eq2.vel2gain != 0) ? 2 : 0)
479 | ((l->eq3.gain != 0 || l->eq3.vel2gain != 0) ? 4 : 0);
482 void sampler_layer_reset_switches(struct sampler_layer *l, struct sampler_module *m)
484 l->last_key = l->data.sw_lokey;
485 l->current_seq_position = l->data.seq_position;
488 struct layer_foreach_struct
490 struct sampler_layer *layer;
491 const char *cfg_section;
494 static void layer_foreach_func(void *user_data, const char *key)
496 if (!strcmp(key, "file"))
497 key = "sample";
498 // import is handled in sampler_load_layer_overrides
499 if (!strcmp(key, "import"))
500 return;
501 // layer%d should be ignored, it's handled by sampler_program_new_from_cfg
502 if (!strncmp(key, "layer", 5) && isdigit(key[5]))
503 return;
504 struct layer_foreach_struct *lfs = user_data;
505 const char *value = cbox_config_get_string(lfs->cfg_section, key);
506 GError *error = NULL;
507 if (!sampler_layer_apply_param(lfs->layer, key, value, &error))
509 if (error)
510 g_warning("Error '%s', context: %s in section %s", error->message, key, lfs->cfg_section);
511 else
512 g_warning("Unknown sample layer parameter: %s in section %s", key, lfs->cfg_section);
516 void sampler_layer_load_overrides(struct sampler_layer *l, const char *cfg_section)
518 char *imp = cbox_config_get_string(cfg_section, "import");
519 if (imp)
520 sampler_layer_load_overrides(l, imp);
522 struct layer_foreach_struct lfs = {
523 .layer = l,
524 .cfg_section = cfg_section
526 cbox_config_foreach_key(layer_foreach_func, cfg_section, &lfs);
529 struct sampler_layer *sampler_layer_new_from_section(struct sampler_module *m, struct sampler_program *parent_program, struct sampler_layer *parent_group, const char *cfg_section)
531 struct sampler_layer *l = sampler_layer_new(m, parent_program, parent_group ? parent_group : parent_program->default_group);
532 sampler_layer_load_overrides(l, cfg_section);
533 sampler_layer_data_finalize(&l->data, l->parent_group ? &l->parent_group->data : NULL, parent_program);
534 sampler_layer_reset_switches(l, m);
535 return l;
538 static int sfz_note_from_string(const char *note)
540 static const int semis[] = {9, 11, 0, 2, 4, 5, 7};
541 int pos;
542 int nn = tolower(note[0]);
543 int nv;
544 if (nn >= '0' && nn <= '9')
545 return atoi(note);
546 if (nn < 'a' && nn > 'g')
547 return -1;
548 nv = semis[nn - 'a'];
550 for (pos = 1; tolower(note[pos]) == 'b' || note[pos] == '#'; pos++)
551 nv += (note[pos] != '#') ? -1 : +1;
553 if ((note[pos] == '-' && note[pos + 1] == '1' && note[pos + 2] == '\0') || (note[pos] >= '0' && note[pos] <= '9' && note[pos + 1] == '\0'))
555 return nv + 12 * (1 + atoi(note + pos));
558 return -1;
561 static double atof_C(const char *value)
563 return g_ascii_strtod(value, NULL);
566 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)
568 static const enum sampler_modsrc srcs[] = { smsrc_ampenv, smsrc_filenv, smsrc_pitchenv };
569 static const enum sampler_moddest dests[] = { smdest_gain, smdest_cutoff, smdest_pitch };
570 enum sampler_modsrc src = srcs[env_type];
571 enum sampler_moddest dest = dests[env_type];
572 float fvalue = atof_C(value);
574 #define PROC_SET_ENV_FIELD(name, index, def_value) \
575 if (!strcmp(key, #name)) {\
576 env->name = fvalue; \
577 has_fields->name = 1; \
578 return TRUE; \
580 DAHDSR_FIELDS(PROC_SET_ENV_FIELD)
581 if (!strcmp(key, "depth"))
582 sampler_layer_set_modulation1(layer, src, dest, atof_C(value), 0);
583 else if (!strcmp(key, "vel2delay"))
584 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 0, fvalue);
585 else if (!strcmp(key, "vel2attack"))
586 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 1, fvalue);
587 else if (!strcmp(key, "vel2hold"))
588 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 2, fvalue);
589 else if (!strcmp(key, "vel2decay"))
590 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 3, fvalue);
591 else if (!strcmp(key, "vel2sustain"))
592 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 4, fvalue);
593 else if (!strcmp(key, "vel2release"))
594 sampler_layer_add_nif(layer, sampler_nif_vel2env, (env_type << 4) + 5, fvalue);
595 else if (!strcmp(key, "vel2depth"))
596 sampler_layer_set_modulation(layer, src, smsrc_vel, dest, atof_C(value), 0);
597 else if (!strncmp(key, "depthcc", 7))
599 int cc = atoi(key + 7);
600 if (cc > 0 && cc < 120)
601 sampler_layer_set_modulation(layer, src, cc, dest, fvalue, 0);
602 else
603 return FALSE;
605 else
606 return FALSE;
607 return TRUE;
610 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)
612 static const enum sampler_modsrc srcs[] = { smsrc_amplfo, smsrc_fillfo, smsrc_pitchlfo };
613 static const enum sampler_moddest dests[] = { smdest_gain, smdest_cutoff, smdest_pitch };
614 enum sampler_modsrc src = srcs[lfo_type];
615 enum sampler_moddest dest = dests[lfo_type];
617 #define PROC_SET_LFO_FIELD(name, index, def_value) \
618 if (!strcmp(key, #name)) {\
619 params->name = fvalue; \
620 has_fields->name = 1; \
621 return TRUE; \
623 float fvalue = atof_C(value);
624 LFO_FIELDS(PROC_SET_LFO_FIELD)
625 if (!strcmp(key, "depth"))
626 sampler_layer_set_modulation1(layer, src, dest, fvalue, 0);
627 else if (!strcmp(key, "depthchanaft"))
628 sampler_layer_set_modulation(layer, src, smsrc_chanaft, dest, fvalue, 0);
629 else if (!strcmp(key, "depthpolyaft"))
630 sampler_layer_set_modulation(layer, src, smsrc_polyaft, dest, fvalue, 0);
631 else if (!strncmp(key, "depthcc", 7))
633 int cc = atoi(key + 7);
634 if (cc > 0 && cc < 120)
635 sampler_layer_set_modulation(layer, src, cc, dest, fvalue, 0);
636 else
637 return FALSE;
639 else
640 return FALSE;
641 return TRUE;
644 static gboolean parse_eq_param(struct sampler_layer *layer, struct sampler_eq_params *params, struct sampler_eq_has_fields *has_fields, int eq_index, const char *key, const char *value)
646 #define PROC_SET_EQ_FIELD(name, index, def_value) \
647 if (!strcmp(key, #name)) {\
648 params->name = fvalue; \
649 has_fields->name = 1; \
650 return TRUE; \
652 float fvalue = atof_C(value);
653 EQ_FIELDS(PROC_SET_EQ_FIELD)
654 return FALSE;
657 #define PARSE_PARAM_midi_note_t(field, strname, valuestr) \
658 return ((l->data.field = sfz_note_from_string(value)), (l->data.has_##field = 1));
659 #define PARSE_PARAM_int(field, strname, valuestr) \
660 return ((l->data.field = atoi(value)), (l->data.has_##field = 1));
661 #define PARSE_PARAM_uint32_t(field, strname, valuestr) \
662 return ((l->data.field = (uint32_t)strtoul(value, NULL, 10)), (l->data.has_##field = 1));
663 #define PARSE_PARAM_float(field, strname, valuestr) \
664 return ((l->data.field = atof_C(value)), (l->data.has_##field = 1));
666 #define PROC_APPLY_PARAM(type, name, def_value) \
667 if (!strcmp(key, #name)) { \
668 PARSE_PARAM_##type(name, #name, value) \
670 #define PROC_APPLY_PARAM_string(name) \
671 if (!strcmp(key, #name)) { \
672 if (l->data.name && value && !strcmp(l->data.name, value)) \
673 return (l->data.has_##name = 1); \
674 g_free(l->data.name); \
675 return ((l->data.name = g_strdup(value)), (l->data.name##_changed = 1), (l->data.has_##name = 1)); \
677 #define PROC_APPLY_PARAM_dBamp(type, name, def_value) \
678 if (!strcmp(key, #name)) { \
679 return ((l->data.name = atof_C(value)), (l->data.has_##name = 1)); \
681 #define PROC_APPLY_PARAM_enum(enumtype, name, def_value) \
682 if (!strcmp(key, #name)) { \
683 if (!enumtype##_from_string(value, &l->data.name)) { \
684 g_set_error(error, CBOX_MODULE_ERROR, CBOX_MODULE_ERROR_FAILED, "Value %s is not a correct value for %s", value, #name); \
685 return FALSE; \
687 l->data.has_##name = 1; \
688 return TRUE; \
691 // LFO and envelope need special handling now
692 #define PROC_APPLY_PARAM_dahdsr(name, parname, index) \
693 if (!strncmp(key, #parname "_", sizeof(#parname))) \
694 return parse_envelope_param(l, &l->data.name, &l->data.has_##name, index, key + sizeof(#parname), value);
695 #define PROC_APPLY_PARAM_lfo(name, parname, index) \
696 if (!strncmp(key, #parname "_", sizeof(#parname))) \
697 return parse_lfo_param(l, &l->data.name, &l->data.has_##name, index, key + sizeof(#parname), value);
698 #define PROC_APPLY_PARAM_eq(name, parname, index) \
699 if (!strncmp(key, #parname "_", sizeof(#parname))) \
700 return parse_eq_param(l, &l->data.name, &l->data.has_##name, index, key + sizeof(#parname), value);
701 #define PROC_APPLY_PARAM_ccrange(name) /* handled separately in apply_param */
703 static void sampler_layer_apply_unknown(struct sampler_layer *l, const char *key, const char *value)
705 if (!l->unknown_keys)
706 l->unknown_keys = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
708 g_hash_table_insert(l->unknown_keys, g_strdup(key), g_strdup(value));
711 gboolean sampler_layer_apply_param(struct sampler_layer *l, const char *key, const char *value, GError **error)
713 try_now:
714 // XXXKF: this is seriously stupid code, this should use a hash table for
715 // fixed strings, or something else that doesn't explode O(N**2) with
716 // number of attributes. But premature optimization is a root of all evil.
718 SAMPLER_FIXED_FIELDS(PROC_APPLY_PARAM)
720 // XXXKF: to make things worse, some attributes have names different from
721 // C field names, or have multiple names, or don't map 1:1 to internal model
723 if (!strcmp(key, "lolev"))
724 l->data.lovel = atoi(value), l->data.has_lovel = 1;
725 else if (!strcmp(key, "hilev"))
726 l->data.hivel = atoi(value), l->data.has_hivel = 1;
727 else if (!strcmp(key, "benddown"))
728 l->data.bend_down = atoi(value), l->data.has_bend_down = 1;
729 else if (!strcmp(key, "bendup"))
730 l->data.bend_up = atoi(value), l->data.has_bend_up = 1;
731 else if (!strcmp(key, "loopstart"))
732 l->data.loop_start = atoi(value), l->data.has_loop_start = 1;
733 else if (!strcmp(key, "loopend"))
734 l->data.loop_end = atoi(value), l->data.has_loop_end = 1;
735 else if (!strcmp(key, "cutoff_chanaft"))
736 sampler_layer_set_modulation1(l, smsrc_chanaft, smdest_cutoff, atof_C(value), 0);
737 else if (!strcmp(key, "amp_random"))
738 sampler_layer_add_nif(l, sampler_nif_addrandom, 0, atof_C(value));
739 else if (!strcmp(key, "fil_random"))
740 sampler_layer_add_nif(l, sampler_nif_addrandom, 1, atof_C(value));
741 else if (!strcmp(key, "pitch_random"))
742 sampler_layer_add_nif(l, sampler_nif_addrandom, 2, atof_C(value));
743 else if (!strcmp(key, "pitch_veltrack"))
744 sampler_layer_add_nif(l, sampler_nif_vel2pitch, 0, atof_C(value));
745 else if (!strncmp(key, "delay_cc", 8))
747 int ccno = atoi(key + 8);
748 if (ccno > 0 && ccno < 120)
749 sampler_layer_add_nif(l, sampler_nif_cc2delay, ccno, atof_C(value));
750 else
751 goto unknown_key;
753 else if (!strncmp(key, "cutoff_cc", 9))
755 int ccno = atoi(key + 9);
756 if (ccno > 0 && ccno < 120)
757 sampler_layer_set_modulation1(l, ccno, smdest_cutoff, atof_C(value), 0);
758 else
759 goto unknown_key;
761 else if (!strncmp(key, "pitch_cc", 8))
763 int ccno = atoi(key + 8);
764 if (ccno > 0 && ccno < 120)
765 sampler_layer_set_modulation1(l, ccno, smdest_pitch, atof_C(value), 0);
766 else
767 goto unknown_key;
769 else if (!strncmp(key, "tonectl_cc", 10))
771 int ccno = atoi(key + 10);
772 if (ccno > 0 && ccno < 120)
773 sampler_layer_set_modulation1(l, ccno, smdest_tonectl, atof_C(value), 0);
774 else
775 goto unknown_key;
777 else if (!strncmp(key, "gain_cc", 7))
779 int ccno = atoi(key + 7);
780 if (ccno > 0 && ccno < 120)
781 sampler_layer_set_modulation1(l, ccno, smdest_gain, atof_C(value), 0);
782 else
783 goto unknown_key;
785 else if (!strncmp(key, "amp_velcurve_", 13))
787 // if not known yet, set to 0, it can always be overriden via velcurve_quadratic setting
788 if (l->data.velcurve_quadratic == -1)
789 l->data.velcurve_quadratic = 0;
790 int point = atoi(key + 13);
791 if (point >= 0 && point <= 127)
793 l->data.velcurve[point] = atof_C(value);
794 if (l->data.velcurve[point] < 0)
795 l->data.velcurve[point] = 0;
796 if (l->data.velcurve[point] > 1)
797 l->data.velcurve[point] = 1;
799 else
800 goto unknown_key;
802 else if (!strncmp(key, "on_locc", 7) || !strncmp(key, "on_hicc", 7))
804 int cc = atoi(key + 7);
805 if (cc > 0 && cc < 120)
807 if (*value)
809 l->data.on_cc_number = cc;
810 if (key[3] == 'l')
812 l->data.on_locc = atoi(value);
813 l->data.has_on_locc = TRUE;
815 else
817 l->data.on_hicc = atoi(value);
818 l->data.has_on_hicc = TRUE;
821 else
823 l->data.on_cc_number = -1;
824 l->data.has_on_locc = FALSE;
825 l->data.has_on_hicc = FALSE;
828 else
829 return FALSE;
831 else if (!strncmp(key, "locc", 4) || !strncmp(key, "hicc", 4))
833 int cc = atoi(key + 4);
834 if (cc > 0 && cc < 120)
836 if (*value)
838 l->data.cc_number = cc;
839 if (key[0] == 'l')
841 l->data.locc = atoi(value);
842 l->data.has_locc = TRUE;
844 else
846 l->data.hicc = atoi(value);
847 l->data.has_hicc = TRUE;
850 else
852 l->data.cc_number = -1;
853 l->data.has_locc = FALSE;
854 l->data.has_hicc = FALSE;
857 else
858 return FALSE;
860 else if (!strcmp(key, "loopmode"))
862 key = "loop_mode";
863 goto try_now; // yes, goto, why not?
865 else if (!strcmp(key, "offby"))
867 key = "off_by";
868 goto try_now;
870 else if (!strncmp(key, "genericmod_", 11))
872 char **tokens = g_strsplit(key, "_", 5);
873 sampler_layer_set_modulation(l, atoi(tokens[1]), atoi(tokens[2]), atoi(tokens[3]), atof(value), atoi(tokens[4]));
874 g_strfreev(tokens);
876 else
877 goto unknown_key;
879 return TRUE;
880 unknown_key:
881 sampler_layer_apply_unknown(l, key, value);
882 g_warning("Unknown SFZ property key: '%s'", key);
883 return TRUE;
886 #define TYPE_PRINTF_uint32_t(name, def_value) \
887 if (show_inherited || l->has_##name) \
888 g_string_append_printf(outstr, " %s=%u", #name, (unsigned)(l->name));
889 #define TYPE_PRINTF_int(name, def_value) \
890 if (show_inherited || l->has_##name) \
891 g_string_append_printf(outstr, " %s=%d", #name, (int)(l->name));
892 #define TYPE_PRINTF_midi_note_t(name, def_value) \
893 if (show_inherited || l->has_##name) { \
894 int val = l->name; \
895 if (val == -1) \
896 g_string_append_printf(outstr, " %s=-1", #name); \
897 else \
898 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)); \
899 } else {}
900 #define TYPE_PRINTF_float(name, def_value) \
901 if (show_inherited || l->has_##name) \
902 g_string_append_printf(outstr, " %s=%s", #name, g_ascii_dtostr(floatbuf, floatbufsize, l->name));
904 #define PROC_FIELDS_TO_FILEPTR(type, name, def_value) \
905 TYPE_PRINTF_##type(name, def_value)
906 #define PROC_FIELDS_TO_FILEPTR_string(name) \
907 if (show_inherited || l->has_##name) \
908 g_string_append_printf(outstr, " %s=%s", #name, l->name ? l->name : "");
909 #define PROC_FIELDS_TO_FILEPTR_dBamp(type, name, def_value) \
910 if (show_inherited || l->has_##name) \
911 g_string_append_printf(outstr, " %s=%s", #name, g_ascii_dtostr(floatbuf, floatbufsize, l->name));
912 #define PROC_FIELDS_TO_FILEPTR_enum(enumtype, name, def_value) \
913 if ((show_inherited || l->has_##name) && (tmpstr = enumtype##_to_string(l->name)) != NULL) \
914 g_string_append_printf(outstr, " %s=%s", #name, tmpstr);
916 #define ENV_PARAM_OUTPUT(param, index, def_value, env, envfield, envname) \
917 if (show_inherited || l->has_##envfield.param) \
918 g_string_append_printf(outstr, " " #envname "_" #param "=%s", g_ascii_dtostr(floatbuf, floatbufsize, env.param));
920 #define PROC_FIELDS_TO_FILEPTR_dahdsr(name, parname, index) \
921 DAHDSR_FIELDS(ENV_PARAM_OUTPUT, l->name, name, parname)
922 #define PROC_FIELDS_TO_FILEPTR_lfo(name, parname, index) \
923 LFO_FIELDS(ENV_PARAM_OUTPUT, l->name, name, parname)
924 #define PROC_FIELDS_TO_FILEPTR_eq(name, parname, index) \
925 EQ_FIELDS(ENV_PARAM_OUTPUT, l->name, name, parname)
926 #define PROC_FIELDS_TO_FILEPTR_ccrange(name) \
927 if (l->has_##name##locc) \
928 g_string_append_printf(outstr, " " #name "locc%d=%d", l->name##cc_number, l->name##locc); \
929 if (l->has_##name##hicc) \
930 g_string_append_printf(outstr, " " #name "hicc%d=%d", l->name##cc_number, l->name##hicc);
932 gchar *sampler_layer_to_string(struct sampler_layer *lr, gboolean show_inherited)
934 struct sampler_layer_data *l = &lr->data;
935 GString *outstr = g_string_sized_new(200);
936 const char *tmpstr;
937 char floatbuf[G_ASCII_DTOSTR_BUF_SIZE];
938 int floatbufsize = G_ASCII_DTOSTR_BUF_SIZE;
939 SAMPLER_FIXED_FIELDS(PROC_FIELDS_TO_FILEPTR)
941 static const char *addrandom_variants[] = { "amp", "fil", "pitch" };
942 static const char *modsrc_names[] = { "chanaft", "vel", "polyaft", "pitch", "pitcheg", "fileg", "ampeg", "pitchlfo", "fillfo", "amplfo", "" };
943 static const char *moddest_names[] = { "gain", "pitch", "cutoff", "resonance", "tonectl" };
944 for(GSList *nif = l->nifs; nif; nif = nif->next)
946 struct sampler_noteinitfunc *nd = nif->data;
947 if (!nd->has_value && !show_inherited)
948 continue;
949 #define PROC_ENVSTAGE_NAME(name, index, def_value) #name,
950 static const char *env_stages[] = { DAHDSR_FIELDS(PROC_ENVSTAGE_NAME) };
951 int v = nd->variant;
952 g_ascii_dtostr(floatbuf, floatbufsize, nd->param);
954 if (nd->notefunc == sampler_nif_addrandom && v >= 0 && v <= 2)
955 g_string_append_printf(outstr, " %s_random=%s", addrandom_variants[nd->variant], floatbuf);
956 else if (nd->notefunc == sampler_nif_vel2pitch)
957 g_string_append_printf(outstr, " pitch_veltrack=%s", floatbuf);
958 else if (nd->notefunc == sampler_nif_cc2delay && v >= 0 && v < 120)
959 g_string_append_printf(outstr, " delay_cc%d=%s", nd->variant, floatbuf);
960 else if (nd->notefunc == sampler_nif_vel2env && v >= 0 && (v & 15) < 6 && (v >> 4) < 3)
961 g_string_append_printf(outstr, " %seg_vel2%s=%s", addrandom_variants[nd->variant >> 4], env_stages[1 + (v & 15)], floatbuf);
963 for(GSList *mod = l->modulations; mod; mod = mod->next)
965 struct sampler_modulation *md = mod->data;
966 if (!md->has_value && !show_inherited)
967 continue;
968 g_ascii_dtostr(floatbuf, floatbufsize, md->amount);
970 if (md->src2 == smsrc_none)
972 if (md->src < 120)
974 g_string_append_printf(outstr, " %s_cc%d=%s", moddest_names[md->dest], md->src, floatbuf);
975 continue;
977 if (md->src < 120 + sizeof(modsrc_names) / sizeof(modsrc_names[0]))
979 if ((md->src == smsrc_filenv && md->dest == smdest_cutoff) ||
980 (md->src == smsrc_pitchenv && md->dest == smdest_pitch))
981 g_string_append_printf(outstr, " %s_depth=%s", modsrc_names[md->src - 120], floatbuf);
982 else
983 g_string_append_printf(outstr, " %s_%s=%s", moddest_names[md->dest], modsrc_names[md->src - 120], floatbuf);
984 continue;
987 if ((md->src == smsrc_amplfo && md->dest == smdest_gain) ||
988 (md->src == smsrc_fillfo && md->dest == smdest_cutoff) ||
989 (md->src == smsrc_pitchlfo && md->dest == smdest_pitch))
991 switch(md->src2)
993 case smsrc_chanaft:
994 case smsrc_polyaft:
995 g_string_append_printf(outstr, " %slfo_depth%s=%s", moddest_names[md->dest], modsrc_names[md->src2 - 120], floatbuf);
996 continue;
997 default:
998 if (md->src2 < 120)
1000 g_string_append_printf(outstr, " %slfo_depthcc%d=%s", moddest_names[md->dest], md->src2, floatbuf);
1001 continue;
1003 break;
1005 break;
1007 if ((md->src == smsrc_ampenv && md->dest == smdest_gain) ||
1008 (md->src == smsrc_filenv && md->dest == smdest_cutoff) ||
1009 (md->src == smsrc_pitchenv && md->dest == smdest_pitch))
1011 if (md->src2 == smsrc_vel)
1013 g_string_append_printf(outstr, " %seg_vel2depth=%s", moddest_names[md->dest], floatbuf);
1014 continue;
1016 if (md->src2 < 120)
1018 g_string_append_printf(outstr, " %s_depthcc%d=%s", modsrc_names[md->src - 120], md->src2, floatbuf);
1019 continue;
1022 g_string_append_printf(outstr, " genericmod_%d_%d_%d_%d=%s", md->src, md->src2, md->dest, md->flags, floatbuf);
1025 if (lr->unknown_keys)
1027 GHashTableIter hti;
1028 gchar *key, *value;
1029 g_hash_table_iter_init(&hti, lr->unknown_keys);
1030 while(g_hash_table_iter_next(&hti, (gpointer *)&key, (gpointer *)&value))
1031 g_string_append_printf(outstr, " %s=%s", key, value);
1034 gchar *res = outstr->str;
1035 g_string_free(outstr, FALSE);
1036 return res;
1039 void sampler_layer_dump(struct sampler_layer *l, FILE *f)
1041 gchar *str = sampler_layer_to_string(l, FALSE);
1042 fprintf(f, "%s\n", str);
1045 void sampler_layer_data_close(struct sampler_layer_data *l)
1047 g_slist_free_full(l->nifs, g_free);
1048 g_slist_free_full(l->modulations, g_free);
1049 if (l->eff_waveform)
1051 cbox_waveform_unref(l->eff_waveform);
1052 l->eff_waveform = NULL;
1054 g_free(l->sample);
1057 void sampler_layer_data_destroy(struct sampler_layer_data *l)
1059 sampler_layer_data_close(l);
1060 free(l);
1063 struct sampler_layer *sampler_layer_new_clone(struct sampler_layer *layer,
1064 struct sampler_module *m, struct sampler_program *parent_program, struct sampler_layer *parent_group)
1066 struct sampler_layer *l = sampler_layer_new(m, parent_program, parent_group);
1067 sampler_layer_data_clone(&l->data, &layer->data, TRUE);
1068 if (layer->unknown_keys)
1070 GHashTableIter iter;
1071 g_hash_table_iter_init(&iter, layer->unknown_keys);
1072 gpointer key, value;
1073 while(g_hash_table_iter_next(&iter, &key, &value))
1074 sampler_layer_apply_param(l, (gchar *)key, (gchar *)value, NULL);
1077 GHashTableIter iter;
1078 g_hash_table_iter_init(&iter, layer->child_layers);
1079 gpointer key, value;
1080 while(g_hash_table_iter_next(&iter, &key, &value))
1082 sampler_layer_new_clone(key, m, parent_program, l);
1083 // g_hash_table_insert(l->child_layers, chl, NULL);
1086 return l;
1089 void sampler_layer_destroyfunc(struct cbox_objhdr *objhdr)
1091 struct sampler_layer *l = CBOX_H2O(objhdr);
1092 struct sampler_program *prg = l->parent_program;
1093 assert(g_hash_table_size(l->child_layers) == 0);
1095 if (l->parent_group)
1097 g_hash_table_remove(l->parent_group->child_layers, l);
1098 if (prg && prg->rll)
1100 sampler_program_delete_layer(prg, l);
1101 sampler_program_update_layers(l->parent_program);
1103 l->parent_group = NULL;
1105 sampler_layer_data_close(&l->data);
1106 if (l->runtime)
1107 sampler_layer_data_destroy(l->runtime);
1108 if (l->unknown_keys)
1109 g_hash_table_destroy(l->unknown_keys);
1110 if (l->child_layers)
1111 g_hash_table_destroy(l->child_layers);
1113 free(l);
1116 //////////////////////////////////////////////////////////////////////////
1118 struct sampler_layer_update_cmd
1120 struct sampler_module *module;
1121 struct sampler_layer *layer;
1122 struct sampler_layer_data *new_data;
1123 struct sampler_layer_data *old_data;
1126 static int sampler_layer_update_cmd_prepare(void *data)
1128 struct sampler_layer_update_cmd *cmd = data;
1129 cmd->old_data = cmd->layer->runtime;
1130 cmd->new_data = calloc(1, sizeof(struct sampler_layer_data));
1132 sampler_layer_data_clone(cmd->new_data, &cmd->layer->data, TRUE);
1133 sampler_layer_data_finalize(cmd->new_data, cmd->layer->parent_group ? &cmd->layer->parent_group->data : NULL, cmd->layer->parent_program);
1134 if (cmd->layer->runtime == NULL)
1136 // initial update of the layer, so none of the voices need updating yet
1137 // because the layer hasn't been allocated to any voice
1138 cmd->layer->runtime = cmd->new_data;
1139 return 1;
1141 return 0;
1144 static int sampler_layer_update_cmd_execute(void *data)
1146 struct sampler_layer_update_cmd *cmd = data;
1148 for (int i = 0; i < 16; i++)
1150 FOREACH_VOICE(cmd->module->channels[i].voices_running, v)
1152 if (v->layer == cmd->layer->runtime)
1154 v->layer = cmd->new_data;
1155 v->layer_changed = TRUE;
1156 sampler_voice_update_params_from_layer(v);
1160 cmd->old_data = cmd->layer->runtime;
1161 cmd->layer->runtime = cmd->new_data;
1162 return 10;
1165 static void sampler_layer_update_cmd_cleanup(void *data)
1167 struct sampler_layer_update_cmd *cmd = data;
1169 sampler_layer_data_destroy(cmd->old_data);
1170 free(cmd);
1173 void sampler_layer_update(struct sampler_layer *l)
1175 // if changing a group, update all child regions instead
1176 if (g_hash_table_size(l->child_layers))
1178 GHashTableIter iter;
1179 g_hash_table_iter_init(&iter, l->child_layers);
1180 gpointer key, value;
1181 while(g_hash_table_iter_next(&iter, &key, &value))
1183 sampler_layer_data_finalize(&((struct sampler_layer *)key)->data, &l->data, l->parent_program);
1184 sampler_layer_update((struct sampler_layer *)key);
1186 return;
1188 static struct cbox_rt_cmd_definition rtcmd = {
1189 .prepare = sampler_layer_update_cmd_prepare,
1190 .execute = sampler_layer_update_cmd_execute,
1191 .cleanup = sampler_layer_update_cmd_cleanup,
1194 struct sampler_layer_update_cmd *lcmd = malloc(sizeof(struct sampler_layer_update_cmd));
1195 lcmd->module = l->module;
1196 lcmd->layer = l;
1197 lcmd->new_data = NULL;
1198 lcmd->old_data = NULL;
1200 cbox_rt_execute_cmd_async(l->module->module.rt, &rtcmd, lcmd);