Line data Source code
1 : #pragma once
2 :
3 : #include <cmath>
4 :
5 : #include "common.h"
6 :
7 : namespace Amplitron {
8 :
9 : /**
10 : * Attack/release envelope follower.
11 : * Used by Compressor, NoiseGate, WahPedal, and AmpSimulator.
12 : */
13 177 : struct EnvelopeFollower {
14 111 : float envelope = 0.0f;
15 :
16 : /**
17 : * Compute attack/release coefficients from time constants.
18 : * @param ms Time in milliseconds.
19 : * @param sr Sample rate.
20 : * @return One-pole coefficient (pass to process()).
21 : */
22 685 : static float time_to_coeff(float ms, int sr) { return std::exp(-1.0f / (sr * ms * 0.001f)); }
23 :
24 : /**
25 : * Process one sample and return the new envelope value.
26 : * Coefficients are in "smoothing" form: higher = slower.
27 : */
28 24000 : float process(float input, float attack_coeff, float release_coeff) {
29 24000 : float abs_in = std::fabs(input);
30 24000 : float coeff = (abs_in > envelope) ? attack_coeff : release_coeff;
31 24000 : envelope = coeff * envelope + (1.0f - coeff) * abs_in;
32 24000 : return envelope;
33 : }
34 :
35 : /**
36 : * Alternative form matching the Compressor's convention:
37 : * coeff = 1 - exp(...), applied as: envelope += coeff * (abs - envelope)
38 : */
39 238080 : float process_additive(float input, float attack_coeff, float release_coeff) {
40 238080 : float abs_in = std::fabs(input);
41 193024 : float coeff = (abs_in > envelope) ? (1.0f - attack_coeff) : (1.0f - release_coeff);
42 238080 : envelope += coeff * (abs_in - envelope);
43 238080 : return envelope;
44 : }
45 :
46 249 : void reset() { envelope = 0.0f; }
47 : };
48 :
49 : } // namespace Amplitron
|