libresidfp 1.0.2
Limiter.h
1/*
2 * This file is part of libsidplayfp, a SID player engine.
3 *
4 * Copyright 2026 Leandro Nini <drfiemost@users.sourceforge.net>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 */
20
21#ifndef LIMITER_H
22#define LIMITER_H
23
24#include <cmath>
25#include <cassert>
26
27#include "siddefs-fp.h"
28
30{
31private:
32 static constexpr int threshold = 28000;
33
34 template<int m>
35 static inline int clipper(int x)
36 {
37 static_assert(m > 0, "Clipper range must be a positive value");
38 assert(x >= 0);
39 if (likely(x < threshold))
40 return x;
41
42 constexpr double max_val = static_cast<double>(m);
43 constexpr double t = threshold / max_val;
44 constexpr double a = 1. - t;
45 constexpr double b = 1. / a;
46
47 double value = static_cast<double>(x - threshold) / max_val;
48 value = a * std::tanh(b * value);
49 return static_cast<int>(threshold + (value * max_val));
50 }
51
52 /*
53 * Soft Clipping implementation, splitted for test.
54 */
55 static inline int softClipImpl(int x)
56 {
57 return x < 0 ? -clipper<32768>(-x) : clipper<32767>(x);
58 }
59
60public:
61 /*
62 * Soft Clipping into 16 bit range [-32768,32767]
63 */
64 static inline short softClip(int x) { return static_cast<short>(softClipImpl(x)); }
65
66};
67
68#endif
Definition Limiter.h:30