summaryrefslogtreecommitdiffstats
path: root/src/adsr.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/adsr.c')
-rw-r--r--src/adsr.c49
1 files changed, 49 insertions, 0 deletions
diff --git a/src/adsr.c b/src/adsr.c
index 4336bb5..439d7b1 100644
--- a/src/adsr.c
+++ b/src/adsr.c
@@ -45,3 +45,52 @@ adsr_amplitude(adsr_t *adsr, float noteOn, float noteOff, unsigned long long ela
return clamp(mod, -1, 1);
}
+
+float
+fix_adsr(adsr_t *adsr, float noteOn, float noteOff, unsigned long long elapsed, unsigned long long noteOffSample)
+{
+ // convert to samples
+ unsigned long long attack = adsr->a * SAMPLE_RATE + 1;
+ unsigned long long decay = adsr->d * SAMPLE_RATE + 1;
+ unsigned long long sustain = adsr->s * SAMPLE_RATE + 1;
+ unsigned long long release = adsr->r * SAMPLE_RATE + 1;
+
+ float mod = 0.0f;
+
+ // if note is pressed
+ if (noteOn != 0 && noteOff == 0) {
+ if (elapsed < attack) {
+ // we are in the attack phase
+ mod = ((float)elapsed / attack) * adsr->peak;
+ }
+ else if (/* elapsed >= attack && */ elapsed < attack + decay) {
+ // we are in the decay phase
+ mod = ((float)(elapsed - attack) / decay) * (adsr->s - adsr->peak) + adsr->peak;
+ }
+ else {// sustain
+ mod = adsr->s;
+ }
+ }
+ else { // note is not pressed
+ if (elapsed < noteOffSample + release) {
+ // we are on the release
+
+ // reuse previous block to find starting value
+ if (noteOffSample < attack) {
+ mod = ((float)noteOffSample / attack) * adsr->peak;
+ }
+ else if (/* elapsed >= attack && */ noteOffSample < attack + decay) {
+ mod = ((float)(noteOffSample - attack) / decay) * (adsr->s - adsr->peak) + adsr->peak;
+ }
+ else {
+ mod = adsr->s;
+ }
+
+ mod = (0 - mod) / (float)release * (elapsed - noteOffSample) + mod;
+ }
+ //printf("el: %ld, att: %ld MOD: %f, on %f, off %f\n", elapsed, attack, mod, noteOn, noteOff);
+ }
+
+
+ return mod;
+}