dsplib 1.1.0
C++ DSP library for MATLAB-like coding
Loading...
Searching...
No Matches
limiter.h
1#pragma once
2
3#include <dsplib/array.h>
4#include <dsplib/utils.h>
5#include <dsplib/math.h>
6
7namespace dsplib {
8
9//Dynamic range limiter
11{
12public:
13 explicit Limiter(int sample_rate = 44100, real_t threshold = -10.0, real_t knee_width = 0, real_t attack_time = 0,
14 real_t release_time = 0.2)
15 : T_{threshold}
16 , W_{knee_width}
17 , wA_{std::exp(-std::log(real_t(9)) / (sample_rate * attack_time))}
18 , wR_{std::exp(-std::log(real_t(9)) / (sample_rate * release_time))} {
19 DSPLIB_ASSERT(threshold >= -50 && threshold <= 0, "`threshold` must be in range [-50:0] db");
20 DSPLIB_ASSERT(knee_width >= 0 && knee_width <= 20, "`knee_width` must be in range [0:20] db");
21 DSPLIB_ASSERT(attack_time >= 0 && attack_time <= 4, "`attack_time` must be in range [0:4] sec");
22 DSPLIB_ASSERT(release_time >= 0 && release_time <= 4, "`knee_wrelease_timeidth` must be in range [0:4] sec");
23 }
24
25 struct Result
26 {
27 explicit Result(int n)
28 : out(n)
29 , gain(n) {
30 }
31 arr_real out;
32 arr_real gain;
33 };
34
35 Result process(span_real x) {
36 const int n = x.size();
37 Result res(n);
38 for (int i = 0; i < n; ++i) {
39 const auto gc = _compute_gain(x[i]);
40 if (gc <= gs_) {
41 gs_ = (wA_ * gs_) + (1 - wA_) * gc;
42 } else {
43 gs_ = (wR_ * gs_) + (1 - wR_) * gc;
44 }
45 const auto glin = db2mag(gs_);
46 res.gain[i] = glin;
47 res.out[i] = x[i] * glin;
48 }
49 return res;
50 }
51
52 Result operator()(span_real x) {
53 return this->process(x);
54 }
55
56private:
57 real_t _compute_gain(const real_t& x) const noexcept {
58 const auto xdb = mag2db(dsplib::abs(x) + eps());
59 auto xsc = xdb;
60 if (xdb >= (T_ + W_ / 2)) {
61 xsc = T_;
62 } else if ((xdb > (T_ - W_ / 2)) && (xdb < (T_ + W_ / 2))) {
63 xsc = xdb - abs2(xdb - T_ + W_ / 2) / (2 * W_);
64 }
65 return (xsc - xdb);
66 }
67
68 real_t T_{1};
69 real_t W_{0};
70 real_t wA_{1};
71 real_t wR_{1};
72 real_t gs_{0};
73};
74
75} // namespace dsplib
Definition limiter.h:11
Definition span.h:295
Definition limiter.h:26