diff --git a/include/dsp/convert.hpp b/include/dsp/convert.hpp new file mode 100644 index 00000000..f41f7e50 --- /dev/null +++ b/include/dsp/convert.hpp @@ -0,0 +1,65 @@ +#pragma once +#include +#include + + +namespace rack { +namespace dsp { + + +/** 24-bit integer, using int32_t for conversions. */ +struct __attribute__((packed)) int24_t { + int32_t i : 24; + int24_t(int32_t i) : i(i) {} + operator int32_t() {return i;} +}; +static_assert(sizeof(int24_t) == 3, "int24_t type must be 3 bytes"); + + +/** Converts between normalized types */ +template +To convert(From x); + + +/** Trivial conversion */ +template +To convert(To x) {return x;} + + +/** Integer to float */ +template <> +inline float convert(int8_t x) {return x / 128.f;} +template <> +inline float convert(int16_t x) {return x / 32768.f;} +template <> +inline float convert(int24_t x) {return x / 8388608.f;} +template <> +inline float convert(int32_t x) {return x / 2147483648.f;} +template <> +inline float convert(int64_t x) {return x / 9223372036854775808.f;} + + +/** Float to integer */ +template <> +inline int8_t convert(float x) {return std::min(std::llround(x * 128.f), 127LL);} +template <> +inline int16_t convert(float x) {return std::min(std::llround(x * 32768.f), 32767LL);} +template <> +inline int24_t convert(float x) {return std::min(std::llround(x * 8388608.f), 8388607LL);} +template <> +inline int32_t convert(float x) {return std::min(std::llround(x * 2147483648.f), 2147483647LL);} +template <> +inline int64_t convert(float x) {return std::min(std::llround(x * 9223372036854775808.f), 9223372036854775807LL);} + + +/** Buffer conversion */ +template +void convert(const From* in, To* out, size_t len) { + for (size_t i = 0; i < len; i++) { + out[i] = convert(in[i]); + } +} + + +} // namespace dsp +} // namespace rack diff --git a/include/rack.hpp b/include/rack.hpp index 08f2f894..9c3b56cf 100644 --- a/include/rack.hpp +++ b/include/rack.hpp @@ -94,6 +94,7 @@ Directly including Rack headers other than rack.hpp in your plugin is unsupporte #include #include +#include #include #include #include @@ -106,7 +107,7 @@ Directly including Rack headers other than rack.hpp in your plugin is unsupporte #include #include #include -#include +#include #include #include