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