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
30 #ifndef BUFFER_SIZE_SAMPLES
31 #define BUFFER_SIZE_SAMPLES 64
35 #define MIN(A, B) ( (A) < (B) ? (A) : (B) )
38 /* internal MIDI event abstraction */
47 struct rmidi_event_t {
48 enum RMIDI_EV_TYPE type;
49 uint8_t channel; /**< the MIDI channel number 0-15 */
63 uint32_t tme[3]; // attack, decay, release times [settings:ms || internal:samples]
64 float vol[2]; // attack, sustain volume [0..1]
65 uint32_t off[3]; // internal use (added attack,decay,release times)
68 typedef struct _RSSynthChannel {
70 uint32_t adsr_cnt[128];
72 float phase[128]; // various use, zero'ed on note-on
73 int8_t miditable[128]; // internal, note-on/off velocity
75 void (*synthesize) (struct _RSSynthChannel* sc,
76 const uint8_t note, const float vol, const float pc,
77 const size_t n_samples, float* left, float* right);
80 typedef void (*SynthFunction) (RSSynthChannel* sc,
81 const uint8_t note, const float vol, const float pc,
82 const size_t n_samples, float* left, float* right);
86 float buf [2][BUFFER_SIZE_SAMPLES];
87 RSSynthChannel sc[16];
95 /* initialize ADSR values
97 * @param rate sample-rate
98 * @param a attack time in seconds
99 * @param d decay time in seconds
100 * @param r release time in seconds
101 * @param avol attack gain [0..1]
102 * @param svol sustain volume level [0..1]
104 static void init_adsr(ADSRcfg *adsr, const double rate,
105 const uint32_t a, const uint32_t d, const uint32_t r,
106 const float avol, const float svol) {
110 adsr->tme[0] = a * rate / 1000.0;
111 adsr->tme[1] = d * rate / 1000.0;
112 adsr->tme[2] = r * rate / 1000.0;
114 assert(adsr->tme[0] > 32);
115 assert(adsr->tme[1] > 32);
116 assert(adsr->tme[2] > 32);
117 assert(adsr->vol[0] >=0 && adsr->vol[1] <= 1.0);
118 assert(adsr->vol[1] >=0 && adsr->vol[1] <= 1.0);
120 adsr->off[0] = adsr->tme[0];
121 adsr->off[1] = adsr->tme[1] + adsr->off[0];
122 adsr->off[2] = adsr->tme[2] + adsr->off[1];
125 /* calculate per-sample, per-key envelope */
126 static inline float adsr_env(RSSynthChannel *sc, const uint8_t note) {
128 if (sc->adsr_cnt[note] < sc->adsr.off[0]) {
130 const uint32_t p = ++sc->adsr_cnt[note];
131 if (p == sc->adsr.tme[0]) {
132 sc->adsr_amp[note] = sc->adsr.vol[0];
133 return sc->adsr.vol[0];
135 const float d = sc->adsr.vol[0] - sc->adsr_amp[note];
136 return sc->adsr_amp[note] + (p / (float) sc->adsr.tme[0]) * d;
139 else if (sc->adsr_cnt[note] < sc->adsr.off[1]) {
141 const uint32_t p = ++sc->adsr_cnt[note] - sc->adsr.off[0];
142 if (p == sc->adsr.tme[1]) {
143 sc->adsr_amp[note] = sc->adsr.vol[1];
144 return sc->adsr.vol[1];
146 const float d = sc->adsr.vol[1] - sc->adsr_amp[note];
147 return sc->adsr_amp[note] + (p / (float) sc->adsr.tme[1]) * d;
150 else if (sc->adsr_cnt[note] == sc->adsr.off[1]) {
152 return sc->adsr.vol[1];
154 else if (sc->adsr_cnt[note] < sc->adsr.off[2]) {
156 const uint32_t p = ++sc->adsr_cnt[note] - sc->adsr.off[1];
157 if (p == sc->adsr.tme[2]) {
158 sc->adsr_amp[note] = 0;
161 const float d = 0 - sc->adsr_amp[note];
162 return sc->adsr_amp[note] + (p / (float) sc->adsr.tme[2]) * d;
166 sc->adsr_cnt[note] = 0;
172 /*****************************************************************************/
173 /* piano like sound w/slight stereo phase */
174 static void synthesize_sineP (RSSynthChannel* sc,
175 const uint8_t note, const float vol, const float fq,
176 const size_t n_samples, float* left, float* right) {
179 float phase = sc->phase[note];
181 for (i=0; i < n_samples; ++i) {
182 float env = adsr_env(sc, note);
183 if (sc->adsr_cnt[note] == 0) break;
184 const float amp = vol * env;
186 left[i] += amp * sinf(2.0 * M_PI * phase);
187 left[i] += .300 * amp * sinf(2.0 * M_PI * phase * 2.0);
188 left[i] += .150 * amp * sinf(2.0 * M_PI * phase * 3.0);
189 left[i] += .080 * amp * sinf(2.0 * M_PI * phase * 4.0);
190 //left[i] -= .007 * amp * sinf(2.0 * M_PI * phase * 5.0);
191 //left[i] += .010 * amp * sinf(2.0 * M_PI * phase * 6.0);
192 left[i] += .020 * amp * sinf(2.0 * M_PI * phase * 7.0);
194 right[i] += amp * sinf(2.0 * M_PI * phase);
195 right[i] += .300 * amp * sinf(2.0 * M_PI * phase * 2.0);
196 right[i] += .150 * amp * sinf(2.0 * M_PI * phase * 3.0);
197 right[i] -= .080 * amp * sinf(2.0 * M_PI * phase * 4.0);
198 //right[i] += .007 * amp * sinf(2.0 * M_PI * phase * 5.0);
199 //right[i] += .010 * amp * sinf(2.0 * M_PI * phase * 6.0);
200 right[i] -= .020 * amp * sinf(2.0 * M_PI * phase * 7.0);
201 if (phase > 1.0) phase -= 2.0;
203 sc->phase[note] = phase;
206 static const ADSRcfg piano_adsr = {{ 5, 800, 100}, { 1.0, 0.0}, {0,0,0}};
208 /*****************************************************************************/
211 /* process note - move through ADSR states, count active keys,.. */
212 static void process_key (void *synth,
213 const uint8_t chn, const uint8_t note,
214 const size_t n_samples, float *left, float *right)
216 RSSynthesizer* rs = (RSSynthesizer*)synth;
217 RSSynthChannel* sc = &rs->sc[chn];
218 const int8_t vel = sc->miditable[note];
219 const float vol = /* master_volume */ 0.25 * fabsf(vel) / 127.0;
220 const float phase = sc->phase[note];
222 if (phase == -10 && vel > 0) {
224 assert(sc->adsr_cnt[note] == 0);
225 sc->adsr_amp[note] = 0;
226 sc->adsr_cnt[note] = 0;
229 //printf("[On] Now %d keys active on chn %d\n", sc->keycomp, chn);
231 else if (phase >= -1.0 && phase <= 1.0 && vel > 0) {
232 // sustain note or re-start note while adsr in progress:
233 if (sc->adsr_cnt[note] > sc->adsr.off[1]) {
235 sc->adsr_amp[note] = adsr_env(sc, note);
236 sc->adsr_cnt[note] = 0;
239 else if (phase >= -1.0 && phase <= 1.0 && vel < 0) {
241 if (sc->adsr_cnt[note] <= sc->adsr.off[1]) {
242 if (sc->adsr_cnt[note] != sc->adsr.off[1]) {
244 sc->adsr_amp[note] = adsr_env(sc, note);
246 sc->adsr_cnt[note] = sc->adsr.off[1] + 1;
250 /* note-on + off in same cycle */
251 sc->miditable[note] = 0;
252 sc->adsr_cnt[note] = 0;
253 sc->phase[note] = -10;
257 // synthesize actual sound
258 sc->synthesize(sc, note, vol, rs->freqs[note], n_samples, left, right);
260 if (sc->adsr_cnt[note] == 0) {
261 //printf("Note %d,%d released\n", chn, note);
262 sc->miditable[note] = 0;
263 sc->adsr_amp[note] = 0;
264 sc->phase[note] = -10;
266 //printf("[off] Now %d keys active on chn %d\n", sc->keycomp, chn);
270 /* synthesize a BUFFER_SIZE_SAMPLES's of audio-data */
271 static void synth_fragment (void *synth, const size_t n_samples, float *left, float *right) {
272 RSSynthesizer* rs = (RSSynthesizer*)synth;
273 memset (left, 0, n_samples * sizeof(float));
274 memset (right, 0, n_samples * sizeof(float));
279 for (c=0; c < 16; ++c) {
280 for (k=0; k < 128; ++k) {
281 if (rs->sc[c].miditable[k] == 0) continue;
282 process_key(synth, c, k, n_samples, left, right);
284 keycomp += rs->sc[c].keycomp;
287 #if 1 // key-compression
288 float kctgt = 8.0 / (float)(keycomp + 7.0);
289 if (kctgt < .5) kctgt = .5;
290 if (kctgt > 1.0) kctgt = 1.0;
291 const float _w = rs->kcfilt;
292 for (i=0; i < n_samples; ++i) {
293 rs->kcgain += _w * (kctgt - rs->kcgain);
294 left[i] *= rs->kcgain;
295 right[i] *= rs->kcgain;
301 static void synth_reset_channel(RSSynthChannel* sc) {
303 for (k=0; k < 128; ++k) {
307 sc->miditable[k] = 0;
312 static void synth_reset(void *synth) {
313 RSSynthesizer* rs = (RSSynthesizer*)synth;
315 for (c=0; c < 16; ++c) {
316 synth_reset_channel(&(rs->sc[c]));
321 static void synth_load(RSSynthChannel *sc, const double rate,
322 SynthFunction synthesize,
323 ADSRcfg const * const adsr) {
324 synth_reset_channel(sc);
325 init_adsr(&sc->adsr, rate,
326 adsr->tme[0], adsr->tme[1], adsr->tme[2],
327 adsr->vol[0], adsr->vol[1]);
328 sc->synthesize = synthesize;
333 * internal abstraction of MIDI data handling
335 static void synth_process_midi_event(void *synth, struct rmidi_event_t *ev) {
336 RSSynthesizer* rs = (RSSynthesizer*)synth;
339 if (rs->sc[ev->channel].miditable[ev->d.tone.note] <= 0)
340 rs->sc[ev->channel].miditable[ev->d.tone.note] = ev->d.tone.velocity;
343 if (rs->sc[ev->channel].miditable[ev->d.tone.note] > 0)
344 rs->sc[ev->channel].miditable[ev->d.tone.note] *= -1.0;
349 if (ev->d.control.param == 0x00 || ev->d.control.param == 0x20) {
350 /* 0x00 and 0x20 are used for BANK select */
353 if (ev->d.control.param == 121) {
354 /* reset all controllers */
357 if (ev->d.control.param == 120 || ev->d.control.param == 123) {
358 /* Midi panic: 120: all sound off, 123: all notes off*/
359 synth_reset_channel(&(rs->sc[ev->channel]));
362 if (ev->d.control.param >= 120) {
363 /* params 122-127 are reserved - skip them. */
372 /******************************************************************************
373 * PUBLIC API (used by lv2.c)
377 * align LV2 and internal synth buffers
378 * call synth_fragment as often as needed for the given LV2 buffer size
380 * @param synth synth-handle
381 * @param written samples written so far (offset in \ref out)
382 * @param nframes total samples to synthesize and write to the \out buffer
383 * @param out pointer to stereo output buffers
384 * @return end of buffer (written + nframes)
386 static uint32_t synth_sound (void *synth, uint32_t written, const uint32_t nframes, float **out) {
387 RSSynthesizer* rs = (RSSynthesizer*)synth;
389 while (written < nframes) {
390 uint32_t nremain = nframes - written;
392 if (rs->boffset >= BUFFER_SIZE_SAMPLES) {
394 synth_fragment(rs, BUFFER_SIZE_SAMPLES, rs->buf[0], rs->buf[1]);
397 uint32_t nread = MIN(nremain, (BUFFER_SIZE_SAMPLES - rs->boffset));
399 memcpy(&out[0][written], &rs->buf[0][rs->boffset], nread*sizeof(float));
400 memcpy(&out[1][written], &rs->buf[1][rs->boffset], nread*sizeof(float));
403 rs->boffset += nread;
409 * parse raw midi-data.
411 * @param synth synth-handle
412 * @param data 8bit midi message
413 * @param size number of bytes in the midi-message
415 static void synth_parse_midi(void *synth, const uint8_t *data, const size_t size) {
416 if (size < 2 || size > 3) return;
417 // All messages need to be 3 bytes; except program-changes: 2bytes.
418 if (size == 2 && (data[0] & 0xf0) != 0xC0) return;
420 struct rmidi_event_t ev;
422 ev.channel = data[0]&0x0f;
423 switch (data[0] & 0xf0) {
426 ev.d.tone.note=data[1]&0x7f;
427 ev.d.tone.velocity=data[2]&0x7f;
431 ev.d.tone.note=data[1]&0x7f;
432 ev.d.tone.velocity=data[2]&0x7f;
435 ev.type=CONTROL_CHANGE;
436 ev.d.control.param=data[1]&0x7f;
437 ev.d.control.value=data[2]&0x7f;
440 ev.type=PROGRAM_CHANGE;
441 ev.d.control.value=data[1]&0x7f;
446 synth_process_midi_event(synth, &ev);
450 * initialize the synth
451 * This should be called after synth_alloc()
452 * as soon as the sample-rate is known
454 * @param synth synth-handle
455 * @param rate sample-rate
457 static void synth_init(void *synth, double rate) {
458 RSSynthesizer* rs = (RSSynthesizer*)synth;
460 rs->boffset = BUFFER_SIZE_SAMPLES;
461 const float tuning = 440;
463 for (k=0; k < 128; k++) {
464 rs->freqs[k] = (2.0 * tuning / 32.0f) * powf(2, (k - 9.0) / 12.0) / rate;
465 assert(rs->freqs[k] < M_PI/2); // otherwise spatialization may phase out..
467 rs->kcfilt = 12.0 / rate;
470 for (c=0; c < 16; c++) {
471 synth_load(&rs->sc[c], rate, &synthesize_sineP, &piano_adsr);
476 * Allocate data-structure, create a handle for all other synth_* functions.
478 * This data should be freeded with \ref synth_free when the synth is no
481 * The synth can only be used after calling \rev synth_init as well.
483 * @return synth-handle
485 static void * synth_alloc(void) {
486 return calloc(1, sizeof(RSSynthesizer));
490 * release synth data structure
491 * @param synth synth-handle
493 static void synth_free(void *synth) {
496 /* vi:set ts=8 sts=2 sw=2 et: */