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.

57 lines
1.5KB

  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 bypass = false;
  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 setQuality(int quality) {
  20. speex_resampler_set_quality(state, quality);
  21. }
  22. void setRates(int inRate, int outRate) {
  23. spx_uint32_t oldInRate, oldOutRate;
  24. speex_resampler_get_rate(state, &oldInRate, &oldOutRate);
  25. if (inRate == (int) oldInRate && outRate == (int) oldOutRate)
  26. return;
  27. int error = speex_resampler_set_rate(state, inRate, outRate);
  28. assert(error == RESAMPLER_ERR_SUCCESS);
  29. }
  30. /** `in` and `out` are interlaced with the number of channels */
  31. void process(const Frame<CHANNELS> *in, int *inFrames, Frame<CHANNELS> *out, int *outFrames) {
  32. if (bypass) {
  33. int len = std::min(*inFrames, *outFrames);
  34. memcpy(out, in, len * sizeof(Frame<CHANNELS>));
  35. *inFrames = len;
  36. *outFrames = len;
  37. return;
  38. }
  39. speex_resampler_process_interleaved_float(state, (const float*)in, (unsigned int*)inFrames, (float*)out, (unsigned int*)outFrames);
  40. }
  41. void reset() {
  42. int error = speex_resampler_reset_mem(state);
  43. assert(error == RESAMPLER_ERR_SUCCESS);
  44. }
  45. };
  46. } // namespace rack