1/*
2 * IIR filter
3 * Copyright (c) 2008 Konstantin Shishkov
4 *
5 * This file is part of Libav.
6 *
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22/**
23 * @file
24 * different IIR filters implementation
25 */
26
27#include "iirfilter.h"
28#include <math.h>
29
30/**
31 * IIR filter global parameters
32 */
33typedef struct FFIIRFilterCoeffs{
34    int   order;
35    float gain;
36    int   *cx;
37    float *cy;
38}FFIIRFilterCoeffs;
39
40/**
41 * IIR filter state
42 */
43typedef struct FFIIRFilterState{
44    float x[1];
45}FFIIRFilterState;
46
47/// maximum supported filter order
48#define MAXORDER 30
49
50static int butterworth_init_coeffs(void *avc, struct FFIIRFilterCoeffs *c,
51                                   enum IIRFilterMode filt_mode,
52                                   int order, float cutoff_ratio,
53                                   float stopband)
54{
55    int i, j;
56    double wa;
57    double p[MAXORDER + 1][2];
58
59    if (filt_mode != FF_FILTER_MODE_LOWPASS) {
60        av_log(avc, AV_LOG_ERROR, "Butterworth filter currently only supports "
61               "low-pass filter mode\n");
62        return -1;
63    }
64    if (order & 1) {
65        av_log(avc, AV_LOG_ERROR, "Butterworth filter currently only supports "
66               "even filter orders\n");
67        return -1;
68    }
69
70    wa = 2 * tan(M_PI * 0.5 * cutoff_ratio);
71
72    c->cx[0] = 1;
73    for(i = 1; i < (order >> 1) + 1; i++)
74        c->cx[i] = c->cx[i - 1] * (order - i + 1LL) / i;
75
76    p[0][0] = 1.0;
77    p[0][1] = 0.0;
78    for(i = 1; i <= order; i++)
79        p[i][0] = p[i][1] = 0.0;
80    for(i = 0; i < order; i++){
81        double zp[2];
82        double th = (i + (order >> 1) + 0.5) * M_PI / order;
83        double a_re, a_im, c_re, c_im;
84        zp[0] = cos(th) * wa;
85        zp[1] = sin(th) * wa;
86        a_re = zp[0] + 2.0;
87        c_re = zp[0] - 2.0;
88        a_im =
89        c_im = zp[1];
90        zp[0] = (a_re * c_re + a_im * c_im) / (c_re * c_re + c_im * c_im);
91        zp[1] = (a_im * c_re - a_re * c_im) / (c_re * c_re + c_im * c_im);
92
93        for(j = order; j >= 1; j--)
94        {
95            a_re = p[j][0];
96            a_im = p[j][1];
97            p[j][0] = a_re*zp[0] - a_im*zp[1] + p[j-1][0];
98            p[j][1] = a_re*zp[1] + a_im*zp[0] + p[j-1][1];
99        }
100        a_re    = p[0][0]*zp[0] - p[0][1]*zp[1];
101        p[0][1] = p[0][0]*zp[1] + p[0][1]*zp[0];
102        p[0][0] = a_re;
103    }
104    c->gain = p[order][0];
105    for(i = 0; i < order; i++){
106        c->gain += p[i][0];
107        c->cy[i] = (-p[i][0] * p[order][0] + -p[i][1] * p[order][1]) /
108                   (p[order][0] * p[order][0] + p[order][1] * p[order][1]);
109    }
110    c->gain /= 1 << order;
111
112    return 0;
113}
114
115static int biquad_init_coeffs(void *avc, struct FFIIRFilterCoeffs *c,
116                              enum IIRFilterMode filt_mode, int order,
117                              float cutoff_ratio, float stopband)
118{
119    double cos_w0, sin_w0;
120    double a0, x0, x1;
121
122    if (filt_mode != FF_FILTER_MODE_HIGHPASS &&
123        filt_mode != FF_FILTER_MODE_LOWPASS) {
124        av_log(avc, AV_LOG_ERROR, "Biquad filter currently only supports "
125               "high-pass and low-pass filter modes\n");
126        return -1;
127    }
128    if (order != 2) {
129        av_log(avc, AV_LOG_ERROR, "Biquad filter must have order of 2\n");
130        return -1;
131    }
132
133    cos_w0 = cos(M_PI * cutoff_ratio);
134    sin_w0 = sin(M_PI * cutoff_ratio);
135
136    a0 = 1.0 + (sin_w0 / 2.0);
137
138    if (filt_mode == FF_FILTER_MODE_HIGHPASS) {
139        c->gain  =  ((1.0 + cos_w0) / 2.0)  / a0;
140        x0       =  ((1.0 + cos_w0) / 2.0)  / a0;
141        x1       = (-(1.0 + cos_w0))        / a0;
142    } else { // FF_FILTER_MODE_LOWPASS
143        c->gain  =  ((1.0 - cos_w0) / 2.0)  / a0;
144        x0       =  ((1.0 - cos_w0) / 2.0)  / a0;
145        x1       =   (1.0 - cos_w0)         / a0;
146    }
147    c->cy[0] = (-1.0 + (sin_w0 / 2.0)) / a0;
148    c->cy[1] =  (2.0 *  cos_w0)        / a0;
149
150    // divide by gain to make the x coeffs integers.
151    // during filtering, the delay state will include the gain multiplication
152    c->cx[0] = lrintf(x0 / c->gain);
153    c->cx[1] = lrintf(x1 / c->gain);
154
155    return 0;
156}
157
158av_cold struct FFIIRFilterCoeffs* ff_iir_filter_init_coeffs(void *avc,
159                                                enum IIRFilterType filt_type,
160                                                enum IIRFilterMode filt_mode,
161                                                int order, float cutoff_ratio,
162                                                float stopband, float ripple)
163{
164    FFIIRFilterCoeffs *c;
165    int ret = 0;
166
167    if (order <= 0 || order > MAXORDER || cutoff_ratio >= 1.0)
168        return NULL;
169
170    FF_ALLOCZ_OR_GOTO(avc, c,     sizeof(FFIIRFilterCoeffs),
171                      init_fail);
172    FF_ALLOC_OR_GOTO (avc, c->cx, sizeof(c->cx[0]) * ((order >> 1) + 1),
173                      init_fail);
174    FF_ALLOC_OR_GOTO (avc, c->cy, sizeof(c->cy[0]) * order,
175                      init_fail);
176    c->order = order;
177
178    switch (filt_type) {
179    case FF_FILTER_TYPE_BUTTERWORTH:
180        ret = butterworth_init_coeffs(avc, c, filt_mode, order, cutoff_ratio,
181                                      stopband);
182        break;
183    case FF_FILTER_TYPE_BIQUAD:
184        ret = biquad_init_coeffs(avc, c, filt_mode, order, cutoff_ratio,
185                                 stopband);
186        break;
187    default:
188        av_log(avc, AV_LOG_ERROR, "filter type is not currently implemented\n");
189        goto init_fail;
190    }
191
192    if (!ret)
193        return c;
194
195init_fail:
196    ff_iir_filter_free_coeffs(c);
197    return NULL;
198}
199
200av_cold struct FFIIRFilterState* ff_iir_filter_init_state(int order)
201{
202    FFIIRFilterState* s = av_mallocz(sizeof(FFIIRFilterState) + sizeof(s->x[0]) * (order - 1));
203    return s;
204}
205
206#define CONV_S16(dest, source) dest = av_clip_int16(lrintf(source));
207
208#define CONV_FLT(dest, source) dest = source;
209
210#define FILTER_BW_O4_1(i0, i1, i2, i3, fmt)         \
211    in = *src0 * c->gain                            \
212         + c->cy[0]*s->x[i0] + c->cy[1]*s->x[i1]    \
213         + c->cy[2]*s->x[i2] + c->cy[3]*s->x[i3];   \
214    res =  (s->x[i0] + in      )*1                  \
215         + (s->x[i1] + s->x[i3])*4                  \
216         +  s->x[i2]            *6;                 \
217    CONV_##fmt(*dst0, res)                          \
218    s->x[i0] = in;                                  \
219    src0 += sstep;                                  \
220    dst0 += dstep;
221
222#define FILTER_BW_O4(type, fmt) {           \
223    int i;                                  \
224    const type *src0 = src;                 \
225    type       *dst0 = dst;                 \
226    for (i = 0; i < size; i += 4) {         \
227        float in, res;                      \
228        FILTER_BW_O4_1(0, 1, 2, 3, fmt);    \
229        FILTER_BW_O4_1(1, 2, 3, 0, fmt);    \
230        FILTER_BW_O4_1(2, 3, 0, 1, fmt);    \
231        FILTER_BW_O4_1(3, 0, 1, 2, fmt);    \
232    }                                       \
233}
234
235#define FILTER_DIRECT_FORM_II(type, fmt) {                                  \
236    int i;                                                                  \
237    const type *src0 = src;                                                 \
238    type       *dst0 = dst;                                                 \
239    for (i = 0; i < size; i++) {                                            \
240        int j;                                                              \
241        float in, res;                                                      \
242        in = *src0 * c->gain;                                               \
243        for(j = 0; j < c->order; j++)                                       \
244            in += c->cy[j] * s->x[j];                                       \
245        res = s->x[0] + in + s->x[c->order >> 1] * c->cx[c->order >> 1];    \
246        for(j = 1; j < c->order >> 1; j++)                                  \
247            res += (s->x[j] + s->x[c->order - j]) * c->cx[j];               \
248        for(j = 0; j < c->order - 1; j++)                                   \
249            s->x[j] = s->x[j + 1];                                          \
250        CONV_##fmt(*dst0, res)                                              \
251        s->x[c->order - 1] = in;                                            \
252        src0 += sstep;                                                      \
253        dst0 += dstep;                                                      \
254    }                                                                       \
255}
256
257#define FILTER_O2(type, fmt) {                                              \
258    int i;                                                                  \
259    const type *src0 = src;                                                 \
260    type       *dst0 = dst;                                                 \
261    for (i = 0; i < size; i++) {                                            \
262        float in = *src0   * c->gain  +                                     \
263                   s->x[0] * c->cy[0] +                                     \
264                   s->x[1] * c->cy[1];                                      \
265        CONV_##fmt(*dst0, s->x[0] + in + s->x[1] * c->cx[1])                \
266        s->x[0] = s->x[1];                                                  \
267        s->x[1] = in;                                                       \
268        src0 += sstep;                                                      \
269        dst0 += dstep;                                                      \
270    }                                                                       \
271}
272
273void ff_iir_filter(const struct FFIIRFilterCoeffs *c,
274                   struct FFIIRFilterState *s, int size,
275                   const int16_t *src, int sstep, int16_t *dst, int dstep)
276{
277    if (c->order == 2) {
278        FILTER_O2(int16_t, S16)
279    } else if (c->order == 4) {
280        FILTER_BW_O4(int16_t, S16)
281    } else {
282        FILTER_DIRECT_FORM_II(int16_t, S16)
283    }
284}
285
286void ff_iir_filter_flt(const struct FFIIRFilterCoeffs *c,
287                       struct FFIIRFilterState *s, int size,
288                       const float *src, int sstep, float *dst, int dstep)
289{
290    if (c->order == 2) {
291        FILTER_O2(float, FLT)
292    } else if (c->order == 4) {
293        FILTER_BW_O4(float, FLT)
294    } else {
295        FILTER_DIRECT_FORM_II(float, FLT)
296    }
297}
298
299av_cold void ff_iir_filter_free_state(struct FFIIRFilterState *state)
300{
301    av_free(state);
302}
303
304av_cold void ff_iir_filter_free_coeffs(struct FFIIRFilterCoeffs *coeffs)
305{
306    if(coeffs){
307        av_free(coeffs->cx);
308        av_free(coeffs->cy);
309    }
310    av_free(coeffs);
311}
312
313#ifdef TEST
314#undef printf
315#include <stdio.h>
316
317#define FILT_ORDER 4
318#define SIZE 1024
319int main(void)
320{
321    struct FFIIRFilterCoeffs *fcoeffs = NULL;
322    struct FFIIRFilterState  *fstate  = NULL;
323    float cutoff_coeff = 0.4;
324    int16_t x[SIZE], y[SIZE];
325    int i;
326
327    fcoeffs = ff_iir_filter_init_coeffs(NULL, FF_FILTER_TYPE_BUTTERWORTH,
328                                        FF_FILTER_MODE_LOWPASS, FILT_ORDER,
329                                        cutoff_coeff, 0.0, 0.0);
330    fstate  = ff_iir_filter_init_state(FILT_ORDER);
331
332    for (i = 0; i < SIZE; i++) {
333        x[i] = lrint(0.75 * INT16_MAX * sin(0.5*M_PI*i*i/SIZE));
334    }
335
336    ff_iir_filter(fcoeffs, fstate, SIZE, x, 1, y, 1);
337
338    for (i = 0; i < SIZE; i++)
339        printf("%6d %6d\n", x[i], y[i]);
340
341    ff_iir_filter_free_coeffs(fcoeffs);
342    ff_iir_filter_free_state(fstate);
343    return 0;
344}
345#endif /* TEST */
346