libsidplayfp  2.11.0
Resampler.h
1 /*
2  * This file is part of libsidplayfp, a SID player engine.
3  *
4  * Copyright 2011-2024 Leandro Nini <drfiemost@users.sourceforge.net>
5  * Copyright 2007-2010 Antti Lankila
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20  */
21 
22 #ifndef RESAMPLER_H
23 #define RESAMPLER_H
24 
25 #include <cmath>
26 #include <cassert>
27 
28 #include "sidcxx11.h"
29 
30 #include "siddefs-fp.h"
31 
32 namespace reSIDfp
33 {
34 
39 class Resampler
40 {
41 private:
42  template<int m>
43  static inline int clipper(int x)
44  {
45  assert(x >= 0);
46  constexpr int threshold = 28000;
47  if (likely(x < threshold))
48  return x;
49 
50  constexpr double max_val = static_cast<double>(m);
51  constexpr double t = threshold / max_val;
52  constexpr double a = 1. - t;
53  constexpr double b = 1. / a;
54 
55  double value = static_cast<double>(x - threshold) / max_val;
56  value = t + a * std::tanh(b * value);
57  return static_cast<int>(value * max_val);
58  }
59 
60  /*
61  * Soft Clipping implementation, splitted for test.
62  */
63  static inline int softClipImpl(int x)
64  {
65  return x < 0 ? -clipper<32768>(-x) : clipper<32767>(x);
66  }
67 
68 protected:
69  /*
70  * Soft Clipping into 16 bit range [-32768,32767]
71  */
72  static inline short softClip(int x) { return static_cast<short>(softClipImpl(x)); }
73 
74  virtual int output() const = 0;
75 
76  Resampler() {}
77 
78 public:
79  virtual ~Resampler() = default;
80 
87  virtual bool input(int sample) = 0;
88 
94  inline short getOutput(int scaleFactor) const
95  {
96  const int out = (scaleFactor * output()) / 2;
97  return softClip(out);
98  }
99 
100  virtual void reset() = 0;
101 };
102 
103 } // namespace reSIDfp
104 
105 #endif
Definition: Resampler.h:40
virtual bool input(int sample)=0
short getOutput(int scaleFactor) const
Definition: Resampler.h:94