PcmUtils.hxx 2.02 KB
Newer Older
1
/*
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 21
#ifndef MPD_PCM_UTILS_H
#define MPD_PCM_UTILS_H
Warren Dukes's avatar
Warren Dukes committed
22

23
#include "Compiler.h"
24

25 26
#include <limits>

27
#include <stdint.h>
28

29 30 31
enum class SampleFormat : uint8_t;
template<SampleFormat F> struct SampleTraits;

32 33 34 35 36
/**
 * Add a byte count to the specified pointer.  This is a utility
 * function to convert a source pointer and a byte count to an "end"
 * pointer for use in loops.
 */
Max Kellermann's avatar
Max Kellermann committed
37 38 39
template<typename T>
static inline const T *
pcm_end_pointer(const T *p, size_t size)
40
{
Max Kellermann's avatar
Max Kellermann committed
41
	return (const T *)((const uint8_t *)p + size);
42 43
}

44 45 46 47
/**
 * Check if the value is within the range of the provided bit size,
 * and caps it if necessary.
 */
48
template<SampleFormat F, class Traits=SampleTraits<F>>
49
gcc_const
50 51
static inline typename Traits::value_type
PcmClamp(typename Traits::long_type x)
52
{
53 54 55 56
	typedef typename Traits::value_type T;
	typedef typename Traits::long_type U;
	constexpr U MIN_VALUE = -(U(1) << (Traits::BITS - 1));
	constexpr U MAX_VALUE = (U(1) << (Traits::BITS - 1)) - 1;
57 58 59 60

	typedef std::numeric_limits<T> limits;
	static_assert(MIN_VALUE >= limits::min(), "out of range");
	static_assert(MAX_VALUE <= limits::max(), "out of range");
61

62
	if (gcc_unlikely(x < MIN_VALUE))
63 64
		return T(MIN_VALUE);

65
	if (gcc_unlikely(x > MAX_VALUE))
66 67 68 69 70
		return T(MAX_VALUE);

	return T(x);
}

Warren Dukes's avatar
Warren Dukes committed
71
#endif