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.

56 lines
1.4KB

  1. #pragma once
  2. #include <assert.h>
  3. #include <string.h>
  4. #include <speex/speex_resampler.h>
  5. #include "frame.hpp"
  6. namespace rack {
  7. template<int CHANNELS>
  8. struct SampleRateConverter {
  9. SpeexResamplerState *state = NULL;
  10. bool noConversion = true;
  11. SampleRateConverter() {
  12. int error;
  13. state = speex_resampler_init(CHANNELS, 44100, 44100, SPEEX_RESAMPLER_QUALITY_DEFAULT, &error);
  14. assert(error == RESAMPLER_ERR_SUCCESS);
  15. }
  16. ~SampleRateConverter() {
  17. speex_resampler_destroy(state);
  18. }
  19. void setRates(float inRate, float outRate) {
  20. int error = speex_resampler_set_rate(state, inRate, outRate);
  21. assert(error == RESAMPLER_ERR_SUCCESS);
  22. noConversion = inRate == outRate;
  23. }
  24. void setRatioSmooth(float ratio) DEPRECATED {
  25. // FIXME: this doesn't do a smooth change -- speex doesn't appear to support that.
  26. const int base = 1000;
  27. setRates(base, ratio * base);
  28. }
  29. /** `in` and `out` are interlaced with the number of channels */
  30. void process(const Frame<CHANNELS> *in, int *inFrames, Frame<CHANNELS> *out, int *outFrames) {
  31. if (noConversion) {
  32. int len = std::min(*inFrames, *outFrames);
  33. memcpy(out, in, len * sizeof(Frame<CHANNELS>));
  34. *inFrames = len;
  35. *outFrames = len;
  36. return;
  37. }
  38. speex_resampler_process_interleaved_float(state, (const float*)in, (unsigned int*)inFrames, (float*)out, (unsigned int*)outFrames);
  39. }
  40. void reset() {
  41. int error = speex_resampler_reset_mem(state);
  42. assert(error == RESAMPLER_ERR_SUCCESS);
  43. }
  44. };
  45. } // namespace rack