// -dynamic threshold- compressor
// good for making sustaining delay/reverb tails more prominent...

slider1:0.8<0,1,0.001>volume
slider2:0.2<0,1,0.001>sustain
slider3:1<0,1,0.01>wet mix
slider4:0.5<0,1,0.01>output

in_pin:L in
in_pin:R in
out_pin:L out
out_pin:R out

@init
cSAMPLE_RATE = 1/srate;
tmp = 0.01; //10 ms decay time on peak detector
prls = 1 - (cSAMPLE_RATE/(cSAMPLE_RATE + tmp));

tmp = 0.05; //50 ms att/rel on compressor
calpha = cSAMPLE_RATE/(cSAMPLE_RATE + tmp);
cbeta = 1 - calpha;
cthresh = 0.25;
cratio = 0.25;

timer = 0;
hold = (srate*0.0125)|0; //12.5ms

db2log = log(10)/20;

compeak = 0;
compenv = 0;
oldcompenv = 0;
cpthresh = cthresh; //dynamic threshold

@slider
Pvolume = slider1;
level = exp((-60 * (1 - (Pvolume + 0.2)))*db2log); //-48dB to +12dB

Psustain = slider2;
fsustain = Psustain;
cratio = 1.25 - fsustain;
cthresh = 0.25 + fsustain;

input = exp((60 * fsustain - 18)*db2log); //-18dB to +42dB

fwet = slider3; //wet mix
fout = slider4; //output
wet = 1 - fwet;
wet = fout * (1 - wet * wet); //-3dB at 50% mix
dry = fout * 2 * (1 - fwet * fwet);

@sample
auxtempl = spl0 * input;
auxtempr = spl1 * input;
auxcombi = 0.5 * (auxtempl + auxtempr);

(abs(auxcombi) > compeak) ? (
compeak = abs(auxcombi); //first do peak detection on the signal
timer = 0;
);
(timer>hold) ? (
compeak *= prls;
timer-=1;
);
timer+=1;
compenv = cbeta * oldcompenv + calpha * compeak; //next average into envelope follower
oldcompenv = compenv;

(compenv > cpthresh) ? ( //if envelope of signal exceeds thresh, then compress
compg = cpthresh + cpthresh*(compenv - cpthresh)/compenv;
cpthresh = cthresh + cratio*(compg - cpthresh); //cpthresh changes dynamically
tmpgain = compg/compenv;
):(
tmpgain = 1;
);

(compenv < cpthresh) ? cpthresh = compenv;
(cpthresh < cthresh) ? cpthresh = cthresh;

spl0 = spl0 * dry + auxtempl * tmpgain * (level/input) * wet;
spl1 = spl1 * dry + auxtempr * tmpgain * (level/input) * wet;

@gfx 0 100
gfx_r=0; gfx_g=0.9; gfx_b=0; gfx_a=1;
gfx_setfont(1,"Arial", 16);

gfx_x =20; gfx_y =10;  gfx_printf("%.1f",(-60 * (1 - (Pvolume + 0.2))) );
gfx_x =60; gfx_y =10;  gfx_printf("dB");
gfx_x =90; gfx_y =10;  gfx_printf("Volume");

gfx_x =20; gfx_y =30;  gfx_printf("%.1f",(60 * fsustain - 18) );
gfx_x =60; gfx_y =30;  gfx_printf("dB");
gfx_x =90; gfx_y =30;  gfx_printf("Sustain");

gfx_x =20; gfx_y =50;  gfx_printf("%.0f",(100 * fwet) );
gfx_x =60; gfx_y =50;  gfx_drawchar($'%');
gfx_x =90; gfx_y =50;  gfx_printf("Wet Mix");

gfx_x =20; gfx_y =70;  gfx_printf("%.1f",(20 * log10(2 * fout)) );
gfx_x =60; gfx_y =70;  gfx_printf("dB");
gfx_x =90; gfx_y =70;  gfx_printf("Output");
