You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.6KB

  1. #pragma once
  2. #include <type_traits>
  3. #include <dsp/common.hpp>
  4. namespace rack {
  5. namespace dsp {
  6. /** 24-bit integer, using int32_t for conversions. */
  7. struct __attribute__((packed)) int24_t {
  8. int32_t i : 24;
  9. int24_t(int32_t i) : i(i) {}
  10. operator int32_t() {return i;}
  11. };
  12. static_assert(sizeof(int24_t) == 3, "int24_t type must be 3 bytes");
  13. /** Converts between normalized types.
  14. Default implementation is the default cast.
  15. */
  16. template <typename To, typename From>
  17. To convert(From x) {return x;}
  18. /** Integer to float */
  19. template <>
  20. inline float convert(int8_t x) {return x / 128.f;}
  21. template <>
  22. inline float convert(int16_t x) {return x / 32768.f;}
  23. template <>
  24. inline float convert(int24_t x) {return x / 8388608.f;}
  25. template <>
  26. inline float convert(int32_t x) {return x / 2147483648.f;}
  27. template <>
  28. inline float convert(int64_t x) {return x / 9223372036854775808.f;}
  29. /** Float to integer */
  30. template <>
  31. inline int8_t convert(float x) {return std::min(std::llround(x * 128.f), 127LL);}
  32. template <>
  33. inline int16_t convert(float x) {return std::min(std::llround(x * 32768.f), 32767LL);}
  34. template <>
  35. inline int24_t convert(float x) {return std::min(std::llround(x * 8388608.f), 8388607LL);}
  36. template <>
  37. inline int32_t convert(float x) {return std::min(std::llround(x * 2147483648.f), 2147483647LL);}
  38. template <>
  39. inline int64_t convert(float x) {return std::min(std::llround(x * 9223372036854775808.f), 9223372036854775807LL);}
  40. /** Buffer conversion */
  41. template <typename To, typename From>
  42. void convert(const From* in, To* out, size_t len) {
  43. for (size_t i = 0; i < len; i++) {
  44. out[i] = convert<To, From>(in[i]);
  45. }
  46. }
  47. } // namespace dsp
  48. } // namespace rack