eff01d8d69270f40b9b32a104fefbe7425acf62a
[ardour.git] / libs / plugins / reasonablesynth.lv2 / rsynth.c
1 /* reasonable simple synth
2  *
3  * Copyright (C) 2013 Robin Gareus <robin@gareus.org>
4  *
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)
8  * any later version.
9  *
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.
14  *
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.
18  */
19
20 #ifndef _GNU_SOURCE
21 #define _GNU_SOURCE // needed for M_PI
22 #endif
23
24 #include <math.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <stdint.h>
28 #include <stdbool.h>
29 #include <assert.h>
30
31 #ifndef BUFFER_SIZE_SAMPLES
32 #define BUFFER_SIZE_SAMPLES 64
33 #endif
34
35 #ifndef MIN
36 #define MIN(A, B) ( (A) < (B) ? (A) : (B) )
37 #endif
38
39 /* internal MIDI event abstraction */
40 enum RMIDI_EV_TYPE {
41   INVALID=0,
42   NOTE_ON,
43   NOTE_OFF,
44   PROGRAM_CHANGE,
45   CONTROL_CHANGE,
46 };
47
48 struct rmidi_event_t {
49   enum RMIDI_EV_TYPE type;
50   uint8_t channel; /**< the MIDI channel number 0-15 */
51   union {
52     struct {
53       uint8_t note;
54       uint8_t velocity;
55     } tone;
56     struct {
57       uint8_t param;
58       uint8_t value;
59     } control;
60   } d;
61 };
62
63 typedef struct {
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)
67 } ADSRcfg;
68
69 typedef struct _RSSynthChannel {
70   uint32_t  keycomp;
71   uint32_t  adsr_cnt[128];
72   float     adsr_amp[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
76   ADSRcfg   adsr;
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);
80 } RSSynthChannel;
81
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);
85
86 typedef struct {
87   uint32_t       boffset;
88   float          buf [2][BUFFER_SIZE_SAMPLES];
89   RSSynthChannel sc[16];
90   float          freqs[128];
91   float          kcgain;
92   float          kcfilt;
93   double         rate;
94   uint32_t       xmas_on;
95   uint32_t       xmas_off;
96 } RSSynthesizer;
97
98
99 /* initialize ADSR values
100  *
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]
107  */
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) {
111
112   adsr->vol[0] = avol;
113   adsr->vol[1] = 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;
117
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);
123
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];
127 }
128
129 /* calculate per-sample, per-key envelope */
130 static inline float adsr_env(RSSynthChannel *sc, const uint8_t note) {
131
132   if (sc->adsr_cnt[note] < sc->adsr.off[0]) {
133     // attack
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];
138     } else {
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;
141     }
142   }
143   else if (sc->adsr_cnt[note] < sc->adsr.off[1]) {
144     // decay
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];
149     } else {
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;
152     }
153   }
154   else if (sc->adsr_cnt[note] == sc->adsr.off[1]) {
155     // sustain
156     return sc->adsr.vol[1];
157   }
158   else if (sc->adsr_cnt[note] < sc->adsr.off[2]) {
159     // release
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;
163       return 0;
164     } else {
165       const float d = 0 - sc->adsr_amp[note];
166       return sc->adsr_amp[note] + (p / (float) sc->adsr.tme[2]) * d;
167     }
168   }
169   else {
170     sc->adsr_cnt[note] = 0;
171     return 0;
172   }
173 }
174
175
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) {
181
182   size_t i;
183   float phase = sc->phase[note];
184
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;
189     if (amp > 1e-10) {
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);
197       phase += fq;
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     } else {
206       phase += fq;
207     }
208     if (phase > 1.0) phase -= 2.0;
209   }
210   sc->phase[note] = phase;
211 }
212
213 static const ADSRcfg piano_adsr = {{   5, 800,  100}, { 1.0,  0.0}, {0,0,0}};
214
215 /*****************************************************************************/
216
217
218 /* process note - move through ADSR states, count active keys,.. */
219 static void process_key (void *synth,
220     const uint8_t chn, const uint8_t note,
221     const size_t n_samples, float *left, float *right)
222 {
223   RSSynthesizer*  rs = (RSSynthesizer*)synth;
224   RSSynthChannel* sc = &rs->sc[chn];
225   const int8_t vel = sc->miditable[note];
226   const int8_t msg = sc->midimsgs[note];
227   const float vol = /* master_volume */ 0.1 * fabsf(vel) / 127.0;
228   const float phase = sc->phase[note];
229   sc->midimsgs[note] = 0;
230
231   if (phase == -10 && vel > 0) {
232     // new note on
233     assert(sc->adsr_cnt[note] == 0);
234     sc->adsr_amp[note] = 0;
235     sc->adsr_cnt[note] = 0;
236     sc->phase[note] = 0;
237     sc->keycomp++;
238     //printf("[On] Now %d keys active on chn %d\n", sc->keycomp, chn);
239   }
240   else if (phase >= -1.0 && phase <= 1.0 && vel > 0) {
241     // sustain note or re-start note while adsr in progress:
242     if (sc->adsr_cnt[note] > sc->adsr.off[1] || msg == 3) {
243       // x-fade to attack
244       sc->adsr_amp[note] = adsr_env(sc, note);
245       sc->adsr_cnt[note] = 0;
246     }
247   }
248   else if (phase >= -1.0 && phase <= 1.0 && vel < 0) {
249     // note off
250     if (sc->adsr_cnt[note] <= sc->adsr.off[1]) {
251       if (sc->adsr_cnt[note] != sc->adsr.off[1]) {
252         // x-fade to release
253         sc->adsr_amp[note] = adsr_env(sc, note);
254       }
255       sc->adsr_cnt[note] = sc->adsr.off[1] + 1;
256     }
257   }
258   else {
259     /* note-on + off in same cycle */
260     sc->miditable[note] = 0;
261     sc->adsr_cnt[note] = 0;
262     sc->phase[note] = -10;
263     return;
264   }
265
266   // synthesize actual sound
267   sc->synthesize(sc, note, vol, rs->freqs[note], n_samples, left, right);
268
269   if (sc->adsr_cnt[note] == 0) {
270     //printf("Note %d,%d released\n", chn, note);
271     sc->miditable[note] = 0;
272     sc->adsr_amp[note] = 0;
273     sc->phase[note] = -10;
274     sc->keycomp--;
275     //printf("[off] Now %d keys active on chn %d\n", sc->keycomp, chn);
276   }
277 }
278
279 /* synthesize a BUFFER_SIZE_SAMPLES's of audio-data */
280 static void synth_fragment (void *synth, const size_t n_samples, float *left, float *right) {
281   RSSynthesizer* rs = (RSSynthesizer*)synth;
282   memset (left, 0, n_samples * sizeof(float));
283   memset (right, 0, n_samples * sizeof(float));
284   uint8_t keycomp = 0;
285   int c,k;
286   size_t i;
287
288   for (c=0; c < 16; ++c) {
289     for (k=0; k < 128; ++k) {
290       if (rs->sc[c].miditable[k] == 0) continue;
291       process_key(synth, c, k, n_samples, left, right);
292     }
293     keycomp += rs->sc[c].keycomp;
294   }
295
296 #if 1 // key-compression
297   float kctgt = 8.0 / (float)(keycomp + 7.0);
298   if (kctgt < .5) kctgt = .5;
299   if (kctgt > 1.0) kctgt = 1.0;
300   const float _w = rs->kcfilt;
301   for (i=0; i < n_samples; ++i) {
302     rs->kcgain += _w * (kctgt - rs->kcgain);
303     left[i]  *= rs->kcgain;
304     right[i] *= rs->kcgain;
305   }
306   rs->kcgain += 1e-12;
307 #endif
308 }
309
310 static void synth_reset_channel(RSSynthChannel* sc) {
311   int k;
312   for (k=0; k < 128; ++k) {
313     sc->adsr_cnt[k]  = 0;
314     sc->adsr_amp[k]  = 0;
315     sc->phase[k]     = -10;
316     sc->miditable[k] = 0;
317     sc->midimsgs[k]  = 0;
318   }
319   sc->keycomp = 0;
320 }
321
322 static void synth_reset(void *synth) {
323   RSSynthesizer* rs = (RSSynthesizer*)synth;
324   int c;
325   for (c=0; c < 16; ++c) {
326     synth_reset_channel(&(rs->sc[c]));
327   }
328   rs->kcgain = 0;
329 }
330
331 static void synth_load(RSSynthChannel *sc, const double rate,
332     SynthFunction synthesize,
333     ADSRcfg const * const adsr) {
334   synth_reset_channel(sc);
335   init_adsr(&sc->adsr, rate,
336       adsr->tme[0], adsr->tme[1], adsr->tme[2],
337       adsr->vol[0], adsr->vol[1]);
338   sc->synthesize = synthesize;
339 }
340
341
342 /**
343  * internal abstraction of MIDI data handling
344  */
345 static void synth_process_midi_event(void *synth, struct rmidi_event_t *ev) {
346   RSSynthesizer* rs = (RSSynthesizer*)synth;
347   switch(ev->type) {
348     case NOTE_ON:
349       rs->sc[ev->channel].midimsgs[ev->d.tone.note] |= 1;
350       if (rs->sc[ev->channel].miditable[ev->d.tone.note] <= 0)
351         rs->sc[ev->channel].miditable[ev->d.tone.note] = ev->d.tone.velocity;
352       break;
353     case NOTE_OFF:
354       rs->sc[ev->channel].midimsgs[ev->d.tone.note] |= 2;
355       if (rs->sc[ev->channel].miditable[ev->d.tone.note] > 0)
356         rs->sc[ev->channel].miditable[ev->d.tone.note] *= -1.0;
357       break;
358     case PROGRAM_CHANGE:
359       break;
360     case CONTROL_CHANGE:
361       if (ev->d.control.param == 0x00 || ev->d.control.param == 0x20) {
362         /*  0x00 and 0x20 are used for BANK select */
363         break;
364       } else
365       if (ev->d.control.param == 121) {
366         /* reset all controllers */
367         break;
368       } else
369       if (ev->d.control.param == 120 || ev->d.control.param == 123) {
370         /* Midi panic: 120: all sound off, 123: all notes off*/
371         synth_reset_channel(&(rs->sc[ev->channel]));
372         break;
373       } else
374       if (ev->d.control.param >= 120) {
375         /* params 122-127 are reserved - skip them. */
376         break;
377       }
378       break;
379     default:
380       break;
381   }
382 }
383
384 /******************************************************************************
385  * PUBLIC API (used by lv2.c)
386  */
387
388 /**
389  * align LV2 and internal synth buffers
390  * call synth_fragment as often as needed for the given LV2 buffer size
391  *
392  * @param synth synth-handle
393  * @param written samples written so far (offset in \ref out)
394  * @param nframes total samples to synthesize and write to the \out buffer
395  * @param out pointer to stereo output buffers
396  * @return end of buffer (written + nframes)
397  */
398 static uint32_t synth_sound (void *synth, uint32_t written, const uint32_t nframes, float **out) {
399   RSSynthesizer* rs = (RSSynthesizer*)synth;
400
401   while (written < nframes) {
402     uint32_t nremain = nframes - written;
403
404     if (rs->boffset >= BUFFER_SIZE_SAMPLES)  {
405       rs->boffset = 0;
406       synth_fragment(rs, BUFFER_SIZE_SAMPLES, rs->buf[0], rs->buf[1]);
407     }
408
409     uint32_t nread = MIN(nremain, (BUFFER_SIZE_SAMPLES - rs->boffset));
410
411     memcpy(&out[0][written], &rs->buf[0][rs->boffset], nread*sizeof(float));
412     memcpy(&out[1][written], &rs->buf[1][rs->boffset], nread*sizeof(float));
413
414     written += nread;
415     rs->boffset += nread;
416   }
417   return written;
418 }
419
420 /**
421  * parse raw midi-data.
422  *
423  * @param synth synth-handle
424  * @param data 8bit midi message
425  * @param size number of bytes in the midi-message
426  */
427 static void synth_parse_midi(void *synth, const uint8_t *data, const size_t size) {
428   if (size < 2 || size > 3) return;
429   // All messages need to be 3 bytes; except program-changes: 2bytes.
430   if (size == 2 && (data[0] & 0xf0)  != 0xC0) return;
431
432   struct rmidi_event_t ev;
433
434   ev.channel = data[0]&0x0f;
435   switch (data[0] & 0xf0) {
436     case 0x80:
437       ev.type=NOTE_OFF;
438       ev.d.tone.note=data[1]&0x7f;
439       ev.d.tone.velocity=data[2]&0x7f;
440       break;
441     case 0x90:
442       ev.type=NOTE_ON;
443       ev.d.tone.note=data[1]&0x7f;
444       ev.d.tone.velocity=data[2]&0x7f;
445       break;
446     case 0xB0:
447       ev.type=CONTROL_CHANGE;
448       ev.d.control.param=data[1]&0x7f;
449       ev.d.control.value=data[2]&0x7f;
450       break;
451     case 0xC0:
452       ev.type=PROGRAM_CHANGE;
453       ev.d.control.value=data[1]&0x7f;
454       break;
455     default:
456       return;
457   }
458   synth_process_midi_event(synth, &ev);
459 }
460
461 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 };
462
463 static void synth_parse_xmas(void *synth, const uint8_t *data, const size_t size) {
464   RSSynthesizer* rs = (RSSynthesizer*)synth;
465   if (size < 2 || size > 3) return;
466   // All messages need to be 3 bytes; except program-changes: 2bytes.
467   if (size == 2 && (data[0] & 0xf0)  != 0xC0) return;
468
469   struct rmidi_event_t ev;
470
471   ev.channel = data[0]&0x0f;
472   switch (data[0] & 0xf0) {
473     case 0x80:
474       ev.type=NOTE_OFF;
475       ev.d.tone.note=jingle[rs->xmas_off++];
476       ev.d.tone.velocity=data[2]&0x7f;
477       if (rs->xmas_off >= sizeof(jingle)) rs->xmas_off = 0;
478       break;
479     case 0x90:
480       ev.type=NOTE_ON;
481       ev.d.tone.note=jingle[rs->xmas_on++];
482       ev.d.tone.velocity=data[2]&0x7f;
483       if (rs->xmas_on >= sizeof(jingle)) rs->xmas_on = 0;
484       break;
485     case 0xB0:
486       ev.type=CONTROL_CHANGE;
487       ev.d.control.param=data[1]&0x7f;
488       ev.d.control.value=data[2]&0x7f;
489       break;
490     case 0xC0:
491       ev.type=PROGRAM_CHANGE;
492       ev.d.control.value=data[1]&0x7f;
493       break;
494     default:
495       return;
496   }
497   synth_process_midi_event(synth, &ev);
498 }
499 /**
500  * initialize the synth
501  * This should be called after synth_alloc()
502  * as soon as the sample-rate is known
503  *
504  * @param synth synth-handle
505  * @param rate sample-rate
506  */
507 static void synth_init(void *synth, double rate) {
508   RSSynthesizer* rs = (RSSynthesizer*)synth;
509   rs->rate = rate;
510   rs->boffset = BUFFER_SIZE_SAMPLES;
511   const float tuning = 440;
512   int c,k;
513   for (k=0; k < 128; k++) {
514     rs->freqs[k] = (tuning / 32.0f) * powf(2, (k - 9.0) / 12.0) / rate;
515     assert(rs->freqs[k] < M_PI/2); // otherwise spatialization may phase out..
516   }
517   rs->kcfilt = 12.0 / rate;
518   synth_reset(synth);
519
520   for (c=0; c < 16; c++) {
521     synth_load(&rs->sc[c], rate, &synthesize_sineP, &piano_adsr);
522   }
523   rs->xmas_on = 0;
524   rs->xmas_off = 0;
525 }
526
527 /**
528  * Allocate data-structure, create a handle for all other synth_* functions.
529  *
530  * This data should be freeded with \ref synth_free when the synth is no
531  * longer needed.
532  *
533  * The synth can only be used after calling \rev synth_init as well.
534  *
535  * @return synth-handle
536  */
537 static void * synth_alloc(void) {
538   return calloc(1, sizeof(RSSynthesizer));
539 }
540
541 /**
542  * release synth data structure
543  * @param synth synth-handle
544  */
545 static void synth_free(void *synth) {
546   free(synth);
547 }
548 /* vi:set ts=8 sts=2 sw=2 et: */