Improve non-default routing for USB MIDI. Pass usb_midi_input/output from JackIO...
[calfbox.git] / wavebank.c
blob9b1d79a6914e051e86e34202f5aac15decc91d5e
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 "cmd.h"
20 #include "dspmath.h"
21 #include "errors.h"
22 #include "wavebank.h"
23 #include <assert.h>
24 #include <errno.h>
25 #include <glib.h>
26 #include <math.h>
27 #include <stdlib.h>
28 #include <string.h>
30 #define STD_WAVEFORM_FRAMES 1024
31 #define STD_WAVEFORM_BITS 10
33 ///////////////////////////////////////////////////////////////////////////////
35 // Sine table
36 static complex float euler_table[STD_WAVEFORM_FRAMES];
38 // Bit reversal table
39 static int map_table[STD_WAVEFORM_FRAMES];
41 // Initialise tables using for FFT
42 static void init_tables(void)
44 int rev = 1 << (STD_WAVEFORM_BITS - 1);
45 for (int i = 0; i < STD_WAVEFORM_FRAMES; i++)
47 euler_table[i] = cos(i * 2 * M_PI / STD_WAVEFORM_FRAMES) + I * sin(i * 2 * M_PI / STD_WAVEFORM_FRAMES);
48 int ni = 0;
49 for (int j = 0; j < STD_WAVEFORM_BITS; j++)
51 if (i & (rev >> j))
52 ni = ni | (1 << j);
54 map_table[i] = ni;
58 // Trivial implementation of Cooley-Tukey, only works for even values of ANALYSIS_BUFFER_BITS
59 static void my_fft_main(complex float output[STD_WAVEFORM_FRAMES])
61 complex float temp[STD_WAVEFORM_FRAMES];
63 for (int i = 0; i < STD_WAVEFORM_BITS; i++)
65 complex float *src = (i & 1) ? temp : output;
66 complex float *dst = (i & 1) ? output : temp;
67 int invi = STD_WAVEFORM_BITS - i - 1;
68 int disp = 1 << i;
69 int mask = disp - 1;
71 for (int j = 0; j < STD_WAVEFORM_FRAMES / 2; j++)
73 int jj1 = (j & mask) + ((j & ~mask) << 1); // insert 0 at ith bit to get the left arm of the butterfly
74 int jj2 = jj1 + disp; // insert 1 at ith bit to get the right arm
75 assert((jj1 + disp) == (jj1 | disp));
77 // e^iw
78 complex float eiw1 = euler_table[(jj1 << invi) & (STD_WAVEFORM_FRAMES - 1)];
79 complex float eiw2 = euler_table[(jj2 << invi) & (STD_WAVEFORM_FRAMES - 1)];
81 // printf("%d -> %d, %d\n", j, jj, jj + disp);
82 butterfly(&dst[jj1], &dst[jj2], src[jj1], src[jj2], eiw1, eiw2);
87 static void my_fft_r2c(complex float output[STD_WAVEFORM_FRAMES], int16_t input[STD_WAVEFORM_FRAMES])
89 assert(!(STD_WAVEFORM_BITS&1));
90 // Copy + bit reversal addressing
91 for (int i = 0; i < STD_WAVEFORM_FRAMES; i++)
92 output[i] = input[map_table[i]] * (1.0 / STD_WAVEFORM_FRAMES);
94 my_fft_main(output);
98 static void my_ifft_c2r(int16_t output[STD_WAVEFORM_FRAMES], complex float input[STD_WAVEFORM_FRAMES])
100 complex float temp2[STD_WAVEFORM_FRAMES];
101 for (int i = 0; i < STD_WAVEFORM_FRAMES; i++)
102 temp2[i] = input[map_table[i]];
103 assert(!(STD_WAVEFORM_BITS&1));
105 my_fft_main(temp2);
106 // Copy + bit reversal addressing
107 float maxv = 0;
108 for (int i = 0; i < STD_WAVEFORM_FRAMES; i++)
110 float value = creal(temp2[i]);
111 if (value < -32768) value = -32768;
112 if (value > 32767) value = 32767;
113 if (fabs(value) > maxv)
114 maxv = fabs(value);
115 output[i] = (int16_t)value;
119 struct wave_bank
121 int64_t bytes, maxbytes, serial_no;
122 GHashTable *waveforms_by_name, *waveforms_by_id;
123 GSList *std_waveforms;
126 static struct wave_bank bank;
128 GQuark cbox_waveform_error_quark(void)
130 return g_quark_from_string("cbox-waveform-error-quark");
133 float func_sine(float v, void *user_data)
135 return sin(2 * M_PI * v);
138 float func_sqr(float v, void *user_data)
140 return v < 0.5 ? -1 : 1;
143 float func_saw(float v, void *user_data)
145 return 2 * v - 1;
148 float func_tri(float v, void *user_data)
150 if (v <= 0.25f)
151 return v * 4;
152 if (v <= 0.75f)
153 return 1 - (v - 0.25f) * 4;
154 return -1 + 4 * (v - 0.75f);
157 void cbox_waveform_generate_levels(struct cbox_waveform *waveform, int levels, double ratio)
159 complex float output[STD_WAVEFORM_FRAMES], bandlimited[STD_WAVEFORM_FRAMES];
160 my_fft_r2c(output, waveform->data);
161 int N = STD_WAVEFORM_FRAMES;
163 waveform->levels = calloc(levels, sizeof(struct cbox_waveform_level));
164 double rate = 65536.0 * 65536.0; // / waveform->info.frames;
165 double orig_rate = 65536.0 * 65536.0; // / waveform->info.frames;
166 for (int i = 0; i < levels; i++)
168 int harmonics = N / 2 / (rate / orig_rate);
169 bandlimited[0] = 0;
171 for (int j = 1; j <= harmonics; j++)
173 bandlimited[j] = output[j];
174 bandlimited[N - j] = output[N - j];
176 for (int j = harmonics; j <= N / 2; j++)
177 bandlimited[j] = bandlimited [N - j] = 0;
179 waveform->levels[i].data = calloc(N, sizeof(int16_t));
180 my_ifft_c2r(waveform->levels[i].data, bandlimited);
181 waveform->levels[i].max_rate = (uint64_t)(rate);
182 rate *= ratio;
184 waveform->level_count = levels;
187 void cbox_wavebank_add_std_waveform(const char *name, float (*getfunc)(float v, void *user_data), void *user_data, int levels)
189 int nsize = STD_WAVEFORM_FRAMES;
190 int16_t *wave = calloc(nsize, sizeof(int16_t));
191 for (int i = 0; i < nsize; i++)
193 float v = getfunc(i * 1.0 / nsize, user_data);
194 if (fabs(v) > 1)
195 v = (v < 0) ? -1 : 1;
196 // cannot use full scale here, because bandlimiting will introduce
197 // some degree of overshoot
198 wave[i] = (int16_t)(25000 * v);
200 struct cbox_waveform *waveform = calloc(1, sizeof(struct cbox_waveform));
201 waveform->data = wave;
202 waveform->info.channels = 1;
203 waveform->info.frames = nsize;
204 waveform->info.samplerate = (int)(nsize * 261.6255);
205 waveform->id = ++bank.serial_no;
206 waveform->bytes = waveform->info.channels * 2 * (waveform->info.frames + 1);
207 waveform->refcount = 1;
208 waveform->canonical_name = g_strdup(name);
209 waveform->display_name = g_strdup(name);
210 waveform->has_loop = TRUE;
211 waveform->loop_start = 0;
212 waveform->loop_end = nsize;
213 waveform->levels = NULL;
214 waveform->level_count = 0;
216 if (levels)
217 cbox_waveform_generate_levels(waveform, levels, 2);
219 g_hash_table_insert(bank.waveforms_by_name, waveform->canonical_name, waveform);
220 g_hash_table_insert(bank.waveforms_by_id, &waveform->id, waveform);
221 bank.std_waveforms = g_slist_prepend(bank.std_waveforms, waveform);
222 // These waveforms are not included in the bank size, I don't think it has
223 // much value for the user.
226 void cbox_wavebank_init()
228 init_tables();
230 bank.bytes = 0;
231 bank.maxbytes = 0;
232 bank.serial_no = 0;
233 bank.waveforms_by_name = g_hash_table_new(g_str_hash, g_str_equal);
234 bank.waveforms_by_id = g_hash_table_new(g_int_hash, g_int_equal);
235 bank.std_waveforms = NULL;
237 cbox_wavebank_add_std_waveform("*sine", func_sine, NULL, 0);
238 cbox_wavebank_add_std_waveform("*saw", func_saw, NULL, 11);
239 cbox_wavebank_add_std_waveform("*sqr", func_sqr, NULL, 11);
240 cbox_wavebank_add_std_waveform("*tri", func_tri, NULL, 11);
243 struct cbox_waveform *cbox_wavebank_get_waveform(const char *context_name, const char *filename, GError **error)
245 int i;
246 int nshorts;
248 if (!filename)
250 g_set_error(error, CBOX_WAVEFORM_ERROR, CBOX_WAVEFORM_ERROR_FAILED, "%s: no filename specified", context_name);
251 return NULL;
254 // Built in waveforms don't go through path canonicalization
255 if (filename[0] == '*')
257 gpointer value = g_hash_table_lookup(bank.waveforms_by_name, filename);
258 if (value)
260 struct cbox_waveform *waveform = value;
261 cbox_waveform_ref(waveform);
262 return waveform;
266 char *canonical = realpath(filename, NULL);
267 if (!canonical)
269 g_set_error(error, CBOX_WAVEFORM_ERROR, CBOX_WAVEFORM_ERROR_FAILED, "%s: cannot find a real path for '%s'", context_name, filename);
270 return NULL;
272 gpointer value = g_hash_table_lookup(bank.waveforms_by_name, canonical);
273 if (value)
275 free(canonical);
277 struct cbox_waveform *waveform = value;
278 cbox_waveform_ref(waveform);
279 return waveform;
282 struct cbox_waveform *waveform = calloc(1, sizeof(struct cbox_waveform));
283 SNDFILE *sndfile = sf_open(filename, SFM_READ, &waveform->info);
284 SF_INSTRUMENT instrument;
285 if (!sndfile)
287 g_set_error(error, G_FILE_ERROR, g_file_error_from_errno (errno), "%s: cannot open '%s'", context_name, filename);
288 free(canonical);
289 return NULL;
291 if (waveform->info.channels != 1 && waveform->info.channels != 2)
293 g_set_error(error, CBOX_WAVEFORM_ERROR, CBOX_WAVEFORM_ERROR_FAILED,
294 "%s: cannot open file '%s': unsupported channel count %d", context_name, filename, (int)waveform->info.channels);
295 sf_close(sndfile);
296 free(canonical);
297 return NULL;
299 waveform->id = ++bank.serial_no;
300 waveform->bytes = waveform->info.channels * 2 * (waveform->info.frames + 1);
301 waveform->data = malloc(waveform->bytes);
302 waveform->refcount = 1;
303 waveform->canonical_name = canonical;
304 waveform->display_name = g_filename_display_name(canonical);
305 waveform->has_loop = FALSE;
306 waveform->levels = NULL;
307 waveform->level_count = 0;
309 if (sf_command(sndfile, SFC_GET_INSTRUMENT, &instrument, sizeof(SF_INSTRUMENT)))
311 for (int i = 0; i < instrument.loop_count; i++)
313 if (instrument.loops[i].mode == SF_LOOP_FORWARD)
315 waveform->loop_start = instrument.loops[i].start;
316 waveform->loop_end = instrument.loops[i].end;
317 waveform->has_loop = TRUE;
318 break;
323 nshorts = waveform->info.channels * (waveform->info.frames + 1);
324 for (i = 0; i < nshorts; i++)
325 waveform->data[i] = 0;
326 sf_readf_short(sndfile, waveform->data, waveform->info.frames);
327 sf_close(sndfile);
328 bank.bytes += waveform->bytes;
329 if (bank.bytes > bank.maxbytes)
330 bank.maxbytes = bank.bytes;
331 g_hash_table_insert(bank.waveforms_by_name, waveform->canonical_name, waveform);
332 g_hash_table_insert(bank.waveforms_by_id, &waveform->id, waveform);
334 return waveform;
337 int64_t cbox_wavebank_get_bytes()
339 return bank.bytes;
342 int64_t cbox_wavebank_get_maxbytes()
344 return bank.maxbytes;
347 int cbox_wavebank_get_count()
349 return g_hash_table_size(bank.waveforms_by_id);
352 struct cbox_waveform *cbox_wavebank_peek_waveform_by_id(int id)
354 return g_hash_table_lookup(bank.waveforms_by_id, &id);
357 void cbox_wavebank_foreach(void (*cb)(void *, struct cbox_waveform *), void *user_data)
359 GHashTableIter iter;
360 gpointer key, value;
362 g_hash_table_iter_init (&iter, bank.waveforms_by_id);
363 while (g_hash_table_iter_next (&iter, &key, &value))
365 (*cb)(user_data, value);
369 void cbox_wavebank_close()
371 if (bank.bytes > 0)
372 g_warning("Warning: %lld bytes in unfreed samples", (long long int)bank.bytes);
373 while(bank.std_waveforms)
375 cbox_waveform_unref((struct cbox_waveform *)bank.std_waveforms->data);
376 bank.std_waveforms = g_slist_delete_link(bank.std_waveforms, bank.std_waveforms);
378 g_hash_table_destroy(bank.waveforms_by_id);
379 g_hash_table_destroy(bank.waveforms_by_name);
380 bank.waveforms_by_id = NULL;
381 bank.waveforms_by_name = NULL;
384 /////////////////////////////////////////////////////////////////////////////////////////////////////
386 void cbox_waveform_ref(struct cbox_waveform *waveform)
388 ++waveform->refcount;
391 void cbox_waveform_unref(struct cbox_waveform *waveform)
393 if (--waveform->refcount > 0)
394 return;
396 g_hash_table_remove(bank.waveforms_by_name, waveform->canonical_name);
397 g_hash_table_remove(bank.waveforms_by_id, &waveform->id);
398 bank.bytes -= waveform->bytes;
400 g_free(waveform->display_name);
401 free(waveform->canonical_name);
402 for (int i = 0; i < waveform->level_count; i++)
403 free(waveform->levels[i].data);
404 free(waveform->levels);
405 free(waveform->data);
406 free(waveform);
410 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
412 struct waves_foreach_data
414 struct cbox_command_target *fb;
415 GError **error;
416 gboolean success;
419 void wave_list_cb(void *user_data, struct cbox_waveform *waveform)
421 struct waves_foreach_data *wfd = user_data;
423 wfd->success = wfd->success && cbox_execute_on(wfd->fb, NULL, "/waveform", "i", wfd->error, (int)waveform->id);
426 static gboolean waves_process_cmd(struct cbox_command_target *ct, struct cbox_command_target *fb, struct cbox_osc_command *cmd, GError **error)
428 if (!strcmp(cmd->command, "/status") && !strcmp(cmd->arg_types, ""))
430 if (!cbox_check_fb_channel(fb, cmd->command, error))
431 return FALSE;
433 // XXXKF this only supports 4GB - not a big deal for now yet?
434 return cbox_execute_on(fb, NULL, "/bytes", "i", error, (int)cbox_wavebank_get_bytes()) &&
435 cbox_execute_on(fb, NULL, "/max_bytes", "i", error, (int)cbox_wavebank_get_maxbytes()) &&
436 cbox_execute_on(fb, NULL, "/count", "i", error, (int)cbox_wavebank_get_count())
439 else if (!strcmp(cmd->command, "/list") && !strcmp(cmd->arg_types, ""))
441 if (!cbox_check_fb_channel(fb, cmd->command, error))
442 return FALSE;
444 struct waves_foreach_data wfd = { fb, error, TRUE };
445 cbox_wavebank_foreach(wave_list_cb, &wfd);
446 return wfd.success;
448 else if (!strcmp(cmd->command, "/info") && !strcmp(cmd->arg_types, "i"))
450 if (!cbox_check_fb_channel(fb, cmd->command, error))
451 return FALSE;
453 int id = CBOX_ARG_I(cmd, 0);
454 struct cbox_waveform *waveform = cbox_wavebank_peek_waveform_by_id(id);
455 if (waveform == NULL)
457 g_set_error(error, CBOX_MODULE_ERROR, CBOX_MODULE_ERROR_FAILED, "Waveform %d not found", id);
458 return FALSE;
460 assert(id == waveform->id);
461 if (!cbox_execute_on(fb, NULL, "/filename", "s", error, waveform->canonical_name)) // XXXKF convert to utf8
462 return FALSE;
463 if (!cbox_execute_on(fb, NULL, "/name", "s", error, waveform->display_name))
464 return FALSE;
465 if (!cbox_execute_on(fb, NULL, "/bytes", "i", error, (int)waveform->bytes))
466 return FALSE;
467 if (waveform->has_loop && !cbox_execute_on(fb, NULL, "/loop", "ii", error, (int)waveform->loop_start, (int)waveform->loop_end))
468 return FALSE;
469 return TRUE;
471 else
473 g_set_error(error, CBOX_MODULE_ERROR, CBOX_MODULE_ERROR_FAILED, "Unknown combination of target path and argument: '%s', '%s'", cmd->command, cmd->arg_types);
474 return FALSE;
478 struct cbox_command_target cbox_waves_cmd_target =
480 .process_cmd = waves_process_cmd,
481 .user_data = NULL