Cleanup
[calf.git] / src / audio_fx.cpp
bloba8f50f4d1710066f9615304371e5976644339088
1 /* Calf DSP Library
2 * Reusable audio effect classes - implementation.
4 * Copyright (C) 2001-2010 Krzysztof Foltman, Markus Schmidt, Thor Harald Johansen and others
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General
17 * Public License along with this program; if not, write to the
18 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 * Boston, MA 02110-1301 USA
22 #include <calf/audio_fx.h>
23 #include <calf/giface.h>
24 #include <limits.h>
25 #include <stdlib.h>
26 #include <time.h>
27 #include <math.h>
29 using namespace calf_plugins;
30 using namespace dsp;
32 simple_phaser::simple_phaser(int _max_stages, float *x1vals, float *y1vals)
34 max_stages = _max_stages;
35 x1 = x1vals;
36 y1 = y1vals;
38 set_base_frq(1000);
39 set_mod_depth(1000);
40 set_fb(0);
41 state = 0;
42 cnt = 0;
43 stages = 0;
44 set_stages(_max_stages);
47 void simple_phaser::set_stages(int _stages)
49 if (_stages > stages)
51 assert(_stages <= max_stages);
52 if (_stages > max_stages)
53 _stages = max_stages;
54 for (int i = stages; i < _stages; i++)
56 x1[i] = x1[stages-1];
57 y1[i] = y1[stages-1];
60 stages = _stages;
63 void simple_phaser::reset()
65 cnt = 0;
66 state = 0;
67 phase.set(0);
68 for (int i = 0; i < max_stages; i++)
69 x1[i] = y1[i] = 0;
70 control_step();
73 void simple_phaser::control_step()
75 cnt = 0;
76 int v = phase.get() + 0x40000000;
77 int sign = v >> 31;
78 v ^= sign;
79 // triangle wave, range from 0 to INT_MAX
80 double vf = (double)((v >> 16) * (1.0 / 16384.0) - 1);
82 float freq = base_frq * pow(2.0, vf * mod_depth / 1200.0);
83 freq = dsp::clip<float>(freq, 10.0, 0.49 * sample_rate);
84 stage1.set_ap_w(freq * (M_PI / 2.0) * odsr);
85 phase += dphase * 32;
86 for (int i = 0; i < stages; i++)
88 dsp::sanitize(x1[i]);
89 dsp::sanitize(y1[i]);
91 dsp::sanitize(state);
94 void simple_phaser::process(float *buf_out, float *buf_in, int nsamples)
96 for (int i=0; i<nsamples; i++) {
97 cnt++;
98 if (cnt == 32)
99 control_step();
100 float in = *buf_in++;
101 float fd = in + state * fb;
102 for (int j = 0; j < stages; j++)
103 fd = stage1.process_ap(fd, x1[j], y1[j]);
104 state = fd;
106 float sdry = in * gs_dry.get();
107 float swet = fd * gs_wet.get();
108 *buf_out++ = sdry + swet;
112 float simple_phaser::freq_gain(float freq, float sr) const
114 typedef std::complex<double> cfloat;
115 freq *= 2.0 * M_PI / sr;
116 cfloat z = 1.0 / exp(cfloat(0.0, freq)); // z^-1
118 cfloat p = cfloat(1.0);
119 cfloat stg = stage1.h_z(z);
121 for (int i = 0; i < stages; i++)
122 p = p * stg;
124 p = p / (cfloat(1.0) - cfloat(fb) * p);
125 return std::abs(cfloat(gs_dry.get_last()) + cfloat(gs_wet.get_last()) * p);
128 ///////////////////////////////////////////////////////////////////////////////////
130 void biquad_filter_module::calculate_filter(float freq, float q, int mode, float gain)
132 if (mode <= mode_36db_lp) {
133 order = mode + 1;
134 left[0].set_lp_rbj(freq, pow(q, 1.0 / order), srate, gain);
135 } else if ( mode_12db_hp <= mode && mode <= mode_36db_hp ) {
136 order = mode - mode_12db_hp + 1;
137 left[0].set_hp_rbj(freq, pow(q, 1.0 / order), srate, gain);
138 } else if ( mode_6db_bp <= mode && mode <= mode_18db_bp ) {
139 order = mode - mode_6db_bp + 1;
140 left[0].set_bp_rbj(freq, pow(q, 1.0 / order), srate, gain);
141 } else { // mode_6db_br <= mode <= mode_18db_br
142 order = mode - mode_6db_br + 1;
143 left[0].set_br_rbj(freq, order * 0.1 * q, srate, gain);
146 right[0].copy_coeffs(left[0]);
147 for (int i = 1; i < order; i++) {
148 left[i].copy_coeffs(left[0]);
149 right[i].copy_coeffs(left[0]);
153 void biquad_filter_module::filter_activate()
155 for (int i=0; i < order; i++) {
156 left[i].reset();
157 right[i].reset();
161 void biquad_filter_module::sanitize()
163 for (int i=0; i < order; i++) {
164 left[i].sanitize();
165 right[i].sanitize();
169 int biquad_filter_module::process_channel(uint16_t channel_no, const float *in, float *out, uint32_t numsamples, int inmask) {
170 dsp::biquad_d1 *filter;
171 switch (channel_no) {
172 case 0:
173 filter = left;
174 break;
176 case 1:
177 filter = right;
178 break;
180 default:
181 assert(false);
182 return 0;
185 if (inmask) {
186 switch(order) {
187 case 1:
188 for (uint32_t i = 0; i < numsamples; i++)
189 out[i] = filter[0].process(in[i]);
190 break;
191 case 2:
192 for (uint32_t i = 0; i < numsamples; i++)
193 out[i] = filter[1].process(filter[0].process(in[i]));
194 break;
195 case 3:
196 for (uint32_t i = 0; i < numsamples; i++)
197 out[i] = filter[2].process(filter[1].process(filter[0].process(in[i])));
198 break;
200 } else {
201 if (filter[order - 1].empty())
202 return 0;
203 switch(order) {
204 case 1:
205 for (uint32_t i = 0; i < numsamples; i++)
206 out[i] = filter[0].process_zeroin();
207 break;
208 case 2:
209 if (filter[0].empty())
210 for (uint32_t i = 0; i < numsamples; i++)
211 out[i] = filter[1].process_zeroin();
212 else
213 for (uint32_t i = 0; i < numsamples; i++)
214 out[i] = filter[1].process(filter[0].process_zeroin());
215 break;
216 case 3:
217 if (filter[1].empty())
218 for (uint32_t i = 0; i < numsamples; i++)
219 out[i] = filter[2].process_zeroin();
220 else
221 for (uint32_t i = 0; i < numsamples; i++)
222 out[i] = filter[2].process(filter[1].process(filter[0].process_zeroin()));
223 break;
226 for (int i = 0; i < order; i++)
227 filter[i].sanitize();
228 return filter[order - 1].empty() ? 0 : inmask;
231 float biquad_filter_module::freq_gain(int subindex, float freq, float srate) const
233 float level = 1.0;
234 for (int j = 0; j < order; j++)
235 level *= left[j].freq_gain(freq, srate);
236 return level;
239 /////////////////////////////////////////////////////////////////////////////////////////////////////////
241 void reverb::update_times()
243 switch(type)
245 case 0:
246 tl[0] = 397 << 16, tr[0] = 383 << 16;
247 tl[1] = 457 << 16, tr[1] = 429 << 16;
248 tl[2] = 549 << 16, tr[2] = 631 << 16;
249 tl[3] = 649 << 16, tr[3] = 756 << 16;
250 tl[4] = 773 << 16, tr[4] = 803 << 16;
251 tl[5] = 877 << 16, tr[5] = 901 << 16;
252 break;
253 case 1:
254 tl[0] = 697 << 16, tr[0] = 783 << 16;
255 tl[1] = 957 << 16, tr[1] = 929 << 16;
256 tl[2] = 649 << 16, tr[2] = 531 << 16;
257 tl[3] = 1049 << 16, tr[3] = 1177 << 16;
258 tl[4] = 473 << 16, tr[4] = 501 << 16;
259 tl[5] = 587 << 16, tr[5] = 681 << 16;
260 break;
261 case 2:
262 default:
263 tl[0] = 697 << 16, tr[0] = 783 << 16;
264 tl[1] = 957 << 16, tr[1] = 929 << 16;
265 tl[2] = 649 << 16, tr[2] = 531 << 16;
266 tl[3] = 1249 << 16, tr[3] = 1377 << 16;
267 tl[4] = 1573 << 16, tr[4] = 1671 << 16;
268 tl[5] = 1877 << 16, tr[5] = 1781 << 16;
269 break;
270 case 3:
271 tl[0] = 1097 << 16, tr[0] = 1087 << 16;
272 tl[1] = 1057 << 16, tr[1] = 1031 << 16;
273 tl[2] = 1049 << 16, tr[2] = 1039 << 16;
274 tl[3] = 1083 << 16, tr[3] = 1055 << 16;
275 tl[4] = 1075 << 16, tr[4] = 1099 << 16;
276 tl[5] = 1003 << 16, tr[5] = 1073 << 16;
277 break;
278 case 4:
279 tl[0] = 197 << 16, tr[0] = 133 << 16;
280 tl[1] = 357 << 16, tr[1] = 229 << 16;
281 tl[2] = 549 << 16, tr[2] = 431 << 16;
282 tl[3] = 949 << 16, tr[3] = 1277 << 16;
283 tl[4] = 1173 << 16, tr[4] = 1671 << 16;
284 tl[5] = 1477 << 16, tr[5] = 1881 << 16;
285 break;
286 case 5:
287 tl[0] = 197 << 16, tr[0] = 133 << 16;
288 tl[1] = 257 << 16, tr[1] = 179 << 16;
289 tl[2] = 549 << 16, tr[2] = 431 << 16;
290 tl[3] = 619 << 16, tr[3] = 497 << 16;
291 tl[4] = 1173 << 16, tr[4] = 1371 << 16;
292 tl[5] = 1577 << 16, tr[5] = 1881 << 16;
293 break;
296 float fDec=1000 + 2400.f * diffusion;
297 for (int i = 0 ; i < 6; i++) {
298 ldec[i]=exp(-float(tl[i] >> 16) / fDec),
299 rdec[i]=exp(-float(tr[i] >> 16) / fDec);
303 void reverb::reset()
305 apL1.reset();apR1.reset();
306 apL2.reset();apR2.reset();
307 apL3.reset();apR3.reset();
308 apL4.reset();apR4.reset();
309 apL5.reset();apR5.reset();
310 apL6.reset();apR6.reset();
311 lp_left.reset();lp_right.reset();
312 old_left = 0; old_right = 0;
315 void reverb::process(float &left, float &right)
317 unsigned int ipart = phase.ipart();
319 // the interpolated LFO might be an overkill here
320 int lfo = phase.lerp_by_fract_int<int, 14, int>(sine.data[ipart], sine.data[ipart+1]) >> 2;
321 phase += dphase;
323 left += old_right;
324 left = apL1.process_allpass_comb_lerp16(left, tl[0] - 45*lfo, ldec[0]);
325 left = apL2.process_allpass_comb_lerp16(left, tl[1] + 47*lfo, ldec[1]);
326 float out_left = left;
327 left = apL3.process_allpass_comb_lerp16(left, tl[2] + 54*lfo, ldec[2]);
328 left = apL4.process_allpass_comb_lerp16(left, tl[3] - 69*lfo, ldec[3]);
329 left = apL5.process_allpass_comb_lerp16(left, tl[4] + 69*lfo, ldec[4]);
330 left = apL6.process_allpass_comb_lerp16(left, tl[5] - 46*lfo, ldec[5]);
331 old_left = lp_left.process(left * fb);
332 sanitize(old_left);
334 right += old_left;
335 right = apR1.process_allpass_comb_lerp16(right, tr[0] - 45*lfo, rdec[0]);
336 right = apR2.process_allpass_comb_lerp16(right, tr[1] + 47*lfo, rdec[1]);
337 float out_right = right;
338 right = apR3.process_allpass_comb_lerp16(right, tr[2] + 54*lfo, rdec[2]);
339 right = apR4.process_allpass_comb_lerp16(right, tr[3] - 69*lfo, rdec[3]);
340 right = apR5.process_allpass_comb_lerp16(right, tr[4] + 69*lfo, rdec[4]);
341 right = apR6.process_allpass_comb_lerp16(right, tr[5] - 46*lfo, rdec[5]);
342 old_right = lp_right.process(right * fb);
343 sanitize(old_right);
345 left = out_left, right = out_right;
348 /// Distortion Module by Tom Szilagyi
350 /// This module provides a blendable saturation stage
351 ///////////////////////////////////////////////////////////////////////////////////////////////
353 tap_distortion::tap_distortion()
355 is_active = false;
356 srate = 0;
357 meter = 0.f;
358 rdrive = rbdr = kpa = kpb = kna = knb = ap = an = imr = kc = srct = sq = pwrq = prev_med = prev_out = 0.f;
359 drive_old = blend_old = -1.f;
360 over = 1;
363 void tap_distortion::activate()
365 is_active = true;
366 set_params(0.f, 0.f);
368 void tap_distortion::deactivate()
370 is_active = false;
373 void tap_distortion::set_params(float blend, float drive)
375 // set distortion coeffs
376 if ((drive_old != drive) || (blend_old != blend)) {
377 rdrive = 12.0f / drive;
378 rbdr = rdrive / (10.5f - blend) * 780.0f / 33.0f;
379 kpa = D(2.0f * (rdrive*rdrive) - 1.0f) + 1.0f;
380 kpb = (2.0f - kpa) / 2.0f;
381 ap = ((rdrive*rdrive) - kpa + 1.0f) / 2.0f;
382 kc = kpa / D(2.0f * D(2.0f * (rdrive*rdrive) - 1.0f) - 2.0f * rdrive*rdrive);
384 srct = (0.1f * srate) / (0.1f * srate + 1.0f);
385 sq = kc*kc + 1.0f;
386 knb = -1.0f * rbdr / D(sq);
387 kna = 2.0f * kc * rbdr / D(sq);
388 an = rbdr*rbdr / sq;
389 imr = 2.0f * knb + D(2.0f * kna + 4.0f * an - 1.0f);
390 pwrq = 2.0f / (imr + 1.0f);
392 drive_old = drive;
393 blend_old = blend;
397 void tap_distortion::set_sample_rate(uint32_t sr)
399 srate = sr;
400 over = srate * 2 > 96000 ? 1 : 2;
401 resampler.set_params(srate, over, 2);
404 float tap_distortion::process(float in)
406 double *samples = resampler.upsample((double)in);
407 meter = 0.f;
408 for (int o = 0; o < over; o++) {
409 float proc = samples[o];
410 float med;
411 if (proc >= 0.0f) {
412 med = (D(ap + proc * (kpa - proc)) + kpb) * pwrq;
413 } else {
414 med = (D(an - proc * (kna + proc)) + knb) * pwrq * -1.0f;
416 proc = srct * (med - prev_med + prev_out);
417 prev_med = M(med);
418 prev_out = M(proc);
419 samples[o] = proc;
420 meter = std::max(meter, proc);
422 float out = (float)resampler.downsample(samples);
423 return out;
426 float tap_distortion::get_distortion_level()
428 return meter;
431 ////////////////////////////////////////////////////////////////////////////////
433 simple_lfo::simple_lfo()
435 is_active = false;
436 phase = 0.f;
439 void simple_lfo::activate()
441 is_active = true;
442 phase = 0.f;
445 void simple_lfo::deactivate()
447 is_active = false;
450 float simple_lfo::get_value()
452 return get_value_from_phase(phase, offset) * amount;
455 float simple_lfo::get_value_from_phase(float ph, float off) const
457 float val = 0.f;
458 float phs = ph + off;
459 if (phs >= 1.0)
460 phs = fmod(phs, 1.f);
461 switch (mode) {
462 default:
463 case 0:
464 // sine
465 val = sin((phs * 360.f) * M_PI / 180);
466 break;
467 case 1:
468 // triangle
469 if(phs > 0.75)
470 val = (phs - 0.75) * 4 - 1;
471 else if(phs > 0.5)
472 val = (phs - 0.5) * 4 * -1;
473 else if(phs > 0.25)
474 val = 1 - (phs - 0.25) * 4;
475 else
476 val = phs * 4;
477 break;
478 case 2:
479 // square
480 val = (phs < 0.5) ? -1 : +1;
481 break;
482 case 3:
483 // saw up
484 val = phs * 2.f - 1;
485 break;
486 case 4:
487 // saw down
488 val = 1 - phs * 2.f;
489 break;
491 return val;
494 void simple_lfo::advance(uint32_t count)
496 //this function walks from 0.f to 1.f and starts all over again
497 phase += count * freq * (1.0 / srate);
498 if (phase >= 1.0)
499 phase = fmod(phase, 1.f);
502 void simple_lfo::set_phase(float ph)
504 //set the phase from outsinde
505 phase = fabs(ph);
506 if (phase >= 1.0)
507 phase = fmod(phase, 1.f);
510 void simple_lfo::set_params(float f, int m, float o, uint32_t sr, float a)
512 // freq: a value in Hz
513 // mode: sine=0, triangle=1, square=2, saw_up=3, saw_down=4
514 // offset: value between 0.f and 1.f to offset the lfo in time
515 freq = f;
516 mode = m;
517 offset = o;
518 srate = sr;
519 amount = a;
521 void simple_lfo::set_freq(float f)
523 freq = f;
525 void simple_lfo::set_mode(int m)
527 mode = m;
529 void simple_lfo::set_offset(float o)
531 offset = o;
533 void simple_lfo::set_amount(float a)
535 amount = a;
537 bool simple_lfo::get_graph(float *data, int points, cairo_iface *context, int *mode) const
539 if (!is_active)
540 return false;
541 for (int i = 0; i < points; i++) {
542 float ph = (float)i / (float)points;
543 data[i] = get_value_from_phase(ph, offset) * amount;
545 return true;
548 bool simple_lfo::get_dot(float &x, float &y, int &size, cairo_iface *context) const
550 if (!is_active)
551 return false;
552 float phs = phase + offset;
553 if (phs >= 1.0)
554 phs = fmod(phs, 1.f);
555 x = phase;
556 y = get_value_from_phase(phase, offset) * amount;
557 return true;
561 /// Lookahead Limiter by Christian Holschuh and Markus Schmidt
563 lookahead_limiter::lookahead_limiter() {
564 is_active = false;
565 channels = 2;
566 id = 0;
567 buffer_size = 0;
568 overall_buffer_size = 0;
569 att = 1.f;
570 att_max = 1.0;
571 pos = 0;
572 delta = 0.f;
573 _delta = 0.f;
574 peak = 0.f;
575 over_s = 0;
576 over_c = 1.f;
577 attack = 0.005;
578 use_multi = false;
579 weight = 1.f;
580 _sanitize = false;
581 auto_release = false;
582 asc_active = false;
583 nextiter = 0;
584 nextlen = 0;
585 asc = 0.f;
586 asc_c = 0;
587 asc_pos = -1;
588 asc_changed = false;
589 asc_coeff = 1.f;
591 lookahead_limiter::~lookahead_limiter()
593 free(buffer);
594 free(nextpos);
595 free(nextdelta);
598 void lookahead_limiter::activate()
600 is_active = true;
601 pos = 0;
605 void lookahead_limiter::set_multi(bool set) { use_multi = set; }
607 void lookahead_limiter::deactivate()
609 is_active = false;
612 float lookahead_limiter::get_attenuation()
614 float a = att_max;
615 att_max = 1.0;
616 return a;
619 void lookahead_limiter::set_sample_rate(uint32_t sr)
621 srate = sr;
622 // rebuild buffer
623 overall_buffer_size = (int)(srate * (100.f / 1000.f) * channels) + channels; // buffer size attack rate multiplied by 2 channels
624 buffer = (float*) calloc(overall_buffer_size, sizeof(float));
625 pos = 0;
627 nextdelta = (float*) calloc(overall_buffer_size, sizeof(float));
628 nextpos = (int*) malloc(overall_buffer_size * sizeof(int));
629 memset(nextpos, -1, overall_buffer_size * sizeof(int));
631 reset();
634 void lookahead_limiter::set_params(float l, float a, float r, float w, bool ar, float arc, bool d)
636 limit = l;
637 attack = a / 1000.f;
638 release = r / 1000.f;
639 auto_release = ar;
640 asc_coeff = arc;
641 debug = d;
642 weight = w;
645 void lookahead_limiter::reset() {
646 int bs = (int)(srate * attack * channels);
647 buffer_size = bs - bs % channels; // buffer size attack rate
648 _sanitize = true;
649 pos = 0;
650 nextpos[0] = -1;
651 nextlen = 0;
652 nextiter = 0;
653 delta = 0.f;
654 att = 1.f;
655 reset_asc();
658 void lookahead_limiter::reset_asc() {
659 asc = 0.f;
660 asc_c = 0;
661 asc_pos = pos;
662 asc_changed = true;
665 float lookahead_limiter::get_rdelta(float peak, float _limit, float _att, bool _asc) {
667 // calc the att for average input to walk to if we use asc (att of average signal)
668 float _a_att = (limit * weight) / (asc_coeff * asc) * (float)asc_c;
670 // calc a release delta from this attenuation
671 float _rdelta = (1.0 - _att) / (srate * release);
672 if(_asc and auto_release and asc_c > 0 and _a_att > _att) {
673 // check if releasing to average level of peaks is steeper than
674 // releasing to 1.f
675 float _delta = std::max((_a_att - _att) / (srate * release), _rdelta / 10);
676 if(_delta < _rdelta) {
677 asc_active = true;
678 _asc_used = true;
679 _rdelta = _delta;
682 return _rdelta;
685 void lookahead_limiter::process(float &left, float &right, float * multi_buffer)
687 // PROTIP: harming paying customers enough to make them develop a competing
688 // product may be considered an example of a less than sound business practice.
690 // fill lookahead buffer
691 if(_sanitize) {
692 // if we're sanitizing (zeroing) the buffer on attack time change,
693 // don't write the samples to the buffer
694 buffer[pos] = 0.f;
695 buffer[pos + 1] = 0.f;
696 } else {
697 buffer[pos] = left;
698 buffer[pos + 1] = right;
701 // are we using multiband? get the multiband coefficient or use 1.f
702 float multi_coeff = (use_multi) ? multi_buffer[pos] : 1.f;
704 // calc the real limit including weight and multi coeff
705 float _limit = limit * multi_coeff * weight;
707 // input peak - impact higher in left or right channel?
708 peak = fabs(left) > fabs(right) ? fabs(left) : fabs(right);
710 // add an eventually appearing peak to the asc fake buffer if asc active
711 if(auto_release and peak > _limit) {
712 asc += peak;
713 asc_c ++;
716 if(peak > _limit or multi_coeff < 1.0) {
717 float _multi_coeff = 1.f;
718 float _peak;
720 // calc the attenuation needed to reduce incoming peak
721 float _att = std::min(_limit / peak, 1.f);
722 // calc release without any asc to keep all relevant peaks
723 float _rdelta = get_rdelta(peak, _limit, _att, false);
725 // calc the delta for walking to incoming peak attenuation
726 float _delta = (_limit / peak - att) / buffer_size * channels;
728 if(_delta < delta) {
729 // is the delta more important than the actual one?
730 // if so, we can forget about all stored deltas (because they can't
731 // be more important - we already checked that earlier) and use this
732 // delta now. and we have to create a release delta in nextpos buffer
733 nextpos[0] = pos;
734 nextpos[1] = -1;
735 nextdelta[0] = _rdelta;
736 nextlen = 1;
737 nextiter = 0;
738 delta = _delta;
739 } else {
740 // we have a peak on input its delta is less important than the
741 // actual delta. But what about the stored deltas we're following?
742 bool _found = false;
743 int i = 0;
744 for(i = nextiter; i < nextiter + nextlen; i++) {
745 // walk through our nextpos buffer
746 int j = i % buffer_size;
747 // calculate a delta for the next stored peak
748 // are we using multiband? then get the multi_coeff for the
749 // stored position
750 _multi_coeff = (use_multi) ? multi_buffer[nextpos[j]] : 1.f;
751 // is the left or the right channel on this position more
752 // important?
753 _peak = fabs(buffer[nextpos[j]]) > fabs(buffer[nextpos[j] + 1]) ? fabs(buffer[nextpos[j]]) : fabs(buffer[nextpos[j] + 1]);
754 // calc a delta to use to reach our incoming peak from the
755 // stored position
756 _delta = (_limit / peak - (limit * _multi_coeff * weight) / _peak) / (((buffer_size - nextpos[j] + pos) % buffer_size) / channels);
757 if(_delta < nextdelta[j]) {
758 // if the buffered delta is more important than the delta
759 // used to reach our peak from the stored position, store
760 // the new delta at that position and stop the loop
761 nextdelta[j] = _delta;
762 _found = true;
763 break;
766 if(_found) {
767 // there was something more important in the next-buffer.
768 // throw away any position and delta after the important
769 // position and add a new release delta
770 nextlen = i - nextiter + 1;
771 nextpos[(nextiter + nextlen) % buffer_size] = pos;
772 nextdelta[(nextiter + nextlen) % buffer_size] = _rdelta;
773 // set the next following position value to -1 (cleaning up the
774 // nextpos buffer)
775 nextpos[(nextiter + nextlen + 1) % buffer_size] = -1;
776 // and raise the length of our nextpos buffer for keeping the
777 // release value
778 nextlen ++;
783 // switch left and right pointers in buffer to output position
784 left = buffer[(pos + channels) % buffer_size];
785 right = buffer[(pos + channels + 1) % buffer_size];
787 // if a peak leaves the buffer, remove it from asc fake buffer
788 // but only if we're not sanitizing asc buffer
789 float _peak = fabs(left) > fabs(right) ? fabs(left) : fabs(right);
790 float _multi_coeff = (use_multi) ? multi_buffer[(pos + channels) % buffer_size] : 1.f;
791 if(pos == asc_pos and !asc_changed) {
792 asc_pos = -1;
794 if(auto_release and asc_pos == -1 and _peak > (limit * weight * _multi_coeff)) {
795 asc -= _peak;
796 asc_c --;
799 // change the attenuation level
800 att += delta;
802 // ...and calculate outpout from it
803 left *= att;
804 right *= att;
806 if((pos + channels) % buffer_size == nextpos[nextiter]) {
807 // if we reach a buffered position, change the actual delta and erase
808 // this (the first) element from nextpos and nextdelta buffer
809 if(auto_release) {
810 // set delta to asc influenced release delta
811 delta = get_rdelta(_peak, (limit * weight * _multi_coeff), att);
812 if(nextlen > 1) {
813 // if there are more positions to walk to, calc delta to next
814 // position in buffer and compare it to release delta (keep
815 // changes between peaks below asc steepness)
816 int _nextpos = nextpos[(nextiter + 1) % buffer_size];
817 float __peak = fabs(buffer[_nextpos]) > fabs(buffer[_nextpos + 1]) ? fabs(buffer[_nextpos]) : fabs(buffer[_nextpos + 1]);
818 float __multi_coeff = (use_multi) ? multi_buffer[_nextpos] : 1.f;
819 float __delta = ((limit * __multi_coeff * weight) / __peak - att) / (((buffer_size + _nextpos - ((pos + channels) % buffer_size)) % buffer_size) / channels);
820 if(__delta < delta) {
821 delta = __delta;
824 } else {
825 // if no asc set delta from nextdelta buffer and fix the attenuation
826 delta = nextdelta[nextiter];
827 att = (limit * weight * _multi_coeff) / _peak;
829 // remove first element from circular nextpos buffer
830 nextlen -= 1;
831 nextpos[nextiter] = -1;
832 nextiter = (nextiter + 1) % buffer_size;
835 if (att > 1.0f) {
836 // release time seems over, reset attenuation and delta
837 att = 1.0f;
838 delta = 0.0f;
839 nextiter = 0;
840 nextlen = 0;
841 nextpos[0] = -1;
844 // main limiting party is over, let's cleanup the puke
846 if(_sanitize) {
847 // we're sanitizing? then send 0.f as output
848 left = 0.f;
849 right = 0.f;
852 // security personnel pawing your values
853 if(att <= 0.f) {
854 // if this happens we're doomed!!
855 // may happen on manually lowering attack
856 att = 0.0000000000001;
857 delta = (1.0f - att) / (srate * release);
860 if(att != 1.f and 1 - att < 0.0000000000001) {
861 // denormalize att
862 att = 1.f;
865 if(delta != 0.f and fabs(delta) < 0.00000000000001) {
866 // denormalize delta
867 delta = 0.f;
870 // post treatment (denormal, limit)
871 denormal(&left);
872 denormal(&right);
874 // store max attenuation for meter output
875 att_max = (att < att_max) ? att : att_max;
877 // step forward in our sample ring buffer
878 pos = (pos + channels) % buffer_size;
880 // sanitizing is always done after a full cycle through the lookahead buffer
881 if(_sanitize and pos == 0) _sanitize = false;
883 asc_changed = false;
886 bool lookahead_limiter::get_asc() {
887 if(!asc_active) return false;
888 asc_active = false;
889 return true;
893 ////////////////////////////////////////////////////////////////////////////////
895 transients::transients() {
896 envelope = 0.f;
897 attack = 0.f;
898 release = 0.f;
899 attack_coef = 0.f;
900 release_coef = 0.f;
901 att_time = 0.f;
902 att_level = 0.f;
903 rel_time = 0.f;
904 rel_level = 0.f;
905 sust_thres = 1.f;
906 maxdelta = 0.f;
907 new_return = 1.f;
908 old_return = 1.f;
909 lookahead = 0;
910 lookpos = 0;
911 channels = 1;
912 cnt = 0;
913 sustain_ended = false;
915 transients::~transients()
917 free(lookbuf);
919 void transients::set_channels(int ch) {
920 channels = ch;
921 lookbuf = (float*) calloc(looksize * channels, sizeof(float));
922 lookpos = 0;
924 void transients::set_sample_rate(uint32_t sr) {
925 srate = sr;
926 attack_coef = exp(log(0.01) / (0.001 * srate));
927 release_coef = exp(log(0.01) / (0.2f * srate));
928 // due to new calculation in attack, we sometimes get harsh
929 // gain reduction/boost.
930 // to prevent "clicks" a maxdelta is set, which allows the signal
931 // to raise/fall ~6dB/ms.
932 maxdelta = pow(4, 1.f / (0.001 * srate));
933 calc_relfac();
935 void transients::set_params(float att_t, float att_l, float rel_t, float rel_l, float sust_th, int look) {
936 lookahead = look;
937 sust_thres = sust_th;
938 att_time = att_t;
939 rel_time = rel_t;
940 att_level = att_l > 0 ? 0.25f * pow(att_l * 8, 2)
941 : -0.25f * pow(att_l * 4, 2);
942 rel_level = rel_l > 0 ? 0.5f * pow(rel_l * 8, 2)
943 : -0.25f * pow(rel_l * 4, 2);
944 calc_relfac();
946 void transients::calc_relfac()
948 relfac = pow(0.5f, 1.f / (0.001 * rel_time * srate));
950 void transients::process(float *in) {
951 // fill lookahead buffer
952 float s = 0;
953 for (int i = 0; i < channels; i++) {
954 lookbuf[lookpos + i] = in[i];
955 s += fabs(in[i]);
957 s /= channels;
959 // envelope follower
960 // this is the real envelope follower curve. It raises as
961 // fast as the signal is raising and falls much slower
962 // depending on the sample rate and the ffactor
963 // (the falling factor)
964 if(s > envelope)
965 envelope = attack_coef * (envelope - s) + s;
966 else
967 envelope = release_coef * (envelope - s) + s;
969 // attack follower
970 // this is a curve which follows the envelope slowly.
971 // It never can rise above the envelope. It reaches 70.7%
972 // of the envelope in a certain amount of time set by the user
974 double attdelta = (envelope - attack)
975 * 0.707
976 / (srate * att_time * 0.001);
977 if (sustain_ended == true and envelope / attack - 1 > 0.2f)
978 sustain_ended = false;
979 attack += attdelta;
981 // never raise above envelope
982 attack = std::min(envelope, attack);
984 // release follower
985 // this is a curve which is always above the envelope. It
986 // starts to fall when the envelope falls beneath the
987 // sustain threshold
989 if ((envelope / release) - sust_thres < 0 and sustain_ended == false)
990 sustain_ended = true;
991 double reldelta = sustain_ended ? relfac : 1;
993 // release delta can never raise above 0
994 release *= reldelta;
996 // never fall below envelope
997 release = std::max(envelope, release);
999 // difference between attack and envelope
1000 double attdiff = attack > 0 ? log(envelope / attack) : 0;
1002 // difference between release and envelope
1003 double reldiff = envelope > 0 ? log(release / envelope) : 0;
1005 // amplification factor from attack and release curve
1006 double ampfactor = attdiff * att_level + reldiff * rel_level;
1007 old_return = new_return;
1008 new_return = 1 + (ampfactor < 0 ? expm1(ampfactor) : ampfactor);
1009 if (new_return / old_return > maxdelta)
1010 new_return = old_return * maxdelta;
1011 else if (new_return / old_return < 1 / maxdelta)
1012 new_return = old_return / maxdelta;
1014 int pos = (lookpos + looksize * channels - lookahead * channels) % (looksize * channels);
1016 for (int i = 0; i < channels; i++) {
1017 in[i] = lookbuf[pos + i] * new_return;
1019 //if (in[0] > 0.5)
1020 //fprintf(stderr, "%.5f\n", in[0]);
1021 // advance lookpos
1022 lookpos = (lookpos + channels) % (looksize * channels);
1024 cnt += 1;
1028 //////////////////////////////////////////////////////////////////
1030 crossover::crossover() {
1031 bands = -1;
1032 mode = -1;
1033 redraw_graph = 1;
1035 void crossover::set_sample_rate(uint32_t sr) {
1036 srate = sr;
1038 void crossover::init(int c, int b, uint32_t sr) {
1039 channels = std::min(8, c);
1040 bands = std::min(8, b);
1041 srate = sr;
1042 for(int b = 0; b < bands; b ++) {
1043 // reset frequency settings
1044 freq[b] = 1.0;
1045 active[b] = true;
1046 level[b] = 1.0;
1047 for (int c = 0; c < channels; c ++) {
1048 // reset outputs
1049 out[c][b] = 0.f;
1053 float crossover::set_filter(int b, float f, bool force) {
1054 // keep between neighbour bands
1055 if (b)
1056 f = std::max((float)freq[b-1] * 1.1f, f);
1057 if (b < bands - 2)
1058 f = std::min((float)freq[b+1] * 0.9f, f);
1059 // restrict to 10-20k
1060 f = std::max(10.f, std::min(20000.f, f));
1061 // nothing changed? return
1062 if (freq[b] == f and !force)
1063 return freq[b];
1064 freq[b] = f;
1065 float q;
1066 switch (mode) {
1067 case 0:
1068 default:
1069 q = 0.5;
1070 break;
1071 case 1:
1072 q = 0.7071068123730965;
1073 break;
1074 case 2:
1075 q = 0.54;
1076 break;
1078 for (int c = 0; c < channels; c ++) {
1079 if (!c) {
1080 lp[c][b][0].set_lp_rbj(freq[b], q, (float)srate);
1081 hp[c][b][0].set_hp_rbj(freq[b], q, (float)srate);
1082 } else {
1083 lp[c][b][0].copy_coeffs(lp[c-1][b][0]);
1084 hp[c][b][0].copy_coeffs(hp[c-1][b][0]);
1086 if (mode > 1) {
1087 if (!c) {
1088 lp[c][b][1].set_lp_rbj(freq[b], 1.34, (float)srate);
1089 hp[c][b][1].set_hp_rbj(freq[b], 1.34, (float)srate);
1090 } else {
1091 lp[c][b][1].copy_coeffs(lp[c-1][b][1]);
1092 hp[c][b][1].copy_coeffs(hp[c-1][b][1]);
1094 lp[c][b][2].copy_coeffs(lp[c][b][0]);
1095 hp[c][b][2].copy_coeffs(hp[c][b][0]);
1096 lp[c][b][3].copy_coeffs(lp[c][b][1]);
1097 hp[c][b][3].copy_coeffs(hp[c][b][1]);
1098 } else {
1099 lp[c][b][1].copy_coeffs(lp[c][b][0]);
1100 hp[c][b][1].copy_coeffs(hp[c][b][0]);
1103 redraw_graph = std::min(2, redraw_graph + 1);
1104 return freq[b];
1106 void crossover::set_mode(int m) {
1107 if(mode == m)
1108 return;
1109 mode = m;
1110 for(int i = 0; i < bands - 1; i ++) {
1111 set_filter(i, freq[i], true);
1113 redraw_graph = std::min(2, redraw_graph + 1);
1115 void crossover::set_active(int b, bool a) {
1116 if (active[b] == a)
1117 return;
1118 active[b] = a;
1119 redraw_graph = std::min(2, redraw_graph + 1);
1121 void crossover::set_level(int b, float l) {
1122 if (level[b] == l)
1123 return;
1124 level[b] = l;
1125 redraw_graph = std::min(2, redraw_graph + 1);
1127 void crossover::process(float *data) {
1128 for (int c = 0; c < channels; c++) {
1129 for(int b = 0; b < bands; b ++) {
1130 out[c][b] = data[c];
1131 for (int f = 0; f < get_filter_count(); f++){
1132 if(b + 1 < bands) {
1133 out[c][b] = lp[c][b][f].process(out[c][b]);
1134 lp[c][b][f].sanitize();
1136 if(b - 1 >= 0) {
1137 out[c][b] = hp[c][b - 1][f].process(out[c][b]);
1138 hp[c][b - 1][f].sanitize();
1141 out[c][b] *= level[b];
1145 float crossover::get_value(int c, int b) {
1146 return out[c][b];
1148 bool crossover::get_graph(int subindex, int phase, float *data, int points, cairo_iface *context, int *mode) const
1150 if (subindex >= bands) {
1151 redraw_graph = std::max(0, redraw_graph - 1);
1152 return false;
1154 float ret;
1155 double freq;
1156 for (int i = 0; i < points; i++) {
1157 ret = 1.f;
1158 freq = 20.0 * pow (20000.0 / 20.0, i * 1.0 / points);
1159 for(int f = 0; f < get_filter_count(); f ++) {
1160 if(subindex < bands -1)
1161 ret *= lp[0][subindex][f].freq_gain(freq, (float)srate);
1162 if(subindex > 0)
1163 ret *= hp[0][subindex - 1][f].freq_gain(freq, (float)srate);
1165 ret *= level[subindex];
1166 context->set_source_rgba(0.15, 0.2, 0.0, !active[subindex] ? 0.3 : 0.8);
1167 data[i] = dB_grid(ret);
1169 return true;
1171 bool crossover::get_layers(int index, int generation, unsigned int &layers) const
1173 layers = 0 | (redraw_graph or !generation ? LG_CACHE_GRAPH : 0) | (!generation ? LG_CACHE_GRID : 0);
1174 return redraw_graph or !generation;
1177 int crossover::get_filter_count() const
1179 switch (mode) {
1180 case 0:
1181 default:
1182 return 1;
1183 case 1:
1184 return 2;
1185 case 2:
1186 return 4;
1190 //////////////////////////////////////////////////////////////////
1192 bitreduction::bitreduction()
1194 coeff = 1;
1195 morph = 0;
1196 mode = 0;
1197 dc = 0;
1198 sqr = 0;
1199 aa = 0;
1200 aa1 = 0;
1201 redraw_graph = true;
1202 bypass = true;
1204 void bitreduction::set_sample_rate(uint32_t sr)
1206 srate = sr;
1208 void bitreduction::set_params(float b, float mo, bool bp, uint32_t md, float d, float a)
1210 morph = 1 - mo;
1211 bypass = bp;
1212 dc = d;
1213 aa = a;
1214 mode = md;
1215 coeff = powf(2.0f, b) - 1;
1216 sqr = sqrt(coeff / 2);
1217 aa1 = (1.f - aa) / 2.f;
1218 redraw_graph = true;
1220 float bitreduction::add_dc(float s, float dc) const
1222 return s > 0 ? s *= dc : s /= dc;
1224 float bitreduction::remove_dc(float s, float dc) const
1226 return s > 0 ? s /= dc : s *= dc;
1228 float bitreduction::waveshape(float in) const
1230 double y;
1231 double k;
1233 // add dc
1234 in = add_dc(in, dc);
1236 // main rounding calculation depending on mode
1238 // the idea for anti-aliasing:
1239 // you need a function f which brings you to the scale, where you want to round
1240 // and the function f_b (with f(f_b)=id) which brings you back to your original scale.
1242 // then you can use the logic below in the following way:
1243 // y = f(in) and k = roundf(y)
1244 // if (y > k + aa1)
1245 // k = f_b(k) + ( f_b(k+1) - f_b(k) ) *0.5 * (sin(x - PI/2) + 1)
1246 // if (y < k + aa1)
1247 // k = f_b(k) - ( f_b(k+1) - f_b(k) ) *0.5 * (sin(x - PI/2) + 1)
1249 // whereas x = (fabs(f(in) - k) - aa1) * PI / aa
1250 // for both cases.
1252 switch (mode) {
1253 case 0:
1254 default:
1255 // linear
1256 y = (in) * coeff;
1257 k = roundf(y);
1258 if (k - aa1 <= y and y <= k + aa1) {
1259 k /= coeff;
1260 } else if (y > k + aa1) {
1261 k = k / coeff + ((k + 1) / coeff - k / coeff) * 0.5 * (sin(M_PI * (fabs(y - k) - aa1) / aa - M_PI_2) + 1);
1262 } else {
1263 k = k / coeff - (k / coeff - (k - 1) / coeff) * 0.5 * (sin(M_PI * (fabs(y - k) - aa1) / aa - M_PI_2) + 1);
1265 break;
1266 case 1:
1267 // logarithmic
1268 y = sqr * log(fabs(in)) + sqr * sqr;
1269 k = roundf(y);
1270 if(!in) {
1271 k = 0;
1272 } else if (k - aa1 <= y and y <= k + aa1) {
1273 k = in / fabs(in) * exp(k / sqr - sqr);
1274 } else if (y > k + aa1) {
1275 k = in / fabs(in) * (exp(k / sqr - sqr) + (exp((k + 1) / sqr - sqr) - exp(k / sqr - sqr)) * 0.5 * (sin((fabs(y - k) - aa1) / aa * M_PI - M_PI_2) + 1));
1276 } else {
1277 k = in / fabs(in) * (exp(k / sqr - sqr) - (exp(k / sqr - sqr) - exp((k - 1) / sqr - sqr)) * 0.5 * (sin((fabs(y - k) - aa1) / aa * M_PI - M_PI_2) + 1));
1279 break;
1282 // morph between dry and wet signal
1283 k += (in - k) * morph;
1285 // remove dc
1286 k = remove_dc(k, dc);
1288 return k;
1290 float bitreduction::process(float in)
1292 return waveshape(in);
1295 bool bitreduction::get_layers(int index, int generation, unsigned int &layers) const
1297 layers = redraw_graph or !generation ? LG_CACHE_GRAPH | LG_CACHE_GRID : 0;
1298 return redraw_graph or !generation;
1300 bool bitreduction::get_graph(int subindex, int phase, float *data, int points, cairo_iface *context, int *mode) const
1302 if (subindex >= 2) {
1303 redraw_graph = false;
1304 return false;
1306 for (int i = 0; i < points; i++) {
1307 data[i] = sin(((float)i / (float)points * 360.) * M_PI / 180.);
1308 if (subindex and !bypass)
1309 data[i] = waveshape(data[i]);
1310 else {
1311 context->set_line_width(1);
1312 context->set_source_rgba(0.15, 0.2, 0.0, 0.15);
1315 return true;
1317 bool bitreduction::get_gridline(int subindex, int phase, float &pos, bool &vertical, std::string &legend, cairo_iface *context) const
1319 if (phase or subindex)
1320 return false;
1321 pos = 0;
1322 vertical = false;
1323 return true;
1326 //////////////////////////////////////////////////////////////////
1328 resampleN::resampleN()
1330 factor = 2;
1331 srate = 0;
1332 filters = 2;
1334 resampleN::~resampleN()
1336 free(tmp);
1338 void resampleN::set_params(uint32_t sr, int fctr = 2, int fltrs = 2)
1340 srate = sr;
1341 factor = std::min(16, std::max(1, fctr));
1342 filters = std::min(4, std::max(1, fltrs));
1343 // set all filters
1344 filter[0][0].set_lp_rbj(std::max(25000., (double)srate / 2), 0.8, (float)srate * factor);
1345 for (int i = 1; i < filters; i++) {
1346 filter[0][i].copy_coeffs(filter[0][0]);
1347 filter[1][i].copy_coeffs(filter[0][0]);
1350 double *resampleN::upsample(double sample)
1352 tmp[0] = sample;
1353 if (factor > 1) {
1354 for (int f = 0; f < filters; f++)
1355 tmp[0] = filter[0][f].process(sample);
1356 for (int i = 1; i < factor; i++) {
1357 tmp[i] = 0;
1358 for (int f = 0; f < filters; f++)
1359 tmp[i] = filter[0][f].process(sample);
1362 return tmp;
1364 double resampleN::downsample(double *sample)
1366 if (factor > 1) {
1367 for(int i = 0; i < factor; i++) {
1368 for (int f = 0; f < filters; f++) {
1369 sample[i] = filter[1][f].process(sample[i]);
1373 return sample[0];
1376 //////////////////////////////////////////////////////////////////
1378 samplereduction::samplereduction()
1380 target = 0;
1381 real = 0;
1382 samples = 0;
1383 last = 0;
1384 amount = 0;
1385 round = 0;
1387 void samplereduction::set_params(float am)
1389 amount = am;
1390 round = roundf(amount);
1391 //samples = round;
1393 double samplereduction::process(double in)
1395 samples ++;
1396 if (samples >= round) {
1397 target += amount;
1398 real += round;
1399 if (target + amount >= real + 1) {
1400 last = in;
1401 target = 0;
1402 real = 0;
1404 samples = 0;
1406 return last;