libresidfp 1.1.1
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#include <cstdint>
27
28#include "siddefs-fp.h"
29
31{
32private:
33 static constexpr int32_t threshold = 28000;
34
35 template<int m>
36 static inline int32_t clipper(int32_t x)
37 {
38 static_assert(m > 0, "Clipper range must be a positive value");
39 assert(x >= 0);
40 if (likely(x < threshold))
41 return x;
42
43 constexpr double max_val = static_cast<double>(m);
44 constexpr double t = threshold / max_val;
45 constexpr double a = 1. - t;
46 constexpr double b = 1. / a;
47
48 double value = static_cast<double>(x - threshold) / max_val;
49 value = a * std::tanh(b * value);
50 return static_cast<int32_t>(threshold + (value * max_val));
51 }
52
53 /*
54 * Soft Clipping implementation, splitted for test.
55 */
56 static inline int32_t softClipImpl(int32_t x)
57 {
58 return x < 0 ? -clipper<32768>(-x) : clipper<32767>(x);
59 }
60
61public:
62 /*
63 * Soft Clipping into 16 bit range [-32768,32767]
64 */
65 static inline int16_t softClip(int32_t x) { return static_cast<int16_t>(softClipImpl(x)); }
66
67};
68
69#endif
Definition Limiter.h:31