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.

113 lines
1.9KB

  1. #pragma once
  2. #include "dsp/common.hpp"
  3. namespace rack {
  4. namespace dsp {
  5. struct RCFilter {
  6. float c = 0.f;
  7. float xstate[1] = {};
  8. float ystate[1] = {};
  9. // `r` is the ratio between the cutoff frequency and sample rate, i.e. r = f_c / f_s
  10. void setCutoff(float r) {
  11. c = 2.f / r;
  12. }
  13. void process(float x) {
  14. float y = (x + xstate[0] - ystate[0] * (1 - c)) / (1 + c);
  15. xstate[0] = x;
  16. ystate[0] = y;
  17. }
  18. float lowpass() {
  19. return ystate[0];
  20. }
  21. float highpass() {
  22. return xstate[0] - ystate[0];
  23. }
  24. };
  25. struct PeakFilter {
  26. float state = 0.f;
  27. float c = 0.f;
  28. /** Rate is lambda / sampleRate */
  29. void setRate(float r) {
  30. c = 1.f - r;
  31. }
  32. void process(float x) {
  33. if (x > state)
  34. state = x;
  35. state *= c;
  36. }
  37. float peak() {
  38. return state;
  39. }
  40. };
  41. struct SlewLimiter {
  42. float rise = 1.f;
  43. float fall = 1.f;
  44. float out = 0.f;
  45. void setRiseFall(float rise, float fall) {
  46. this->rise = rise;
  47. this->fall = fall;
  48. }
  49. float process(float in) {
  50. out = math::clamp(in, out - fall, out + rise);
  51. return out;
  52. }
  53. };
  54. struct ExponentialSlewLimiter {
  55. float riseLambda = 1.f;
  56. float fallLambda = 1.f;
  57. float out = 0.f;
  58. float process(float in) {
  59. if (in > out) {
  60. float y = out + (in - out) * riseLambda;
  61. out = (out == y) ? in : y;
  62. }
  63. else if (in < out) {
  64. float y = out + (in - out) * fallLambda;
  65. out = (out == y) ? in : y;
  66. }
  67. return out;
  68. }
  69. };
  70. /** Applies exponential smoothing to a signal with the ODE
  71. \f$ \frac{dy}{dt} = x \lambda \f$.
  72. */
  73. struct ExponentialFilter {
  74. float out = 0.f;
  75. float lambda = 0.f;
  76. void reset() {
  77. out = 0.f;
  78. }
  79. float process(float deltaTime, float in) {
  80. float y = out + (in - out) * lambda * deltaTime;
  81. // If no change was detected, assume float granularity is too small and snap output to input
  82. if (out == y)
  83. out = in;
  84. else
  85. out = y;
  86. return out;
  87. }
  88. DEPRECATED float process(float in) {return process(1.f, in);}
  89. };
  90. } // namespace dsp
  91. } // namespace rack