// set the strength with the 'Envelope' dB sliders.

slider1:0<-100,100,1>Attack (%)
slider2:0<-100,100,1>Sustain (%)
slider3:-30<-120,-1,1>Envelope A (dB)
slider4:-120<-120,-1,1>Envelope S (dB)
slider5:0<-24,24,0.1>Output (dB)
slider6:1<0,1,1{Off,On}>Clip

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

@init
gain = 1;
env1 = env2 = 0;
att_env = 1;
sus_env = 1;

@slider
(old_s3 != slider3 && slider3 < slider4) ? slider4 = slider3;
(old_s4 != slider4 && slider4 > slider3) ? slider3 = slider4;
old_s3 = slider3;
old_s4 = slider4;

attack = slider1/200;
sustain = slider2/100;

b1Env1 = -exp(slider3 / srate);
a0Env1 = 1 + b1Env1;
b1Env2 = -exp(slider4 / srate);
a0Env2 = 1 + b1Env2;

vol = 10^(slider5/20);
clip = slider6;

@sample
in = max(abs(spl0),abs(spl1));
in += 0.00000001;

env1 = (tmpEnv1 = a0Env1*in - b1Env1*tmpEnv1);
env2 = (tmpEnv2 = a0Env2*in - b1Env2*tmpEnv2);

gain_in = env2 - env1;
att_env = env2/env1;
sus_env = env1/env2;
(gain_in > 0) ? gain = exp(log(max(att_env,1))*attack) : gain = exp(log(max(sus_env,1))*sustain);
spl0 *= gain;
spl1 *= gain;

/*
att_env = env2/env1;
sus_env = env1/env2;
gain = exp(log(max(att_env,1))*attack) * exp(log(max(sus_env,1))*sustain);
spl0 *= gain;
spl1 *= gain;
*/

clip ? (
spl0 = min(max(spl0*vol,-1),1);
spl1 = min(max(spl1*vol,-1),1);
):(
spl0 = spl0*vol;
spl1 = spl1*vol;
);
