protect a-delay again Inf, NaN, HUGE and stuff.
[ardour.git] / libs / plugins / a-delay.lv2 / a-delay.c
1 /* a-delay
2  * Copyright (C) 2016 Damien Zammit <damien@zamaudio.com>
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  */
14
15 #include <math.h>
16 #include <stdlib.h>
17 #include <stdio.h>
18
19 #include "lv2/lv2plug.in/ns/lv2core/lv2.h"
20 #include "lv2/lv2plug.in/ns/ext/atom/atom.h"
21 #include "lv2/lv2plug.in/ns/ext/time/time.h"
22 #include "lv2/lv2plug.in/ns/ext/atom/forge.h"
23 #include "lv2/lv2plug.in/ns/ext/urid/urid.h"
24
25 #define ADELAY_URI "urn:ardour:a-delay"
26
27 // 8 seconds of delay at 96kHz
28 #define MAX_DELAY 768000
29
30 #ifndef M_PI
31 # define M_PI 3.1415926
32 #endif
33
34 #ifdef COMPILER_MSVC
35 #include <float.h>
36 #define isfinite_local(val) (bool)_finite((double)val)
37 #else
38 #define isfinite_local isfinite
39 #endif
40
41 typedef enum {
42         ADELAY_INPUT = 0,
43         ADELAY_OUTPUT,
44
45         ADELAY_BPM,
46
47         ADELAY_INV,
48         ADELAY_SYNC,
49         ADELAY_TIME,
50         ADELAY_DIVISOR,
51         ADELAY_WETDRY,
52         ADELAY_FEEDBACK,
53         ADELAY_LPF,
54         ADELAY_GAIN,
55         ADELAY_DELAYTIME,
56         ADELAY_ENABLE,
57 } PortIndex;
58
59
60 typedef struct {
61         LV2_URID atom_Blank;
62         LV2_URID atom_Object;
63         LV2_URID atom_Sequence;
64         LV2_URID atom_Long;
65         LV2_URID atom_Int;
66         LV2_URID atom_Float;
67         LV2_URID atom_Double;
68         LV2_URID time_beatUnit;
69         LV2_URID time_beatsPerMinute;
70         LV2_URID time_Position;
71 } DelayURIs;
72
73 typedef struct {
74         float* input;
75         float* output;
76
77         const LV2_Atom_Sequence* atombpm;
78
79         float* inv;
80         float* sync;
81         float* time;
82         float* divisor;
83         float* wetdry;
84         float* feedback;
85         float* lpf;
86         float* gain;
87         
88         float* delaytime;
89         float* enable;
90
91         float srate;
92         float bpm;
93         float beatunit;
94         int bpmvalid;
95
96         uint32_t posz;
97         float tap[2];
98         float z[MAX_DELAY];
99         int active;
100         int next;
101         float fbstate;
102         float lpfold;
103         float feedbackold;
104         float divisorold;
105         float gainold;
106         float invertold;
107         float timeold;
108         float delaytimeold;
109         float syncold;
110         float wetdryold;
111         float delaysamplesold;
112         float tau;
113
114         float A0, A1, A2, A3, A4, A5;
115         float B0, B1, B2, B3, B4, B5;
116         float state[4];
117
118         DelayURIs uris;
119         LV2_Atom_Forge forge;
120         LV2_URID_Map* map;
121 } ADelay;
122
123 static inline void
124 map_uris(LV2_URID_Map* map, DelayURIs* uris)
125 {
126         uris->atom_Blank          = map->map(map->handle, LV2_ATOM__Blank);
127         uris->atom_Object         = map->map(map->handle, LV2_ATOM__Object);
128         uris->atom_Sequence       = map->map(map->handle, LV2_ATOM__Sequence);
129         uris->atom_Long           = map->map(map->handle, LV2_ATOM__Long);
130         uris->atom_Int            = map->map(map->handle, LV2_ATOM__Int);
131         uris->atom_Float          = map->map(map->handle, LV2_ATOM__Float);
132         uris->atom_Double         = map->map(map->handle, LV2_ATOM__Double);
133         uris->time_beatUnit       = map->map(map->handle, LV2_TIME__beatUnit);
134         uris->time_beatsPerMinute = map->map(map->handle, LV2_TIME__beatsPerMinute);
135         uris->time_Position       = map->map(map->handle, LV2_TIME__Position);
136 }
137
138 static LV2_Handle
139 instantiate(const LV2_Descriptor* descriptor,
140             double rate,
141             const char* bundle_path,
142             const LV2_Feature* const* features)
143 {
144         int i;
145         ADelay* adelay = (ADelay*)calloc(1, sizeof(ADelay));
146         if (!adelay) return NULL;
147
148         for (i = 0; features[i]; ++i) {
149                 if (!strcmp(features[i]->URI, LV2_URID__map)) {
150                         adelay->map = (LV2_URID_Map*)features[i]->data;
151                 }
152         }
153
154         if (!adelay->map) {
155                 fprintf(stderr, "a-delay.lv2 error: Host does not support urid:map\n");
156                 free(adelay);
157                 return NULL;
158         }
159
160         map_uris(adelay->map, &adelay->uris);
161         lv2_atom_forge_init(&adelay->forge, adelay->map);
162
163         adelay->srate = rate;
164         adelay->bpmvalid = 0;
165         adelay->tau = (1.0 - exp (-2.f * M_PI * 25.f / adelay->srate));
166
167         return (LV2_Handle)adelay;
168 }
169
170 static void
171 connect_port(LV2_Handle instance,
172              uint32_t port,
173              void* data)
174 {
175         ADelay* adelay = (ADelay*)instance;
176
177         switch ((PortIndex)port) {
178         case ADELAY_INPUT:
179                 adelay->input = (float*)data;
180                 break;
181         case ADELAY_OUTPUT:
182                 adelay->output = (float*)data;
183                 break;
184         case ADELAY_BPM:
185                 adelay->atombpm = (const LV2_Atom_Sequence*)data;
186                 break;
187         case ADELAY_INV:
188                 adelay->inv = (float*)data;
189                 break;
190         case ADELAY_SYNC:
191                 adelay->sync = (float*)data;
192                 break;
193         case ADELAY_TIME:
194                 adelay->time = (float*)data;
195                 break;
196         case ADELAY_DIVISOR:
197                 adelay->divisor = (float*)data;
198                 break;
199         case ADELAY_WETDRY:
200                 adelay->wetdry = (float*)data;
201                 break;
202         case ADELAY_FEEDBACK:
203                 adelay->feedback = (float*)data;
204                 break;
205         case ADELAY_LPF:
206                 adelay->lpf = (float*)data;
207                 break;
208         case ADELAY_GAIN:
209                 adelay->gain = (float*)data;
210                 break;
211         case ADELAY_DELAYTIME:
212                 adelay->delaytime = (float*)data;
213                 break;
214         case ADELAY_ENABLE:
215                 adelay->enable = (float*)data;
216                 break;
217         }
218 }
219
220 static inline float
221 sanitize_denormal(const float value) {
222         if (!isnormal(value)) {
223                 return 0.f;
224         }
225         return value;
226 }
227
228 static inline float
229 sanitize_input(const float value) {
230         if (!isfinite_local (value)) {
231                 return 0.f;
232         }
233         return value;
234 }
235
236 static inline float
237 from_dB(float gdb) {
238         return (exp(gdb/20.f*log(10.f)));
239 }
240
241 static inline float
242 to_dB(float g) {
243         return (20.f*log10(g));
244 }
245
246 static inline bool
247 is_eq(float a, float b, float small) {
248         return (fabsf(a - b) < small);
249 }
250
251 static void clearfilter(LV2_Handle instance)
252 {
253         ADelay* adelay = (ADelay*)instance;
254
255         adelay->state[0] = adelay->state[1] =
256                 adelay->state[2] = adelay->state[3] = 0.f;
257 }
258
259 static void
260 activate(LV2_Handle instance)
261 {
262         ADelay* adelay = (ADelay*)instance;
263
264         int i;
265         for (i = 0; i < MAX_DELAY; i++) {
266                 adelay->z[i] = 0.f;
267         }
268         adelay->posz = 0;
269         adelay->tap[0] = 0;
270         adelay->tap[1] = 0;
271         adelay->active = 0;
272         adelay->next = 1;
273         adelay->fbstate = 0.f;
274
275         clearfilter(adelay);
276
277         adelay->lpfold = 0.f;
278         adelay->divisorold = 0.f;
279         adelay->gainold = 0.f;
280         adelay->invertold = 0.f;
281         adelay->timeold = 0.f;
282         adelay->delaytimeold = 0.f;
283         adelay->syncold = 0.f;
284         adelay->wetdryold = 0.f;
285         adelay->delaysamplesold = 1.f;
286 }
287
288 static void lpfRbj(LV2_Handle instance, float fc, float srate)
289 {
290         ADelay* adelay = (ADelay*)instance;
291
292         float w0, alpha, cw, sw, q;
293         q = 0.707;
294         w0 = (2. * M_PI * fc / srate);
295         sw = sin(w0);
296         cw = cos(w0);
297         alpha = sw / (2. * q);
298
299         adelay->A0 = 1. + alpha;
300         adelay->A1 = -2. * cw;
301         adelay->A2 = 1. - alpha;
302         adelay->B0 = (1. - cw) / 2.;
303         adelay->B1 = (1. - cw);
304         adelay->B2 = adelay->B0;
305
306         adelay->A3 = 1. + alpha;
307         adelay->A4 = -2. * cw;
308         adelay->A5 = 1. - alpha;
309         adelay->B3 = (1. - cw) / 2.;
310         adelay->B4 = (1. - cw);
311         adelay->B5 = adelay->B3;
312 }
313
314 static float runfilter(LV2_Handle instance, const float in)
315 {
316         ADelay* a = (ADelay*)instance;
317
318         float out;
319
320         out = a->B0/a->A0*in + a->B1/a->A0*a->state[0] + a->B2/a->A0*a->state[1]
321                         -a->A1/a->A0*a->state[2] - a->A2/a->A0*a->state[3] + 1e-20;
322
323         a->state[1] = a->state[0];
324         a->state[0] = in;
325         a->state[3] = a->state[2];
326         a->state[2] = sanitize_input (out);
327         return out;
328 }
329
330 static void
331 update_bpm(ADelay* self, const LV2_Atom_Object* obj)
332 {
333         const DelayURIs* uris = &self->uris;
334
335         // Received new transport bpm/beatunit
336         LV2_Atom *beatunit = NULL, *bpm = NULL;
337         lv2_atom_object_get(obj,
338                             uris->time_beatUnit, &beatunit,
339                             uris->time_beatsPerMinute, &bpm,
340                             NULL);
341         // Tempo changed, update BPM
342         if (bpm && bpm->type == uris->atom_Float) {
343                 self->bpm = ((LV2_Atom_Float*)bpm)->body;
344         }
345         // Time signature changed, update beatunit
346         if (beatunit && beatunit->type == uris->atom_Int) {
347                 int b = ((LV2_Atom_Int*)beatunit)->body;
348                 self->beatunit = (float)b;
349         }
350         if (beatunit && beatunit->type == uris->atom_Double) {
351                 double b = ((LV2_Atom_Double*)beatunit)->body;
352                 self->beatunit = (float)b;
353         }
354         if (beatunit && beatunit->type == uris->atom_Float) {
355                 self->beatunit = ((LV2_Atom_Float*)beatunit)->body;
356         }
357         if (beatunit && beatunit->type == uris->atom_Long) {
358                 long int b = ((LV2_Atom_Long*)beatunit)->body;
359                 self->beatunit = (float)b;
360         }
361         self->bpmvalid = 1;
362 }
363
364 static void
365 run(LV2_Handle instance, uint32_t n_samples)
366 {
367         ADelay* adelay = (ADelay*)instance;
368
369         const float* const input = adelay->input;
370         float* const output = adelay->output;
371
372         const float srate = adelay->srate;
373         const float tau = adelay->tau;
374
375         float wetdry_target = *adelay->wetdry / 100.f;
376         float gain_target = from_dB(*adelay->gain);
377         float wetdry = adelay->wetdryold;
378         float gain = adelay->gainold;
379
380         if (*adelay->enable <= 0) {
381                 wetdry_target = 0.f;
382                 gain_target = 1.0;
383         }
384
385         uint32_t i;
386         float in;
387         int delaysamples = 0;
388         unsigned int tmp;
389         float inv;
390         float xfade;
391         int recalc;
392
393         // TODO LPF
394         if (*(adelay->inv) < 0.5) {
395                 inv = -1.f;
396         } else {
397                 inv = 1.f;
398         }
399         
400         recalc = 0;
401         if (*(adelay->inv) != adelay->invertold) {
402                 recalc = 1;
403         }
404         if (*(adelay->sync) != adelay->syncold) {
405                 recalc = 1;
406         }
407         if (*(adelay->time) != adelay->timeold) {
408                 recalc = 1;
409         }
410         if (*(adelay->feedback) != adelay->feedbackold) {
411                 recalc = 1;
412         }
413         if (*(adelay->divisor) != adelay->divisorold) {
414                 recalc = 1;
415         }
416         if (!is_eq(adelay->lpfold, *adelay->lpf, 0.1)) {
417                 float  tc = (1.0 - exp (-2.f * M_PI * n_samples * 25.f / adelay->srate));
418                 adelay->lpfold += tc * (*adelay->lpf - adelay->lpfold);
419                 recalc = 1;
420         }
421         
422         if (recalc) {
423                 lpfRbj(adelay, adelay->lpfold, srate);
424                 if (*(adelay->sync) > 0.5f && adelay->bpmvalid) {
425                         *(adelay->delaytime) = adelay->beatunit * 1000.f * 60.f / (adelay->bpm * *(adelay->divisor));
426                 } else {
427                         *(adelay->delaytime) = *(adelay->time);
428                 }
429                 delaysamples = (int)(*(adelay->delaytime) * srate) / 1000;
430                 adelay->tap[adelay->next] = delaysamples;
431         }
432
433         xfade = 0.f;
434
435         float fbstate = adelay->fbstate;
436         const float feedback = *adelay->feedback;
437
438         for (i = 0; i < n_samples; i++) {
439                 in = sanitize_input (input[i]);
440                 adelay->z[adelay->posz] = sanitize_denormal (in + feedback / 100.f * fbstate);
441                 int p = adelay->posz - adelay->tap[adelay->active]; // active line
442                 if (p<0) p += MAX_DELAY;
443                 fbstate = adelay->z[p];
444                 
445                 if (recalc) {
446                         xfade += 1.0f / (float)n_samples;
447                         fbstate *= (1.-xfade);
448                         p = adelay->posz - adelay->tap[adelay->next]; // next line
449                         if (p<0) p += MAX_DELAY;
450                         fbstate += adelay->z[p] * xfade;
451                 }
452
453                 wetdry += tau * (wetdry_target - wetdry) + 1e-12;
454                 gain += tau * (gain_target - gain) + 1e-12;
455
456                 output[i] = (1.f - wetdry) * in;
457                 output[i] += wetdry * -inv * runfilter(adelay, fbstate);
458                 output[i] *= gain;
459
460                 if (++(adelay->posz) >= MAX_DELAY) {
461                         adelay->posz = 0;
462                 }
463         }
464
465         adelay->fbstate = fbstate;
466         adelay->feedbackold = *(adelay->feedback);
467         adelay->divisorold = *(adelay->divisor);
468         adelay->invertold = *(adelay->inv);
469         adelay->timeold = *(adelay->time);
470         adelay->syncold = *(adelay->sync);
471         adelay->wetdryold = wetdry;
472         adelay->gainold = gain;
473         adelay->delaytimeold = *(adelay->delaytime);
474         adelay->delaysamplesold = delaysamples;
475
476         if (recalc) {
477                 tmp = adelay->active;
478                 adelay->active = adelay->next;
479                 adelay->next = tmp;
480         }
481         
482         if (adelay->atombpm) {
483                 LV2_Atom_Event* ev = lv2_atom_sequence_begin(&(adelay->atombpm)->body);
484                 while(!lv2_atom_sequence_is_end(&(adelay->atombpm)->body, (adelay->atombpm)->atom.size, ev)) {
485                         if (ev->body.type == adelay->uris.atom_Blank || ev->body.type == adelay->uris.atom_Object) {
486                                 const LV2_Atom_Object* obj = (LV2_Atom_Object*)&ev->body;
487                                 if (obj->body.otype == adelay->uris.time_Position) {
488                                         update_bpm(adelay, obj);
489                                 }
490                         }
491                         ev = lv2_atom_sequence_next(ev);
492                 }
493         }
494 }
495
496 static void
497 cleanup(LV2_Handle instance)
498 {
499         free(instance);
500 }
501
502 static const void*
503 extension_data(const char* uri)
504 {
505         return NULL;
506 }
507
508 static const LV2_Descriptor descriptor = {
509         ADELAY_URI,
510         instantiate,
511         connect_port,
512         activate,
513         run,
514         NULL,
515         cleanup,
516         extension_data
517 };
518
519 LV2_SYMBOL_EXPORT
520 const LV2_Descriptor*
521 lv2_descriptor(uint32_t index)
522 {
523         switch (index) {
524         case 0:
525                 return &descriptor;
526         default:
527                 return NULL;
528         }
529 }