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