fix merge conflicts with master
[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   ADSRcfg   adsr;
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);
78 } RSSynthChannel;
79
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);
83
84 typedef struct {
85   uint32_t       boffset;
86   float          buf [2][BUFFER_SIZE_SAMPLES];
87   RSSynthChannel sc[16];
88   float          freqs[128];
89   float          kcgain;
90   float          kcfilt;
91   double         rate;
92 } RSSynthesizer;
93
94
95 /* initialize ADSR values
96  *
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]
103  */
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) {
107
108   adsr->vol[0] = avol;
109   adsr->vol[1] = 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;
113
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);
119
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];
123 }
124
125 /* calculate per-sample, per-key envelope */
126 static inline float adsr_env(RSSynthChannel *sc, const uint8_t note) {
127
128   if (sc->adsr_cnt[note] < sc->adsr.off[0]) {
129     // attack
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];
134     } else {
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;
137     }
138   }
139   else if (sc->adsr_cnt[note] < sc->adsr.off[1]) {
140     // decay
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];
145     } else {
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;
148     }
149   }
150   else if (sc->adsr_cnt[note] == sc->adsr.off[1]) {
151     // sustain
152     return sc->adsr.vol[1];
153   }
154   else if (sc->adsr_cnt[note] < sc->adsr.off[2]) {
155     // release
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;
159       return 0;
160     } else {
161       const float d = 0 - sc->adsr_amp[note];
162       return sc->adsr_amp[note] + (p / (float) sc->adsr.tme[2]) * d;
163     }
164   }
165   else {
166     sc->adsr_cnt[note] = 0;
167     return 0;
168   }
169 }
170
171
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) {
177
178   float phase = sc->phase[note];
179
180   for (size_t i=0; i < n_samples; ++i) {
181     float env = adsr_env(sc, note);
182     if (sc->adsr_cnt[note] == 0) break;
183     const float amp = vol * env;
184
185     left[i]  += amp * sinf(2.0 * M_PI * phase);
186     left[i]  += .300 * amp * sinf(2.0 * M_PI * phase * 2.0);
187     left[i]  += .150 * amp * sinf(2.0 * M_PI * phase * 3.0);
188     left[i]  += .080 * amp * sinf(2.0 * M_PI * phase * 4.0);
189   //left[i]  -= .007 * amp * sinf(2.0 * M_PI * phase * 5.0);
190   //left[i]  += .010 * amp * sinf(2.0 * M_PI * phase * 6.0);
191   //left[i]  += .020 * amp * sinf(2.0 * M_PI * phase * 7.0);
192     phase += fq;
193     right[i] += amp * sinf(2.0 * M_PI * phase);
194     right[i] += .300 * amp * sinf(2.0 * M_PI * phase * 2.0);
195     right[i] += .150 * amp * sinf(2.0 * M_PI * phase * 3.0);
196     right[i] -= .080 * amp * sinf(2.0 * M_PI * phase * 4.0);
197   //right[i] += .007 * amp * sinf(2.0 * M_PI * phase * 5.0);
198   //right[i] += .010 * amp * sinf(2.0 * M_PI * phase * 6.0);
199   //right[i] -= .020 * amp * sinf(2.0 * M_PI * phase * 7.0);
200     if (phase > 1.0) phase -= 2.0;
201   }
202   sc->phase[note] = phase;
203 }
204
205 static const ADSRcfg piano_adsr = {{   5, 1300,  100}, { 1.0,  0.0}, {0,0,0}};
206
207 /*****************************************************************************/
208
209
210 /* process note - move through ADSR states, count active keys,.. */
211 static void process_key (void *synth,
212     const uint8_t chn, const uint8_t note,
213     const size_t n_samples, float *left, float *right)
214 {
215   RSSynthesizer*  rs = (RSSynthesizer*)synth;
216   RSSynthChannel* sc = &rs->sc[chn];
217   const int8_t vel = sc->miditable[note];
218   const float vol = /* master_volume */ 0.25 * fabsf(vel) / 127.0;
219   const float phase = sc->phase[note];
220
221   if (phase == -10 && vel > 0) {
222     // new note on
223     assert(sc->adsr_cnt[note] == 0);
224     sc->adsr_amp[note] = 0;
225     sc->adsr_cnt[note] = 0;
226     sc->phase[note] = 0;
227     sc->keycomp++;
228     //printf("[On] Now %d keys active on chn %d\n", sc->keycomp, chn);
229   }
230   else if (phase >= -1.0 && phase <= 1.0 && vel > 0) {
231     // sustain note or re-start note while adsr in progress:
232     if (sc->adsr_cnt[note] > sc->adsr.off[1]) {
233       // x-fade to attack
234       sc->adsr_amp[note] = adsr_env(sc, note);
235       sc->adsr_cnt[note] = 0;
236     }
237   }
238   else if (phase >= -1.0 && phase <= 1.0 && vel < 0) {
239     // note off
240     if (sc->adsr_cnt[note] <= sc->adsr.off[1]) {
241       if (sc->adsr_cnt[note] != sc->adsr.off[1]) {
242         // x-fade to release
243         sc->adsr_amp[note] = adsr_env(sc, note);
244       }
245       sc->adsr_cnt[note] = sc->adsr.off[1] + 1;
246     }
247   }
248   else {
249     /* note-on + off in same cycle */
250     sc->miditable[note] = 0;
251     sc->adsr_cnt[note] = 0;
252     sc->phase[note] = -10;
253     return;
254   }
255
256   // synthesize actual sound
257   sc->synthesize(sc, note, vol, rs->freqs[note], n_samples, left, right);
258
259   if (sc->adsr_cnt[note] == 0) {
260     //printf("Note %d,%d released\n", chn, note);
261     sc->miditable[note] = 0;
262     sc->adsr_amp[note] = 0;
263     sc->phase[note] = -10;
264     sc->keycomp--;
265     //printf("[off] Now %d keys active on chn %d\n", sc->keycomp, chn);
266   }
267 }
268
269 /* synthesize a BUFFER_SIZE_SAMPLES's of audio-data */
270 static void synth_fragment (void *synth, const size_t n_samples, float *left, float *right) {
271   RSSynthesizer* rs = (RSSynthesizer*)synth;
272   memset (left, 0, n_samples * sizeof(float));
273   memset (right, 0, n_samples * sizeof(float));
274   uint8_t keycomp = 0;
275
276   for (int c=0; c < 16; ++c) {
277     for (int k=0; k < 128; ++k) {
278       if (rs->sc[c].miditable[k] == 0) continue;
279       process_key(synth, c, k, n_samples, left, right);
280     }
281     keycomp += rs->sc[c].keycomp;
282   }
283
284 #if 1 // key-compression
285   float kctgt = 8.0 / (float)(keycomp + 7.0);
286   if (kctgt < .5) kctgt = .5;
287   if (kctgt > 1.0) kctgt = 1.0;
288   const float _w = rs->kcfilt;
289   for (unsigned int i=0; i < n_samples; ++i) {
290     rs->kcgain += _w * (kctgt - rs->kcgain);
291     left[i]  *= rs->kcgain;
292     right[i] *= rs->kcgain;
293   }
294   rs->kcgain += 1e-12;
295 #endif
296 }
297
298 static void synth_reset_channel(RSSynthChannel* sc) {
299   for (int k=0; k < 128; ++k) {
300     sc->adsr_cnt[k]  = 0;
301     sc->adsr_amp[k]  = 0;
302     sc->phase[k]     = -10;
303     sc->miditable[k] = 0;
304   }
305   sc->keycomp = 0;
306 }
307
308 static void synth_reset(void *synth) {
309   RSSynthesizer* rs = (RSSynthesizer*)synth;
310   for (int c=0; c < 16; ++c) {
311     synth_reset_channel(&(rs->sc[c]));
312   }
313   rs->kcgain = 0;
314 }
315
316 static void synth_load(RSSynthChannel *sc, const double rate,
317     SynthFunction synthesize,
318     ADSRcfg const * const adsr) {
319   synth_reset_channel(sc);
320   init_adsr(&sc->adsr, rate,
321       adsr->tme[0], adsr->tme[1], adsr->tme[2],
322       adsr->vol[0], adsr->vol[1]);
323   sc->synthesize = synthesize;
324 }
325
326
327 /**
328  * internal abstraction of MIDI data handling
329  */
330 static void synth_process_midi_event(void *synth, struct rmidi_event_t *ev) {
331   RSSynthesizer* rs = (RSSynthesizer*)synth;
332   switch(ev->type) {
333     case NOTE_ON:
334       if (rs->sc[ev->channel].miditable[ev->d.tone.note] <= 0)
335         rs->sc[ev->channel].miditable[ev->d.tone.note] = ev->d.tone.velocity;
336       break;
337     case NOTE_OFF:
338       if (rs->sc[ev->channel].miditable[ev->d.tone.note] > 0)
339         rs->sc[ev->channel].miditable[ev->d.tone.note] *= -1.0;
340       break;
341     case PROGRAM_CHANGE:
342       break;
343     case CONTROL_CHANGE:
344       if (ev->d.control.param == 0x00 || ev->d.control.param == 0x20) {
345         /*  0x00 and 0x20 are used for BANK select */
346         break;
347       } else
348       if (ev->d.control.param == 121) {
349         /* reset all controllers */
350         break;
351       } else
352       if (ev->d.control.param == 120 || ev->d.control.param == 123) {
353         /* Midi panic: 120: all sound off, 123: all notes off*/
354         synth_reset_channel(&(rs->sc[ev->channel]));
355         break;
356       } else
357       if (ev->d.control.param >= 120) {
358         /* params 122-127 are reserved - skip them. */
359         break;
360       }
361       break;
362     default:
363       break;
364   }
365 }
366
367 /******************************************************************************
368  * PUBLIC API (used by lv2.c)
369  */
370
371 /**
372  * align LV2 and internal synth buffers
373  * call synth_fragment as often as needed for the given LV2 buffer size
374  *
375  * @param synth synth-handle
376  * @param written samples written so far (offset in \ref out)
377  * @param nframes total samples to synthesize and write to the \out buffer
378  * @param out pointer to stereo output buffers
379  * @return end of buffer (written + nframes)
380  */
381 static uint32_t synth_sound (void *synth, uint32_t written, const uint32_t nframes, float **out) {
382   RSSynthesizer* rs = (RSSynthesizer*)synth;
383
384   while (written < nframes) {
385     uint32_t nremain = nframes - written;
386
387     if (rs->boffset >= BUFFER_SIZE_SAMPLES)  {
388       rs->boffset = 0;
389       synth_fragment(rs, BUFFER_SIZE_SAMPLES, rs->buf[0], rs->buf[1]);
390     }
391
392     uint32_t nread = MIN(nremain, (BUFFER_SIZE_SAMPLES - rs->boffset));
393
394     memcpy(&out[0][written], &rs->buf[0][rs->boffset], nread*sizeof(float));
395     memcpy(&out[1][written], &rs->buf[1][rs->boffset], nread*sizeof(float));
396
397     written += nread;
398     rs->boffset += nread;
399   }
400   return written;
401 }
402
403 /**
404  * parse raw midi-data.
405  *
406  * @param synth synth-handle
407  * @param data 8bit midi message
408  * @param size number of bytes in the midi-message
409  */
410 static void synth_parse_midi(void *synth, uint8_t *data, size_t size) {
411   if (size < 2 || size > 3) return;
412   // All messages need to be 3 bytes; except program-changes: 2bytes.
413   if (size == 2 && (data[0] & 0xf0)  != 0xC0) return;
414
415   struct rmidi_event_t ev;
416
417   ev.channel = data[0]&0x0f;
418   switch (data[0] & 0xf0) {
419     case 0x80:
420       ev.type=NOTE_OFF;
421       ev.d.tone.note=data[1]&0x7f;
422       ev.d.tone.velocity=data[2]&0x7f;
423       break;
424     case 0x90:
425       ev.type=NOTE_ON;
426       ev.d.tone.note=data[1]&0x7f;
427       ev.d.tone.velocity=data[2]&0x7f;
428       break;
429     case 0xB0:
430       ev.type=CONTROL_CHANGE;
431       ev.d.control.param=data[1]&0x7f;
432       ev.d.control.value=data[2]&0x7f;
433       break;
434     case 0xC0:
435       ev.type=PROGRAM_CHANGE;
436       ev.d.control.value=data[1]&0x7f;
437       break;
438     default:
439       return;
440   }
441   synth_process_midi_event(synth, &ev);
442 }
443
444 /**
445  * initialize the synth
446  * This should be called after synth_alloc()
447  * as soon as the sample-rate is known
448  *
449  * @param synth synth-handle
450  * @param rate sample-rate
451  */
452 static void synth_init(void *synth, double rate) {
453   RSSynthesizer* rs = (RSSynthesizer*)synth;
454   rs->rate = rate;
455   rs->boffset = BUFFER_SIZE_SAMPLES;
456   const float tuning = 440;
457   for (int k=0; k < 128; k++) {
458     rs->freqs[k] = (2.0 * tuning / 32.0f) * powf(2, (k - 9.0) / 12.0) / rate;
459     assert(rs->freqs[k] < M_PI/2); // otherwise spatialization may phase out..
460   }
461   rs->kcfilt = 12.0 / rate;
462   synth_reset(synth);
463
464   for (int c=0; c < 16; c++) {
465     synth_load(&rs->sc[c], rate, &synthesize_sineP, &piano_adsr);
466   }
467 }
468
469 /**
470  * Allocate data-structure, create a handle for all other synth_* functions.
471  *
472  * This data should be freeded with \ref synth_free when the synth is no
473  * longer needed.
474  *
475  * The synth can only be used after calling \rev synth_init as well.
476  *
477  * @return synth-handle
478  */
479 static void * synth_alloc(void) {
480   return calloc(1, sizeof(RSSynthesizer));
481 }
482
483 /**
484  * release synth data structure
485  * @param synth synth-handle
486  */
487 static void synth_free(void *synth) {
488   free(synth);
489 }
490 /* vi:set ts=8 sts=2 sw=2: */