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.

88 lines
1.4KB

  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. /** Applies exponential smoothing to a signal with the ODE
  55. dy/dt = x * lambda
  56. */
  57. struct ExponentialFilter {
  58. float out = 0.f;
  59. float lambda = 1.f;
  60. float process(float in) {
  61. float y = out + (in - out) * lambda;
  62. // If no change was detected, assume float granularity is too small and snap output to input
  63. if (out == y)
  64. out = in;
  65. else
  66. out = y;
  67. return out;
  68. }
  69. };
  70. } // namespace dsp
  71. } // namespace rack