Advertisement
Guest User

Moog resonant IIR voltage-controlled highpass filter.

a guest
Jun 28th, 2017
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.16 KB | None | 0 0
  1. #include <stdint.h>
  2. #include <math.h>
  3.  
  4. typedef struct _filter_moog {                                                                                                                                            
  5.     float res_dB;
  6.     float f, q, p; /* filter coefficients */
  7.     float b0, b1, b2, b3, b4; /* filter state. TODO: make more sane. */
  8. } MoogFilterContext;
  9.  
  10. static inline int av_clip(int val,int min, int max)
  11. {
  12.     if (val > max) val = max;
  13.     if (val < min) val = min;
  14.     return val;
  15. }
  16.  
  17. void moog_filter_reset(MoogFilterContext *s)
  18. {                                                                                                                                                                        
  19.     s->b0 = s->b1 = s->b2 = s->b3 = s->b4 = 0;
  20. }
  21.  
  22. void moog_filter_init(MoogFilterContext *s, unsigned int freq, unsigned int samplerate, float res_dB)
  23. {
  24.     float res, fr, p, q;
  25.  
  26.     moog_filter_reset(s);
  27.  
  28.     freq = av_clip(freq, 75, samplerate>>1);
  29.     cutoff = 2.0f * (float)freq / (float)samplerate;
  30.     q = 1.0f - cutoff;
  31.     p = cutoff + 0.8f * cutoff * q;
  32.     s->f = p + p - 1.0f;
  33.     s->p = p;
  34.  
  35.     res = expf((float)M_LN10 * (res_dB - 96) * 0.05f);
  36.     s->q = res * (1.0f + 0.5f * q * (1.0f - q + 5.6f * q * q));
  37. }
  38.  
  39. static inline float do_filter_moog(MoogFilterContext *s, float in)
  40. {
  41.     float t1, t2, t3, tb0 = s->b0, tb1 = s->b1, tb2 = s->b2, tb3 = s->b3, tb4 = s->b4;
  42.     float f = s->f, p = s->p;
  43.     t3 = in - (s->q * tb4);
  44.     t1 = tb1;  tb1 = (tb0 + t3) * p - tb1 * f;
  45.     t2 = tb2;  tb2 = (tb1 + t1) * p - tb2 * f;
  46.     t1 = tb3;  tb3 = (tb2 + t2) * p - tb3 * f;
  47.     tb4 = (tb3 + t1) * p - tb4 * f;
  48.     tb0 = t3;
  49.     /* *lpf_out = tb4; */
  50.     s->b0 = tb0, s->b1 = tb1, s->b2 = tb2, s->b3 = tb3, s->b4 = tb4;
  51.     return (t3 - tb4); /* Highpass output */
  52. }
  53.  
  54. /* Mono for now, can just do stereo with a pair of MoogFilterContexts.
  55.  * First can be initialized with moog_init() and the second with memcpy()
  56.  */
  57. void moog_filter_hpf_process(MoogFilterContext *s, float *dst, const float *src, size_t nb_samples)
  58. {
  59.     size_t i;
  60.     for(i = 0; i < nb_samples; i++) {
  61.         dst[i] = do_filter_moog(s, src[i]);
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement