/
adsr140.udo
121 lines (99 loc) · 2.58 KB
/
adsr140.udo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
; Gated, Retriggerable Envelope Generator UDO (adsr140)
; Based on design of Doepfer A-140 Envelope Generator Module
; Code based on ADSR code by Nigel Redmon
; (http://www.earlevel.com/main/2013/06/03/envelope-generators-adsr-code/)
; Example by Steven Yi (2015.02.08)
opcode adsr140_calc_coef, k, kk
knum_samps, kratio xin
xout exp( -log((1.0 + kratio) / kratio) / knum_samps)
endop
/* Gated, Re-triggerable ADSR modeled after the Doepfer A-140 */
opcode adsr140, a, aakkkk
agate, aretrig, kattack, kdecay, ksustain, krelease xin
kstate init 0 ; 0 = attack, 1 = decay, 2 = sustain
klasttrig init -1
kval init 0.0
asig init 0
kindx = 0
kattack_base init 0
kdecay_base init 0
krelease_base init 0
kattack_samps init 0
kdecay_samps init 0
krelease_samps init 0
kattack_coef init 0
kdecay_coef init 0
ksustain_coef init 0
klast_attack init -1
klast_decay init -1
klast_release init -1
if (klast_attack != kattack) then
klast_attack = kattack
if(kattack > 0) then
kattack_samps = kattack * sr
kattack_coef = adsr140_calc_coef(kattack_samps, 0.3)
kattack_base = (1.0 + 0.3) * (1 - kattack_coef)
else
kattack_samps = 0
kattack_coef = 0
kattack_base = 0
endif
endif
if (klast_decay != kdecay) then
klast_decay = kdecay
kdecay_samps = kdecay * sr
kdecay_coef = adsr140_calc_coef(kdecay_samps, 0.0001)
kdecay_base = (ksustain - 0.0001) * (1.0 - kdecay_coef)
endif
if (klast_release != krelease) then
klast_release = krelease
krelease_samps = krelease * sr
krelease_coef = adsr140_calc_coef(krelease_samps, 0.0001)
krelease_base = -0.0001 * (1.0 - krelease_coef)
endif
while (kindx < ksmps) do
if (agate[kindx] > 0) then
kretrig = aretrig[kindx]
if (kretrig > 0 && klasttrig <= 0) then
kstate = 0
endif
klasttrig = kretrig
if (kstate == 0) then
if(kattack <= 0) then
kval = 1.0
kstate = 1
else
kval = kattack_base + (kval * kattack_coef)
if(kval >= 1.0) then
kval = 1.0
kstate = 1
endif
asig[kindx] = kval
endif
elseif (kstate == 1) then
kval = kdecay_base + (kval * kdecay_coef)
if(kval <= ksustain) then
kval = ksustain
kstate = 2
endif
asig[kindx] = kval
else
asig[kindx] = ksustain
endif
else ; in a release state
kstate = 0
if (kval == 0.0) then
asig[kindx] = 0
else
; releasing
kval = krelease_base + (kval * krelease_coef)
if(kval <= 0.0) then
kval = 0.0
endif
asig[kindx] = kval
endif
endif
kindx += 1
od
xout asig
endop