1 /*
2  * Copyright 2003-2021 The Music Player Daemon Project
3  * http://www.musicpd.org
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 
20 #ifndef MPD_PCM_DITHER_HXX
21 #define MPD_PCM_DITHER_HXX
22 
23 #include <cstdint>
24 
25 enum class SampleFormat : uint8_t;
26 
27 class PcmDither {
28 	int32_t error[3];
29 	int32_t random;
30 
31 public:
PcmDither()32 	constexpr PcmDither() noexcept
33 		:error{0, 0, 0}, random(0) {}
34 
35 	/**
36 	 * Shift the given sample by #SBITS-#DBITS to the right, and
37 	 * apply dithering.
38 	 *
39 	 * @tparam ST the input sample type
40 	 * @tparam SBITS the input bit width
41 	 * @tparam DBITS the output bit width
42 	 * @param sample the input sample value
43 	 */
44 	template<typename ST, unsigned SBITS, unsigned DBITS>
45 	ST DitherShift(ST sample) noexcept;
46 
47 	void Dither24To16(int16_t *dest, const int32_t *src,
48 			  const int32_t *src_end) noexcept;
49 
50 	void Dither32To16(int16_t *dest, const int32_t *src,
51 			  const int32_t *src_end) noexcept;
52 
53 private:
54 	/**
55 	 * Shift the given sample by #scale_bits to the right, and
56 	 * apply dithering.
57 	 *
58 	 * @param T the input sample type
59 	 * @param MIN the minimum input sample value
60 	 * @param MAX the maximum input sample value
61 	 * @param scale_bits the number of bits to be discarded
62 	 * @param sample the input sample value
63 	 */
64 	template<typename T, T MIN, T MAX, unsigned scale_bits>
65 	T Dither(T sample) noexcept;
66 
67 	/**
68 	 * Convert the given sample from one sample format to another,
69 	 * discarding bits.
70 	 *
71 	 * @param ST the input #SampleTraits class
72 	 * @param ST the output #SampleTraits class
73 	 * @param sample the input sample value
74 	 */
75 	template<typename ST, typename DT>
76 	typename DT::value_type DitherConvert(typename ST::value_type sample) noexcept;
77 
78 	template<typename ST, typename DT>
79 	void DitherConvert(typename DT::pointer dest,
80 			   typename ST::const_pointer src,
81 			   typename ST::const_pointer src_end) noexcept;
82 };
83 
84 #endif
85