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