dsplib 1.1.0
C++ DSP library for MATLAB-like coding
Loading...
Searching...
No Matches
compressor.h
1#pragma once
2
3#include <dsplib/array.h>
4#include <dsplib/utils.h>
5#include <dsplib/math.h>
6
7namespace dsplib {
8
15{
16public:
27 explicit Compressor(int sample_rate = 44100, real_t threshold = -10.0, int ratio = 5, real_t knee_width = 0,
28 real_t attack_time = 0.01, real_t release_time = 0.2)
29 : T_{threshold}
30 , R_{ratio}
31 , W_{knee_width} {
32 wA_ = std::exp(-std::log(9) / (sample_rate * attack_time));
33 wR_ = std::exp(-std::log(9) / (sample_rate * release_time));
34 DSPLIB_ASSERT(threshold >= -50 && threshold <= 0, "`threshold` must be in range [-50:0] db");
35 DSPLIB_ASSERT(ratio >= 1 && ratio <= 50, "`ratio` must be in range [1:50]");
36 DSPLIB_ASSERT(knee_width >= 0 && knee_width <= 20, "`knee_width` must be in range [0:20] db");
37 DSPLIB_ASSERT(attack_time >= 0 && attack_time <= 4, "`attack_time` must be in range [0:4] sec");
38 DSPLIB_ASSERT(release_time >= 0 && release_time <= 4, "`knee_wrelease_timeidth` must be in range [0:4] sec");
39 }
40
44 struct Result
45 {
46 explicit Result(int n)
47 : out(n)
48 , gain(n) {
49 }
50
53 };
54
62 const int n = x.size();
63 Result res(n);
64 for (int i = 0; i < n; ++i) {
65 const auto gc = _compute_gain(x[i]);
66 if (gc <= gs_) {
67 gs_ = (wA_ * gs_) + (1 - wA_) * gc;
68 } else {
69 gs_ = (wR_ * gs_) + (1 - wR_) * gc;
70 }
71 const auto glin = db2mag(gs_);
72 res.gain[i] = glin;
73 res.out[i] = x[i] * glin;
74 }
75 return res;
76 }
77
83 return this->process(x);
84 }
85
86private:
87 [[nodiscard]] real_t _compute_gain(const real_t& x) const noexcept {
88 //TODO: fast log10?
89 const auto xdb = mag2db(dsplib::abs(x) + eps());
90 auto xsc = xdb;
91 if (xdb >= (T_ + W_ / 2)) {
92 xsc = T_ + (xdb - T_) / R_;
93 } else if ((xdb > (T_ - W_ / 2)) && (xdb < (T_ + W_ / 2))) {
94 xsc = xdb + (1 / R_ - 1) * abs2(xdb - T_ + W_ / 2) / (2 * W_);
95 }
96 return (xsc - xdb);
97 }
98
99 real_t T_{1};
100 int R_{1};
101 real_t W_{0};
102 real_t wA_{1};
103 real_t wR_{1};
104 real_t gs_{0};
105};
106
107} // namespace dsplib
Dynamic range compressor.
Definition compressor.h:15
Result operator()(span_real x)
Process audio frame, obj(x) syntax.
Definition compressor.h:82
Compressor(int sample_rate=44100, real_t threshold=-10.0, int ratio=5, real_t knee_width=0, real_t attack_time=0.01, real_t release_time=0.2)
Construct a new Compressor object.
Definition compressor.h:27
Result process(span_real x)
Process audio frame.
Definition compressor.h:61
Definition span.h:295
Compressor processing result.
Definition compressor.h:45
arr_real out
processed signal, in * gain
Definition compressor.h:51
arr_real gain
applied gain
Definition compressor.h:52