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.

64 lines
1.7KB

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