Debian Codegraph @

src/openmpt/soundbase/DitherSimple.hpp

raw
1 /* SPDX-License-Identifier: BSD-3-Clause */
2 /* SPDX-FileCopyrightText: OpenMPT Project Developers and Contributors */
3
4
5 #pragma once
6
7 #include "openmpt/all/BuildSettings.hpp"
8
9 #include "mpt/base/macros.hpp"
10 #include "mpt/random/engine.hpp"
11 #include "mpt/random/default_engines.hpp"
12 #include "mpt/random/random.hpp"
13 #include "mpt/random/seed.hpp"
14 #include "openmpt/base/Types.hpp"
15 #include "openmpt/soundbase/MixSample.hpp"
16 #include "openmpt/soundbase/MixSampleConvert.hpp"
17
18
19 OPENMPT_NAMESPACE_BEGIN
20
21
22 template <int ditherdepth = 1, bool triangular = false, bool shaped = true>
23 struct Dither_SimpleImpl
24 {
25 public:
26 using prng_type = mpt::fast_engine;
27 template <typename Trd>
28 static prng_type prng_init(Trd &rd)
29 {
30 return mpt::make_prng<prng_type>(rd);
31 }
32
33 private:
34 int32 error = 0;
35
36 public:
37 template <uint32 targetbits, typename Trng>
38 MPT_FORCEINLINE MixSampleInt process(MixSampleInt sample, Trng &prng)
39 {
40 if constexpr(targetbits == 0)
41 {
42 MPT_UNUSED(prng);
43 return sample;
44 } else
45 {
46 static_assert(sizeof(MixSampleInt) == 4);
47 constexpr int rshift = (32 - targetbits) - MixSampleIntTraits::mix_headroom_bits;
48 if constexpr(rshift <= 1)
49 {
50 MPT_UNUSED(prng);
51 // nothing to dither
52 return sample;
53 } else
54 {
55 constexpr int rshiftpositive = (rshift > 1) ? rshift : 1; // work-around warnings about negative shift with C++14 compilers
56 constexpr int round_mask = ~((1 << rshiftpositive) - 1);
57 constexpr int round_offset = 1 << (rshiftpositive - 1);
58 constexpr int noise_bits = rshiftpositive + (ditherdepth - 1);
59 constexpr int noise_bias = (1 << (noise_bits - 1));
60 int32 e = error;
61 unsigned int unoise = 0;
62 if constexpr(triangular)
63 {
64 unoise = (mpt::random<unsigned int>(prng, noise_bits) + mpt::random<unsigned int>(prng, noise_bits)) >> 1;
65 } else
66 {
67 unoise = mpt::random<unsigned int>(prng, noise_bits);
68 }
69 int noise = static_cast<int>(unoise) - noise_bias; // un-bias
70 int val = sample;
71 if constexpr(shaped)
72 {
73 val += (e >> 1);
74 }
75 int rounded = (val + noise + round_offset) & round_mask;
76 e = val - rounded;
77 sample = rounded;
78 error = e;
79 return sample;
80 }
81 }
82 }
83 template <uint32 targetbits, typename Trng>
84 MPT_FORCEINLINE MixSampleFloat process(MixSampleFloat sample, Trng &prng)
85 {
86 return mix_sample_cast<MixSampleFloat>(process<targetbits>(mix_sample_cast<MixSampleInt>(sample), prng));
87 }
88 };
89
90 using Dither_Simple = Dither_SimpleImpl<>;
91
92
93 OPENMPT_NAMESPACE_END