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.

100 lines
2.3KB

  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 *st = NULL;
  10. int channels = CHANNELS;
  11. int quality = SPEEX_RESAMPLER_QUALITY_DEFAULT;
  12. int inRate = 44100;
  13. int outRate = 44100;
  14. SampleRateConverter() {
  15. refreshState();
  16. }
  17. ~SampleRateConverter() {
  18. if (st) {
  19. speex_resampler_destroy(st);
  20. }
  21. }
  22. /** Sets the number of channels to actually process. This can be at most CHANNELS. */
  23. void setChannels(int channels) {
  24. assert(channels <= CHANNELS);
  25. if (channels == this->channels)
  26. return;
  27. this->channels = channels;
  28. refreshState();
  29. }
  30. /** From 0 (worst, fastest) to 10 (best, slowest) */
  31. void setQuality(int quality) {
  32. if (quality == this->quality)
  33. return;
  34. this->quality = quality;
  35. refreshState();
  36. }
  37. void setRates(int inRate, int outRate) {
  38. if (inRate == this->inRate && outRate == this->outRate)
  39. return;
  40. this->inRate = inRate;
  41. this->outRate = outRate;
  42. refreshState();
  43. }
  44. void refreshState() {
  45. if (st) {
  46. speex_resampler_destroy(st);
  47. st = NULL;
  48. }
  49. if (channels > 0 && inRate != outRate) {
  50. int err;
  51. st = speex_resampler_init(channels, inRate, outRate, quality, &err);
  52. assert(st);
  53. assert(err == RESAMPLER_ERR_SUCCESS);
  54. speex_resampler_set_input_stride(st, CHANNELS);
  55. speex_resampler_set_output_stride(st, CHANNELS);
  56. }
  57. }
  58. /** `in` and `out` are interlaced with the number of channels */
  59. void process(const Frame<CHANNELS> *in, int *inFrames, Frame<CHANNELS> *out, int *outFrames) {
  60. assert(in);
  61. assert(inFrames);
  62. assert(out);
  63. assert(outFrames);
  64. if (st) {
  65. // Resample each channel at a time
  66. spx_uint32_t inLen;
  67. spx_uint32_t outLen;
  68. for (int i = 0; i < channels; i++) {
  69. inLen = *inFrames;
  70. outLen = *outFrames;
  71. int err = speex_resampler_process_float(st, i, ((const float*) in) + i, &inLen, ((float*) out) + i, &outLen);
  72. assert(err == RESAMPLER_ERR_SUCCESS);
  73. }
  74. *inFrames = inLen;
  75. *outFrames = outLen;
  76. }
  77. else {
  78. // Simply copy the buffer without conversion
  79. int frames = min(*inFrames, *outFrames);
  80. memcpy(out, in, frames * sizeof(Frame<CHANNELS>));
  81. *inFrames = frames;
  82. *outFrames = frames;
  83. }
  84. }
  85. };
  86. } // namespace rack