1 /* reasonable simple synth
3 * Copyright (C) 2013 Robin Gareus <robin@gareus.org>
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 2, or (at your option)
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, write to the Free Software Foundation,
17 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21 #define _GNU_SOURCE // needed for M_PI
31 #ifndef BUFFER_SIZE_SAMPLES
32 #define BUFFER_SIZE_SAMPLES 64
36 #define MIN(A, B) ( (A) < (B) ? (A) : (B) )
39 /* internal MIDI event abstraction */
48 struct rmidi_event_t {
49 enum RMIDI_EV_TYPE type;
50 uint8_t channel; /**< the MIDI channel number 0-15 */
64 uint32_t tme[3]; // attack, decay, release times [settings:ms || internal:samples]
65 float vol[2]; // attack, sustain volume [0..1]
66 uint32_t off[3]; // internal use (added attack,decay,release times)
69 typedef struct _RSSynthChannel {
71 uint32_t adsr_cnt[128];
73 float phase[128]; // various use, zero'ed on note-on
74 int8_t miditable[128]; // internal, note-on/off velocity
75 int8_t midimsgs [128]; // internal, note-off + on in same cycle
77 void (*synthesize) (struct _RSSynthChannel* sc,
78 const uint8_t note, const float vol, const float pc,
79 const size_t n_samples, float* left, float* right);
82 typedef void (*SynthFunction) (RSSynthChannel* sc,
83 const uint8_t note, const float vol, const float pc,
84 const size_t n_samples, float* left, float* right);
88 float buf [2][BUFFER_SIZE_SAMPLES];
89 RSSynthChannel sc[16];
99 /* initialize ADSR values
101 * @param rate sample-rate
102 * @param a attack time in seconds
103 * @param d decay time in seconds
104 * @param r release time in seconds
105 * @param avol attack gain [0..1]
106 * @param svol sustain volume level [0..1]
108 static void init_adsr(ADSRcfg *adsr, const double rate,
109 const uint32_t a, const uint32_t d, const uint32_t r,
110 const float avol, const float svol) {
114 adsr->tme[0] = a * rate / 1000.0;
115 adsr->tme[1] = d * rate / 1000.0;
116 adsr->tme[2] = r * rate / 1000.0;
118 assert(adsr->tme[0] > 32);
119 assert(adsr->tme[1] > 32);
120 assert(adsr->tme[2] > 32);
121 assert(adsr->vol[0] >=0 && adsr->vol[1] <= 1.0);
122 assert(adsr->vol[1] >=0 && adsr->vol[1] <= 1.0);
124 adsr->off[0] = adsr->tme[0];
125 adsr->off[1] = adsr->tme[1] + adsr->off[0];
126 adsr->off[2] = adsr->tme[2] + adsr->off[1];
129 /* calculate per-sample, per-key envelope */
130 static inline float adsr_env(RSSynthChannel *sc, const uint8_t note) {
132 if (sc->adsr_cnt[note] < sc->adsr.off[0]) {
134 const uint32_t p = ++sc->adsr_cnt[note];
135 if (p == sc->adsr.tme[0]) {
136 sc->adsr_amp[note] = sc->adsr.vol[0];
137 return sc->adsr.vol[0];
139 const float d = sc->adsr.vol[0] - sc->adsr_amp[note];
140 return sc->adsr_amp[note] + (p / (float) sc->adsr.tme[0]) * d;
143 else if (sc->adsr_cnt[note] < sc->adsr.off[1]) {
145 const uint32_t p = ++sc->adsr_cnt[note] - sc->adsr.off[0];
146 if (p == sc->adsr.tme[1]) {
147 sc->adsr_amp[note] = sc->adsr.vol[1];
148 return sc->adsr.vol[1];
150 const float d = sc->adsr.vol[1] - sc->adsr_amp[note];
151 return sc->adsr_amp[note] + (p / (float) sc->adsr.tme[1]) * d;
154 else if (sc->adsr_cnt[note] == sc->adsr.off[1]) {
156 return sc->adsr.vol[1];
158 else if (sc->adsr_cnt[note] < sc->adsr.off[2]) {
160 const uint32_t p = ++sc->adsr_cnt[note] - sc->adsr.off[1];
161 if (p == sc->adsr.tme[2]) {
162 sc->adsr_amp[note] = 0;
165 const float d = 0 - sc->adsr_amp[note];
166 return sc->adsr_amp[note] + (p / (float) sc->adsr.tme[2]) * d;
170 sc->adsr_cnt[note] = 0;
176 /*****************************************************************************/
177 /* piano like sound w/slight stereo phase */
178 static void synthesize_sineP (RSSynthChannel* sc,
179 const uint8_t note, const float vol, const float fq,
180 const size_t n_samples, float* left, float* right) {
183 float phase = sc->phase[note];
185 for (i=0; i < n_samples; ++i) {
186 float env = adsr_env(sc, note);
187 if (sc->adsr_cnt[note] == 0) break;
188 const float amp = vol * env;
190 left[i] += amp * sinf(2.0 * M_PI * phase);
191 left[i] += .300 * amp * sinf(2.0 * M_PI * phase * 2.0);
192 left[i] += .150 * amp * sinf(2.0 * M_PI * phase * 3.0);
193 left[i] += .080 * amp * sinf(2.0 * M_PI * phase * 4.0);
194 //left[i] -= .007 * amp * sinf(2.0 * M_PI * phase * 5.0);
195 //left[i] += .010 * amp * sinf(2.0 * M_PI * phase * 6.0);
196 left[i] += .020 * amp * sinf(2.0 * M_PI * phase * 7.0);
198 right[i] += amp * sinf(2.0 * M_PI * phase);
199 right[i] += .300 * amp * sinf(2.0 * M_PI * phase * 2.0);
200 right[i] += .150 * amp * sinf(2.0 * M_PI * phase * 3.0);
201 right[i] -= .080 * amp * sinf(2.0 * M_PI * phase * 4.0);
202 //right[i] += .007 * amp * sinf(2.0 * M_PI * phase * 5.0);
203 //right[i] += .010 * amp * sinf(2.0 * M_PI * phase * 6.0);
204 right[i] -= .020 * amp * sinf(2.0 * M_PI * phase * 7.0);
205 if (phase > 1.0) phase -= 2.0;
207 sc->phase[note] = phase;
210 static const ADSRcfg piano_adsr = {{ 5, 800, 100}, { 1.0, 0.0}, {0,0,0}};
212 /*****************************************************************************/
215 /* process note - move through ADSR states, count active keys,.. */
216 static void process_key (void *synth,
217 const uint8_t chn, const uint8_t note,
218 const size_t n_samples, float *left, float *right)
220 RSSynthesizer* rs = (RSSynthesizer*)synth;
221 RSSynthChannel* sc = &rs->sc[chn];
222 const int8_t vel = sc->miditable[note];
223 const int8_t msg = sc->midimsgs[note];
224 const float vol = /* master_volume */ 0.25 * fabsf(vel) / 127.0;
225 const float phase = sc->phase[note];
226 sc->midimsgs[note] = 0;
228 if (phase == -10 && vel > 0) {
230 assert(sc->adsr_cnt[note] == 0);
231 sc->adsr_amp[note] = 0;
232 sc->adsr_cnt[note] = 0;
235 //printf("[On] Now %d keys active on chn %d\n", sc->keycomp, chn);
237 else if (phase >= -1.0 && phase <= 1.0 && vel > 0) {
238 // sustain note or re-start note while adsr in progress:
239 if (sc->adsr_cnt[note] > sc->adsr.off[1] || msg == 3) {
241 sc->adsr_amp[note] = adsr_env(sc, note);
242 sc->adsr_cnt[note] = 0;
245 else if (phase >= -1.0 && phase <= 1.0 && vel < 0) {
247 if (sc->adsr_cnt[note] <= sc->adsr.off[1]) {
248 if (sc->adsr_cnt[note] != sc->adsr.off[1]) {
250 sc->adsr_amp[note] = adsr_env(sc, note);
252 sc->adsr_cnt[note] = sc->adsr.off[1] + 1;
256 /* note-on + off in same cycle */
257 sc->miditable[note] = 0;
258 sc->adsr_cnt[note] = 0;
259 sc->phase[note] = -10;
263 // synthesize actual sound
264 sc->synthesize(sc, note, vol, rs->freqs[note], n_samples, left, right);
266 if (sc->adsr_cnt[note] == 0) {
267 //printf("Note %d,%d released\n", chn, note);
268 sc->miditable[note] = 0;
269 sc->adsr_amp[note] = 0;
270 sc->phase[note] = -10;
272 //printf("[off] Now %d keys active on chn %d\n", sc->keycomp, chn);
276 /* synthesize a BUFFER_SIZE_SAMPLES's of audio-data */
277 static void synth_fragment (void *synth, const size_t n_samples, float *left, float *right) {
278 RSSynthesizer* rs = (RSSynthesizer*)synth;
279 memset (left, 0, n_samples * sizeof(float));
280 memset (right, 0, n_samples * sizeof(float));
285 for (c=0; c < 16; ++c) {
286 for (k=0; k < 128; ++k) {
287 if (rs->sc[c].miditable[k] == 0) continue;
288 process_key(synth, c, k, n_samples, left, right);
290 keycomp += rs->sc[c].keycomp;
293 #if 1 // key-compression
294 float kctgt = 8.0 / (float)(keycomp + 7.0);
295 if (kctgt < .5) kctgt = .5;
296 if (kctgt > 1.0) kctgt = 1.0;
297 const float _w = rs->kcfilt;
298 for (i=0; i < n_samples; ++i) {
299 rs->kcgain += _w * (kctgt - rs->kcgain);
300 left[i] *= rs->kcgain;
301 right[i] *= rs->kcgain;
307 static void synth_reset_channel(RSSynthChannel* sc) {
309 for (k=0; k < 128; ++k) {
313 sc->miditable[k] = 0;
319 static void synth_reset(void *synth) {
320 RSSynthesizer* rs = (RSSynthesizer*)synth;
322 for (c=0; c < 16; ++c) {
323 synth_reset_channel(&(rs->sc[c]));
328 static void synth_load(RSSynthChannel *sc, const double rate,
329 SynthFunction synthesize,
330 ADSRcfg const * const adsr) {
331 synth_reset_channel(sc);
332 init_adsr(&sc->adsr, rate,
333 adsr->tme[0], adsr->tme[1], adsr->tme[2],
334 adsr->vol[0], adsr->vol[1]);
335 sc->synthesize = synthesize;
340 * internal abstraction of MIDI data handling
342 static void synth_process_midi_event(void *synth, struct rmidi_event_t *ev) {
343 RSSynthesizer* rs = (RSSynthesizer*)synth;
346 rs->sc[ev->channel].midimsgs[ev->d.tone.note] |= 1;
347 if (rs->sc[ev->channel].miditable[ev->d.tone.note] <= 0)
348 rs->sc[ev->channel].miditable[ev->d.tone.note] = ev->d.tone.velocity;
351 rs->sc[ev->channel].midimsgs[ev->d.tone.note] |= 2;
352 if (rs->sc[ev->channel].miditable[ev->d.tone.note] > 0)
353 rs->sc[ev->channel].miditable[ev->d.tone.note] *= -1.0;
358 if (ev->d.control.param == 0x00 || ev->d.control.param == 0x20) {
359 /* 0x00 and 0x20 are used for BANK select */
362 if (ev->d.control.param == 121) {
363 /* reset all controllers */
366 if (ev->d.control.param == 120 || ev->d.control.param == 123) {
367 /* Midi panic: 120: all sound off, 123: all notes off*/
368 synth_reset_channel(&(rs->sc[ev->channel]));
371 if (ev->d.control.param >= 120) {
372 /* params 122-127 are reserved - skip them. */
381 /******************************************************************************
382 * PUBLIC API (used by lv2.c)
386 * align LV2 and internal synth buffers
387 * call synth_fragment as often as needed for the given LV2 buffer size
389 * @param synth synth-handle
390 * @param written samples written so far (offset in \ref out)
391 * @param nframes total samples to synthesize and write to the \out buffer
392 * @param out pointer to stereo output buffers
393 * @return end of buffer (written + nframes)
395 static uint32_t synth_sound (void *synth, uint32_t written, const uint32_t nframes, float **out) {
396 RSSynthesizer* rs = (RSSynthesizer*)synth;
398 while (written < nframes) {
399 uint32_t nremain = nframes - written;
401 if (rs->boffset >= BUFFER_SIZE_SAMPLES) {
403 synth_fragment(rs, BUFFER_SIZE_SAMPLES, rs->buf[0], rs->buf[1]);
406 uint32_t nread = MIN(nremain, (BUFFER_SIZE_SAMPLES - rs->boffset));
408 memcpy(&out[0][written], &rs->buf[0][rs->boffset], nread*sizeof(float));
409 memcpy(&out[1][written], &rs->buf[1][rs->boffset], nread*sizeof(float));
412 rs->boffset += nread;
418 * parse raw midi-data.
420 * @param synth synth-handle
421 * @param data 8bit midi message
422 * @param size number of bytes in the midi-message
424 static void synth_parse_midi(void *synth, const uint8_t *data, const size_t size) {
425 if (size < 2 || size > 3) return;
426 // All messages need to be 3 bytes; except program-changes: 2bytes.
427 if (size == 2 && (data[0] & 0xf0) != 0xC0) return;
429 struct rmidi_event_t ev;
431 ev.channel = data[0]&0x0f;
432 switch (data[0] & 0xf0) {
435 ev.d.tone.note=data[1]&0x7f;
436 ev.d.tone.velocity=data[2]&0x7f;
440 ev.d.tone.note=data[1]&0x7f;
441 ev.d.tone.velocity=data[2]&0x7f;
444 ev.type=CONTROL_CHANGE;
445 ev.d.control.param=data[1]&0x7f;
446 ev.d.control.value=data[2]&0x7f;
449 ev.type=PROGRAM_CHANGE;
450 ev.d.control.value=data[1]&0x7f;
455 synth_process_midi_event(synth, &ev);
458 static const uint8_t jingle[] = { 71 ,71 ,71 ,71 ,71 ,71 ,71 ,74 ,67 ,69 ,71 ,72 ,72 ,72 ,72 ,72 ,71 ,71 ,71 ,71 ,71 ,69 ,69 ,71 ,69 ,74 ,71 ,71 ,71 ,71 ,71 ,71 ,71 ,74 ,67 ,69 ,71 ,72 ,72 ,72 ,72 ,72 ,71 ,71 ,71 ,71 ,74 ,74 ,72 ,69 ,67 ,62 ,62 ,71 ,69 ,67 ,62 ,62 ,62 ,62 ,71 ,69 ,67 ,64 ,64 ,64 ,72 ,71 ,69 ,66 ,74 ,76 ,74 ,72 ,69 ,71 ,62 ,62 ,71 ,69 ,67 ,62 ,62 ,62 ,62 ,71 ,69 ,67 ,64 ,64 ,64 ,72 ,71 ,69 ,74 ,74 ,74 ,74 ,76 ,74 ,72 ,69 ,67 ,74 ,71 ,71 ,71 ,71 ,71 ,71 ,71 ,74 ,67 ,69 ,71 ,72 ,72 ,72 ,72 ,72 ,71 ,71 ,71 ,71 ,71 ,69 ,69 ,71 ,69 ,74 ,71 ,71 ,71 ,71 ,71 ,71 ,71 ,74 ,67 ,69 ,71 ,72 ,72 ,72 ,72 ,72 ,71 ,71 ,71 ,71 ,74 ,74 ,72 ,69 ,67 };
460 static void synth_parse_xmas(void *synth, const uint8_t *data, const size_t size) {
461 RSSynthesizer* rs = (RSSynthesizer*)synth;
462 if (size < 2 || size > 3) return;
463 // All messages need to be 3 bytes; except program-changes: 2bytes.
464 if (size == 2 && (data[0] & 0xf0) != 0xC0) return;
466 struct rmidi_event_t ev;
468 ev.channel = data[0]&0x0f;
469 switch (data[0] & 0xf0) {
472 ev.d.tone.note=jingle[rs->xmas_off++];
473 ev.d.tone.velocity=data[2]&0x7f;
474 if (rs->xmas_off >= sizeof(jingle)) rs->xmas_off = 0;
478 ev.d.tone.note=jingle[rs->xmas_on++];
479 ev.d.tone.velocity=data[2]&0x7f;
480 if (rs->xmas_on >= sizeof(jingle)) rs->xmas_on = 0;
483 ev.type=CONTROL_CHANGE;
484 ev.d.control.param=data[1]&0x7f;
485 ev.d.control.value=data[2]&0x7f;
488 ev.type=PROGRAM_CHANGE;
489 ev.d.control.value=data[1]&0x7f;
494 synth_process_midi_event(synth, &ev);
497 * initialize the synth
498 * This should be called after synth_alloc()
499 * as soon as the sample-rate is known
501 * @param synth synth-handle
502 * @param rate sample-rate
504 static void synth_init(void *synth, double rate) {
505 RSSynthesizer* rs = (RSSynthesizer*)synth;
507 rs->boffset = BUFFER_SIZE_SAMPLES;
508 const float tuning = 440;
510 for (k=0; k < 128; k++) {
511 rs->freqs[k] = (tuning / 32.0f) * powf(2, (k - 9.0) / 12.0) / rate;
512 assert(rs->freqs[k] < M_PI/2); // otherwise spatialization may phase out..
514 rs->kcfilt = 12.0 / rate;
517 for (c=0; c < 16; c++) {
518 synth_load(&rs->sc[c], rate, &synthesize_sineP, &piano_adsr);
525 * Allocate data-structure, create a handle for all other synth_* functions.
527 * This data should be freeded with \ref synth_free when the synth is no
530 * The synth can only be used after calling \rev synth_init as well.
532 * @return synth-handle
534 static void * synth_alloc(void) {
535 return calloc(1, sizeof(RSSynthesizer));
539 * release synth data structure
540 * @param synth synth-handle
542 static void synth_free(void *synth) {
545 /* vi:set ts=8 sts=2 sw=2 et: */