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.

filter.hpp 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. dy/dt = x * lambda
  72. */
  73. struct ExponentialFilter {
  74. float out = 0.f;
  75. float lambda = 1.f;
  76. float process(float in) {
  77. float y = out + (in - out) * lambda;
  78. // If no change was detected, assume float granularity is too small and snap output to input
  79. if (out == y)
  80. out = in;
  81. else
  82. out = y;
  83. return out;
  84. }
  85. };
  86. } // namespace dsp
  87. } // namespace rack