PcmDither.cxx 2.17 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2013 The Music Player Daemon Project
3
 * http://www.musicpd.org
4 5 6 7 8 9 10 11 12 13
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
14 15 16 17
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 19
 */

20
#include "config.h"
Max Kellermann's avatar
Max Kellermann committed
21 22
#include "PcmDither.hxx"
#include "PcmPrng.hxx"
23

24 25
inline int16_t
PcmDither::Dither24To16(int_fast32_t sample)
26
{
27 28 29 30 31 32 33 34
	constexpr unsigned from_bits = 24;
	constexpr unsigned to_bits = 16;
	constexpr unsigned scale_bits = from_bits - to_bits;
	constexpr int_fast32_t round = 1 << (scale_bits - 1);
	constexpr int_fast32_t mask = (1 << scale_bits) - 1;
	constexpr int_fast32_t ONE = 1 << (from_bits - 1);
	constexpr int_fast32_t MIN = -ONE;
	constexpr int_fast32_t MAX = ONE - 1;
35

36
	sample += error[0] - error[1] + error[2];
37

38 39
	error[2] = error[1];
	error[1] = error[0] / 2;
40 41

	/* round */
42
	int_fast32_t output = sample + round;
43

44 45
	int_fast32_t rnd = pcm_prng(random);
	output += (rnd & mask) - (random & mask);
46

47
	random = rnd;
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

	/* clip */
	if (output > MAX) {
		output = MAX;

		if (sample > MAX)
			sample = MAX;
	} else if (output < MIN) {
		output = MIN;

		if (sample < MIN)
			sample = MIN;
	}

	output &= ~mask;

64
	error[0] = sample - output;
65 66 67 68 69

	return (int16_t)(output >> scale_bits);
}

void
70 71
PcmDither::Dither24To16(int16_t *dest, const int32_t *src,
			const int32_t *src_end)
72
{
73
	while (src < src_end)
74
		*dest++ = Dither24To16(*src++);
75
}
76

77 78
inline int16_t
PcmDither::Dither32To16(int_fast32_t sample)
79
{
80
	return Dither24To16(sample >> 8);
81 82 83
}

void
84 85
PcmDither::Dither32To16(int16_t *dest, const int32_t *src,
			const int32_t *src_end)
86
{
87
	while (src < src_end)
88
		*dest++ = Dither32To16(*src++);
89
}