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.

86 lines
1.4KB

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