-
Notifications
You must be signed in to change notification settings - Fork 29
/
compressor.go
136 lines (120 loc) · 2.8 KB
/
compressor.go
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package effects
import (
"math"
)
/*
* Data structure representing a compressor effect.
*/
type compressor struct {
unitStruct
envelope float64
}
/*
* Compressor audio processing.
*/
func (this *compressor) Process(in []float64, out []float64, sampleRate uint32) {
this.mutex.RLock()
follow, _ := this.getDiscreteValue("follow")
gainLimit, _ := this.getNumericValue("gain_limit")
targetLevel, _ := this.getNumericValue("target_level")
this.mutex.RUnlock()
gainLimitFac := decibelsToFactor(gainLimit)
targetLevelFac := decibelsToFactor(targetLevel)
sampleRateFloat := float64(sampleRate)
dischargePerSampleEnvelopeArg := -20.0 / sampleRateFloat
dischargePerSampleEnvelopeInv := math.Exp(dischargePerSampleEnvelopeArg)
dischargePerSampleEnvelope := 1.0 - dischargePerSampleEnvelopeInv
envelope := this.envelope
/*
* Process each sample.
*/
for i, sample := range in {
sampleAbs := math.Abs(sample)
/*
* Follow either level or envelope.
*/
switch follow {
case "envelope":
envelope *= dischargePerSampleEnvelopeInv
/*
* If the absolute value of the current sample exceeds the
* current envelope value, make it the new envelope value.
*/
if sampleAbs > envelope {
envelope = sampleAbs
}
case "level":
diff := sampleAbs - envelope
envelope += diff * dischargePerSampleEnvelope
default:
envelope = 1.0
}
gain := targetLevelFac / envelope
/*
* Limit maximum gain.
*/
if gain > gainLimitFac {
gain = gainLimitFac
}
pre := gain * sample
/*
* Limit the output signal to the appropriate range.
*/
if pre < -1.0 {
pre = -1.0
} else if pre > 1.0 {
pre = 1.0
}
out[i] = pre
}
this.envelope = envelope
}
/*
* Create a compressor effects unit.
*/
func createCompressor() Unit {
/*
* Create effects unit.
*/
u := compressor{
unitStruct: unitStruct{
unitType: UNIT_COMPRESSOR,
params: []Parameter{
Parameter{
Name: "follow",
Type: PARAMETER_TYPE_DISCRETE,
PhysicalUnit: "",
Minimum: -1,
Maximum: -1,
NumericValue: -1,
DiscreteValueIndex: 1,
DiscreteValues: []string{
"envelope",
"level",
},
},
Parameter{
Name: "gain_limit",
Type: PARAMETER_TYPE_NUMERIC,
PhysicalUnit: "dB",
Minimum: 0,
Maximum: 30,
NumericValue: 30,
DiscreteValueIndex: -1,
DiscreteValues: nil,
},
Parameter{
Name: "target_level",
Type: PARAMETER_TYPE_NUMERIC,
PhysicalUnit: "dB",
Minimum: -30,
Maximum: 0,
NumericValue: -20,
DiscreteValueIndex: -1,
DiscreteValues: nil,
},
},
},
}
return &u
}