]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_aiir.c
avfilter/af_aiir: implement parallel processing
[ffmpeg] / libavfilter / af_aiir.c
1 /*
2  * Copyright (c) 2018 Paul B Mahol
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include <float.h>
22
23 #include "libavutil/avassert.h"
24 #include "libavutil/avstring.h"
25 #include "libavutil/intreadwrite.h"
26 #include "libavutil/opt.h"
27 #include "libavutil/xga_font_data.h"
28 #include "audio.h"
29 #include "avfilter.h"
30 #include "internal.h"
31
32 typedef struct ThreadData {
33     AVFrame *in, *out;
34 } ThreadData;
35
36 typedef struct Pair {
37     int a, b;
38 } Pair;
39
40 typedef struct BiquadContext {
41     double a[3];
42     double b[3];
43     double i1, i2;
44     double o1, o2;
45 } BiquadContext;
46
47 typedef struct IIRChannel {
48     int nb_ab[2];
49     double *ab[2];
50     double g;
51     double *cache[2];
52     double fir;
53     BiquadContext *biquads;
54     int clippings;
55 } IIRChannel;
56
57 typedef struct AudioIIRContext {
58     const AVClass *class;
59     char *a_str, *b_str, *g_str;
60     double dry_gain, wet_gain;
61     double mix;
62     int normalize;
63     int format;
64     int process;
65     int precision;
66     int response;
67     int w, h;
68     int ir_channel;
69     AVRational rate;
70
71     AVFrame *video;
72
73     IIRChannel *iir;
74     int channels;
75     enum AVSampleFormat sample_format;
76
77     int (*iir_channel)(AVFilterContext *ctx, void *arg, int ch, int nb_jobs);
78 } AudioIIRContext;
79
80 static int query_formats(AVFilterContext *ctx)
81 {
82     AudioIIRContext *s = ctx->priv;
83     AVFilterFormats *formats;
84     AVFilterChannelLayouts *layouts;
85     enum AVSampleFormat sample_fmts[] = {
86         AV_SAMPLE_FMT_DBLP,
87         AV_SAMPLE_FMT_NONE
88     };
89     static const enum AVPixelFormat pix_fmts[] = {
90         AV_PIX_FMT_RGB0,
91         AV_PIX_FMT_NONE
92     };
93     int ret;
94
95     if (s->response) {
96         AVFilterLink *videolink = ctx->outputs[1];
97
98         formats = ff_make_format_list(pix_fmts);
99         if ((ret = ff_formats_ref(formats, &videolink->incfg.formats)) < 0)
100             return ret;
101     }
102
103     layouts = ff_all_channel_counts();
104     if (!layouts)
105         return AVERROR(ENOMEM);
106     ret = ff_set_common_channel_layouts(ctx, layouts);
107     if (ret < 0)
108         return ret;
109
110     sample_fmts[0] = s->sample_format;
111     formats = ff_make_format_list(sample_fmts);
112     if (!formats)
113         return AVERROR(ENOMEM);
114     ret = ff_set_common_formats(ctx, formats);
115     if (ret < 0)
116         return ret;
117
118     formats = ff_all_samplerates();
119     if (!formats)
120         return AVERROR(ENOMEM);
121     return ff_set_common_samplerates(ctx, formats);
122 }
123
124 #define IIR_CH(name, type, min, max, need_clipping)                     \
125 static int iir_ch_## name(AVFilterContext *ctx, void *arg, int ch, int nb_jobs)  \
126 {                                                                       \
127     AudioIIRContext *s = ctx->priv;                                     \
128     const double ig = s->dry_gain;                                      \
129     const double og = s->wet_gain;                                      \
130     const double mix = s->mix;                                          \
131     ThreadData *td = arg;                                               \
132     AVFrame *in = td->in, *out = td->out;                               \
133     const type *src = (const type *)in->extended_data[ch];              \
134     double *oc = (double *)s->iir[ch].cache[0];                         \
135     double *ic = (double *)s->iir[ch].cache[1];                         \
136     const int nb_a = s->iir[ch].nb_ab[0];                               \
137     const int nb_b = s->iir[ch].nb_ab[1];                               \
138     const double *a = s->iir[ch].ab[0];                                 \
139     const double *b = s->iir[ch].ab[1];                                 \
140     const double g = s->iir[ch].g;                                      \
141     int *clippings = &s->iir[ch].clippings;                             \
142     type *dst = (type *)out->extended_data[ch];                         \
143     int n;                                                              \
144                                                                         \
145     for (n = 0; n < in->nb_samples; n++) {                              \
146         double sample = 0.;                                             \
147         int x;                                                          \
148                                                                         \
149         memmove(&ic[1], &ic[0], (nb_b - 1) * sizeof(*ic));              \
150         memmove(&oc[1], &oc[0], (nb_a - 1) * sizeof(*oc));              \
151         ic[0] = src[n] * ig;                                            \
152         for (x = 0; x < nb_b; x++)                                      \
153             sample += b[x] * ic[x];                                     \
154                                                                         \
155         for (x = 1; x < nb_a; x++)                                      \
156             sample -= a[x] * oc[x];                                     \
157                                                                         \
158         oc[0] = sample;                                                 \
159         sample *= og * g;                                               \
160         sample = sample * mix + ic[0] * (1. - mix);                     \
161         if (need_clipping && sample < min) {                            \
162             (*clippings)++;                                             \
163             dst[n] = min;                                               \
164         } else if (need_clipping && sample > max) {                     \
165             (*clippings)++;                                             \
166             dst[n] = max;                                               \
167         } else {                                                        \
168             dst[n] = sample;                                            \
169         }                                                               \
170     }                                                                   \
171                                                                         \
172     return 0;                                                           \
173 }
174
175 IIR_CH(s16p, int16_t, INT16_MIN, INT16_MAX, 1)
176 IIR_CH(s32p, int32_t, INT32_MIN, INT32_MAX, 1)
177 IIR_CH(fltp, float,         -1.,        1., 0)
178 IIR_CH(dblp, double,        -1.,        1., 0)
179
180 #define SERIAL_IIR_CH(name, type, min, max, need_clipping)                  \
181 static int iir_ch_serial_## name(AVFilterContext *ctx, void *arg, int ch, int nb_jobs)  \
182 {                                                                       \
183     AudioIIRContext *s = ctx->priv;                                     \
184     const double ig = s->dry_gain;                                      \
185     const double og = s->wet_gain;                                      \
186     const double mix = s->mix;                                          \
187     const double imix = 1. - mix;                                       \
188     ThreadData *td = arg;                                               \
189     AVFrame *in = td->in, *out = td->out;                               \
190     const type *src = (const type *)in->extended_data[ch];              \
191     type *dst = (type *)out->extended_data[ch];                         \
192     IIRChannel *iir = &s->iir[ch];                                      \
193     const double g = iir->g;                                            \
194     int *clippings = &iir->clippings;                                   \
195     int nb_biquads = (FFMAX(iir->nb_ab[0], iir->nb_ab[1]) + 1) / 2;     \
196     int n, i;                                                           \
197                                                                         \
198     for (i = 0; i < nb_biquads; i++) {                                  \
199         const double a1 = -iir->biquads[i].a[1];                        \
200         const double a2 = -iir->biquads[i].a[2];                        \
201         const double b0 = iir->biquads[i].b[0];                         \
202         const double b1 = iir->biquads[i].b[1];                         \
203         const double b2 = iir->biquads[i].b[2];                         \
204         double i1 = iir->biquads[i].i1;                                 \
205         double i2 = iir->biquads[i].i2;                                 \
206         double o1 = iir->biquads[i].o1;                                 \
207         double o2 = iir->biquads[i].o2;                                 \
208                                                                         \
209         for (n = 0; n < in->nb_samples; n++) {                          \
210             double i0 = ig * (i ? dst[n] : src[n]);                     \
211             double o0 = i0 * b0 + i1 * b1 + i2 * b2 + o1 * a1 + o2 * a2; \
212                                                                         \
213             i2 = i1;                                                    \
214             i1 = i0;                                                    \
215             o2 = o1;                                                    \
216             o1 = o0;                                                    \
217             o0 *= og * g;                                               \
218                                                                         \
219             o0 = o0 * mix + imix * i0;                                  \
220             if (need_clipping && o0 < min) {                            \
221                 (*clippings)++;                                         \
222                 dst[n] = min;                                           \
223             } else if (need_clipping && o0 > max) {                     \
224                 (*clippings)++;                                         \
225                 dst[n] = max;                                           \
226             } else {                                                    \
227                 dst[n] = o0;                                            \
228             }                                                           \
229         }                                                               \
230         iir->biquads[i].i1 = i1;                                        \
231         iir->biquads[i].i2 = i2;                                        \
232         iir->biquads[i].o1 = o1;                                        \
233         iir->biquads[i].o2 = o2;                                        \
234     }                                                                   \
235                                                                         \
236     return 0;                                                           \
237 }
238
239 SERIAL_IIR_CH(s16p, int16_t, INT16_MIN, INT16_MAX, 1)
240 SERIAL_IIR_CH(s32p, int32_t, INT32_MIN, INT32_MAX, 1)
241 SERIAL_IIR_CH(fltp, float,         -1.,        1., 0)
242 SERIAL_IIR_CH(dblp, double,        -1.,        1., 0)
243
244 #define PARALLEL_IIR_CH(name, type, min, max, need_clipping)            \
245 static int iir_ch_parallel_## name(AVFilterContext *ctx, void *arg,     \
246                                    int ch, int nb_jobs)                 \
247 {                                                                       \
248     AudioIIRContext *s = ctx->priv;                                     \
249     const double ig = s->dry_gain;                                      \
250     const double og = s->wet_gain;                                      \
251     const double mix = s->mix;                                          \
252     const double imix = 1. - mix;                                       \
253     ThreadData *td = arg;                                               \
254     AVFrame *in = td->in, *out = td->out;                               \
255     const type *src = (const type *)in->extended_data[ch];              \
256     type *dst = (type *)out->extended_data[ch];                         \
257     IIRChannel *iir = &s->iir[ch];                                      \
258     const double g = iir->g;                                            \
259     const double fir = iir->fir;                                        \
260     int *clippings = &iir->clippings;                                   \
261     int nb_biquads = (FFMAX(iir->nb_ab[0], iir->nb_ab[1]) + 1) / 2;     \
262     int n, i;                                                           \
263                                                                         \
264     for (i = 0; i < nb_biquads; i++) {                                  \
265         const double a1 = -iir->biquads[i].a[1];                        \
266         const double a2 = -iir->biquads[i].a[2];                        \
267         const double b1 = iir->biquads[i].b[1];                         \
268         const double b2 = iir->biquads[i].b[2];                         \
269         double i1 = iir->biquads[i].i1;                                 \
270         double i2 = iir->biquads[i].i2;                                 \
271         double o1 = iir->biquads[i].o1;                                 \
272         double o2 = iir->biquads[i].o2;                                 \
273                                                                         \
274         for (n = 0; n < in->nb_samples; n++) {                          \
275             double i0 = ig * src[n];                                    \
276             double o0 = i1 * b1 + i2 * b2 + o1 * a1 + o2 * a2;          \
277                                                                         \
278             i2 = i1;                                                    \
279             i1 = i0;                                                    \
280             o2 = o1;                                                    \
281             o1 = o0;                                                    \
282             o0 *= og * g;                                               \
283             o0 += dst[n];                                               \
284                                                                         \
285             if (need_clipping && o0 < min) {                            \
286                 (*clippings)++;                                         \
287                 dst[n] = min;                                           \
288             } else if (need_clipping && o0 > max) {                     \
289                 (*clippings)++;                                         \
290                 dst[n] = max;                                           \
291             } else {                                                    \
292                 dst[n] = o0;                                            \
293             }                                                           \
294         }                                                               \
295         iir->biquads[i].i1 = i1;                                        \
296         iir->biquads[i].i2 = i2;                                        \
297         iir->biquads[i].o1 = o1;                                        \
298         iir->biquads[i].o2 = o2;                                        \
299     }                                                                   \
300                                                                         \
301     for (n = 0; n < in->nb_samples; n++) {                              \
302         dst[n] += fir * src[n];                                         \
303         dst[n] = dst[n] * mix + imix * src[n];                          \
304     }                                                                   \
305                                                                         \
306     return 0;                                                           \
307 }
308
309 PARALLEL_IIR_CH(s16p, int16_t, INT16_MIN, INT16_MAX, 1)
310 PARALLEL_IIR_CH(s32p, int32_t, INT32_MIN, INT32_MAX, 1)
311 PARALLEL_IIR_CH(fltp, float,         -1.,        1., 0)
312 PARALLEL_IIR_CH(dblp, double,        -1.,        1., 0)
313
314 static void count_coefficients(char *item_str, int *nb_items)
315 {
316     char *p;
317
318     if (!item_str)
319         return;
320
321     *nb_items = 1;
322     for (p = item_str; *p && *p != '|'; p++) {
323         if (*p == ' ')
324             (*nb_items)++;
325     }
326 }
327
328 static int read_gains(AVFilterContext *ctx, char *item_str, int nb_items)
329 {
330     AudioIIRContext *s = ctx->priv;
331     char *p, *arg, *old_str, *prev_arg = NULL, *saveptr = NULL;
332     int i;
333
334     p = old_str = av_strdup(item_str);
335     if (!p)
336         return AVERROR(ENOMEM);
337     for (i = 0; i < nb_items; i++) {
338         if (!(arg = av_strtok(p, "|", &saveptr)))
339             arg = prev_arg;
340
341         if (!arg) {
342             av_freep(&old_str);
343             return AVERROR(EINVAL);
344         }
345
346         p = NULL;
347         if (sscanf(arg, "%lf", &s->iir[i].g) != 1) {
348             av_log(ctx, AV_LOG_ERROR, "Invalid gains supplied: %s\n", arg);
349             av_freep(&old_str);
350             return AVERROR(EINVAL);
351         }
352
353         prev_arg = arg;
354     }
355
356     av_freep(&old_str);
357
358     return 0;
359 }
360
361 static int read_tf_coefficients(AVFilterContext *ctx, char *item_str, int nb_items, double *dst)
362 {
363     char *p, *arg, *old_str, *saveptr = NULL;
364     int i;
365
366     p = old_str = av_strdup(item_str);
367     if (!p)
368         return AVERROR(ENOMEM);
369     for (i = 0; i < nb_items; i++) {
370         if (!(arg = av_strtok(p, " ", &saveptr)))
371             break;
372
373         p = NULL;
374         if (sscanf(arg, "%lf", &dst[i]) != 1) {
375             av_log(ctx, AV_LOG_ERROR, "Invalid coefficients supplied: %s\n", arg);
376             av_freep(&old_str);
377             return AVERROR(EINVAL);
378         }
379     }
380
381     av_freep(&old_str);
382
383     return 0;
384 }
385
386 static int read_zp_coefficients(AVFilterContext *ctx, char *item_str, int nb_items, double *dst, const char *format)
387 {
388     char *p, *arg, *old_str, *saveptr = NULL;
389     int i;
390
391     p = old_str = av_strdup(item_str);
392     if (!p)
393         return AVERROR(ENOMEM);
394     for (i = 0; i < nb_items; i++) {
395         if (!(arg = av_strtok(p, " ", &saveptr)))
396             break;
397
398         p = NULL;
399         if (sscanf(arg, format, &dst[i*2], &dst[i*2+1]) != 2) {
400             av_log(ctx, AV_LOG_ERROR, "Invalid coefficients supplied: %s\n", arg);
401             av_freep(&old_str);
402             return AVERROR(EINVAL);
403         }
404     }
405
406     av_freep(&old_str);
407
408     return 0;
409 }
410
411 static const char *format[] = { "%lf", "%lf %lfi", "%lf %lfr", "%lf %lfd", "%lf %lfi" };
412
413 static int read_channels(AVFilterContext *ctx, int channels, uint8_t *item_str, int ab)
414 {
415     AudioIIRContext *s = ctx->priv;
416     char *p, *arg, *old_str, *prev_arg = NULL, *saveptr = NULL;
417     int i, ret;
418
419     p = old_str = av_strdup(item_str);
420     if (!p)
421         return AVERROR(ENOMEM);
422     for (i = 0; i < channels; i++) {
423         IIRChannel *iir = &s->iir[i];
424
425         if (!(arg = av_strtok(p, "|", &saveptr)))
426             arg = prev_arg;
427
428         if (!arg) {
429             av_freep(&old_str);
430             return AVERROR(EINVAL);
431         }
432
433         count_coefficients(arg, &iir->nb_ab[ab]);
434
435         p = NULL;
436         iir->cache[ab] = av_calloc(iir->nb_ab[ab] + 1, sizeof(double));
437         iir->ab[ab] = av_calloc(iir->nb_ab[ab] * (!!s->format + 1), sizeof(double));
438         if (!iir->ab[ab] || !iir->cache[ab]) {
439             av_freep(&old_str);
440             return AVERROR(ENOMEM);
441         }
442
443         if (s->format) {
444             ret = read_zp_coefficients(ctx, arg, iir->nb_ab[ab], iir->ab[ab], format[s->format]);
445         } else {
446             ret = read_tf_coefficients(ctx, arg, iir->nb_ab[ab], iir->ab[ab]);
447         }
448         if (ret < 0) {
449             av_freep(&old_str);
450             return ret;
451         }
452         prev_arg = arg;
453     }
454
455     av_freep(&old_str);
456
457     return 0;
458 }
459
460 static void cmul(double re, double im, double re2, double im2, double *RE, double *IM)
461 {
462     *RE = re * re2 - im * im2;
463     *IM = re * im2 + re2 * im;
464 }
465
466 static int expand(AVFilterContext *ctx, double *pz, int n, double *coefs)
467 {
468     coefs[2 * n] = 1.0;
469
470     for (int i = 1; i <= n; i++) {
471         for (int j = n - i; j < n; j++) {
472             double re, im;
473
474             cmul(coefs[2 * (j + 1)], coefs[2 * (j + 1) + 1],
475                  pz[2 * (i - 1)], pz[2 * (i - 1) + 1], &re, &im);
476
477             coefs[2 * j]     -= re;
478             coefs[2 * j + 1] -= im;
479         }
480     }
481
482     for (int i = 0; i < n + 1; i++) {
483         if (fabs(coefs[2 * i + 1]) > FLT_EPSILON) {
484             av_log(ctx, AV_LOG_ERROR, "coefs: %f of z^%d is not real; poles/zeros are not complex conjugates.\n",
485                    coefs[2 * i + 1], i);
486             return AVERROR(EINVAL);
487         }
488     }
489
490     return 0;
491 }
492
493 static void normalize_coeffs(AVFilterContext *ctx, int ch)
494 {
495     AudioIIRContext *s = ctx->priv;
496     IIRChannel *iir = &s->iir[ch];
497     double sum_den = 0.;
498
499     if (!s->normalize)
500         return;
501
502     for (int i = 0; i < iir->nb_ab[1]; i++) {
503         sum_den += iir->ab[1][i];
504     }
505
506     if (sum_den > 1e-6) {
507         double factor, sum_num = 0.;
508
509         for (int i = 0; i < iir->nb_ab[0]; i++) {
510             sum_num += iir->ab[0][i];
511         }
512
513         factor = sum_num / sum_den;
514
515         for (int i = 0; i < iir->nb_ab[1]; i++) {
516             iir->ab[1][i] *= factor;
517         }
518     }
519 }
520
521 static int convert_zp2tf(AVFilterContext *ctx, int channels)
522 {
523     AudioIIRContext *s = ctx->priv;
524     int ch, i, j, ret = 0;
525
526     for (ch = 0; ch < channels; ch++) {
527         IIRChannel *iir = &s->iir[ch];
528         double *topc, *botc;
529
530         topc = av_calloc((iir->nb_ab[1] + 1) * 2, sizeof(*topc));
531         botc = av_calloc((iir->nb_ab[0] + 1) * 2, sizeof(*botc));
532         if (!topc || !botc) {
533             ret = AVERROR(ENOMEM);
534             goto fail;
535         }
536
537         ret = expand(ctx, iir->ab[0], iir->nb_ab[0], botc);
538         if (ret < 0) {
539             goto fail;
540         }
541
542         ret = expand(ctx, iir->ab[1], iir->nb_ab[1], topc);
543         if (ret < 0) {
544             goto fail;
545         }
546
547         for (j = 0, i = iir->nb_ab[1]; i >= 0; j++, i--) {
548             iir->ab[1][j] = topc[2 * i];
549         }
550         iir->nb_ab[1]++;
551
552         for (j = 0, i = iir->nb_ab[0]; i >= 0; j++, i--) {
553             iir->ab[0][j] = botc[2 * i];
554         }
555         iir->nb_ab[0]++;
556
557         normalize_coeffs(ctx, ch);
558
559 fail:
560         av_free(topc);
561         av_free(botc);
562         if (ret < 0)
563             break;
564     }
565
566     return ret;
567 }
568
569 static int decompose_zp2biquads(AVFilterContext *ctx, int channels)
570 {
571     AudioIIRContext *s = ctx->priv;
572     int ch, ret;
573
574     for (ch = 0; ch < channels; ch++) {
575         IIRChannel *iir = &s->iir[ch];
576         int nb_biquads = (FFMAX(iir->nb_ab[0], iir->nb_ab[1]) + 1) / 2;
577         int current_biquad = 0;
578
579         iir->biquads = av_calloc(nb_biquads, sizeof(BiquadContext));
580         if (!iir->biquads)
581             return AVERROR(ENOMEM);
582
583         while (nb_biquads--) {
584             Pair outmost_pole = { -1, -1 };
585             Pair nearest_zero = { -1, -1 };
586             double zeros[4] = { 0 };
587             double poles[4] = { 0 };
588             double b[6] = { 0 };
589             double a[6] = { 0 };
590             double min_distance = DBL_MAX;
591             double max_mag = 0;
592             double factor;
593             int i;
594
595             for (i = 0; i < iir->nb_ab[0]; i++) {
596                 double mag;
597
598                 if (isnan(iir->ab[0][2 * i]) || isnan(iir->ab[0][2 * i + 1]))
599                     continue;
600                 mag = hypot(iir->ab[0][2 * i], iir->ab[0][2 * i + 1]);
601
602                 if (mag > max_mag) {
603                     max_mag = mag;
604                     outmost_pole.a = i;
605                 }
606             }
607
608             for (i = 0; i < iir->nb_ab[0]; i++) {
609                 if (isnan(iir->ab[0][2 * i]) || isnan(iir->ab[0][2 * i + 1]))
610                     continue;
611
612                 if (iir->ab[0][2 * i    ] ==  iir->ab[0][2 * outmost_pole.a    ] &&
613                     iir->ab[0][2 * i + 1] == -iir->ab[0][2 * outmost_pole.a + 1]) {
614                     outmost_pole.b = i;
615                     break;
616                 }
617             }
618
619             av_log(ctx, AV_LOG_VERBOSE, "outmost_pole is %d.%d\n", outmost_pole.a, outmost_pole.b);
620
621             if (outmost_pole.a < 0 || outmost_pole.b < 0)
622                 return AVERROR(EINVAL);
623
624             for (i = 0; i < iir->nb_ab[1]; i++) {
625                 double distance;
626
627                 if (isnan(iir->ab[1][2 * i]) || isnan(iir->ab[1][2 * i + 1]))
628                     continue;
629                 distance = hypot(iir->ab[0][2 * outmost_pole.a    ] - iir->ab[1][2 * i    ],
630                                  iir->ab[0][2 * outmost_pole.a + 1] - iir->ab[1][2 * i + 1]);
631
632                 if (distance < min_distance) {
633                     min_distance = distance;
634                     nearest_zero.a = i;
635                 }
636             }
637
638             for (i = 0; i < iir->nb_ab[1]; i++) {
639                 if (isnan(iir->ab[1][2 * i]) || isnan(iir->ab[1][2 * i + 1]))
640                     continue;
641
642                 if (iir->ab[1][2 * i    ] ==  iir->ab[1][2 * nearest_zero.a    ] &&
643                     iir->ab[1][2 * i + 1] == -iir->ab[1][2 * nearest_zero.a + 1]) {
644                     nearest_zero.b = i;
645                     break;
646                 }
647             }
648
649             av_log(ctx, AV_LOG_VERBOSE, "nearest_zero is %d.%d\n", nearest_zero.a, nearest_zero.b);
650
651             if (nearest_zero.a < 0 || nearest_zero.b < 0)
652                 return AVERROR(EINVAL);
653
654             poles[0] = iir->ab[0][2 * outmost_pole.a    ];
655             poles[1] = iir->ab[0][2 * outmost_pole.a + 1];
656
657             zeros[0] = iir->ab[1][2 * nearest_zero.a    ];
658             zeros[1] = iir->ab[1][2 * nearest_zero.a + 1];
659
660             if (nearest_zero.a == nearest_zero.b && outmost_pole.a == outmost_pole.b) {
661                 zeros[2] = 0;
662                 zeros[3] = 0;
663
664                 poles[2] = 0;
665                 poles[3] = 0;
666             } else {
667                 poles[2] = iir->ab[0][2 * outmost_pole.b    ];
668                 poles[3] = iir->ab[0][2 * outmost_pole.b + 1];
669
670                 zeros[2] = iir->ab[1][2 * nearest_zero.b    ];
671                 zeros[3] = iir->ab[1][2 * nearest_zero.b + 1];
672             }
673
674             ret = expand(ctx, zeros, 2, b);
675             if (ret < 0)
676                 return ret;
677
678             ret = expand(ctx, poles, 2, a);
679             if (ret < 0)
680                 return ret;
681
682             iir->ab[0][2 * outmost_pole.a] = iir->ab[0][2 * outmost_pole.a + 1] = NAN;
683             iir->ab[0][2 * outmost_pole.b] = iir->ab[0][2 * outmost_pole.b + 1] = NAN;
684             iir->ab[1][2 * nearest_zero.a] = iir->ab[1][2 * nearest_zero.a + 1] = NAN;
685             iir->ab[1][2 * nearest_zero.b] = iir->ab[1][2 * nearest_zero.b + 1] = NAN;
686
687             iir->biquads[current_biquad].a[0] = 1.;
688             iir->biquads[current_biquad].a[1] = a[2] / a[4];
689             iir->biquads[current_biquad].a[2] = a[0] / a[4];
690             iir->biquads[current_biquad].b[0] = b[4] / a[4];
691             iir->biquads[current_biquad].b[1] = b[2] / a[4];
692             iir->biquads[current_biquad].b[2] = b[0] / a[4];
693
694             if (s->normalize &&
695                 fabs(iir->biquads[current_biquad].b[0] +
696                      iir->biquads[current_biquad].b[1] +
697                      iir->biquads[current_biquad].b[2]) > 1e-6) {
698                 factor = (iir->biquads[current_biquad].a[0] +
699                           iir->biquads[current_biquad].a[1] +
700                           iir->biquads[current_biquad].a[2]) /
701                          (iir->biquads[current_biquad].b[0] +
702                           iir->biquads[current_biquad].b[1] +
703                           iir->biquads[current_biquad].b[2]);
704
705                 av_log(ctx, AV_LOG_VERBOSE, "factor=%f\n", factor);
706
707                 iir->biquads[current_biquad].b[0] *= factor;
708                 iir->biquads[current_biquad].b[1] *= factor;
709                 iir->biquads[current_biquad].b[2] *= factor;
710             }
711
712             iir->biquads[current_biquad].b[0] *= (current_biquad ? 1.0 : iir->g);
713             iir->biquads[current_biquad].b[1] *= (current_biquad ? 1.0 : iir->g);
714             iir->biquads[current_biquad].b[2] *= (current_biquad ? 1.0 : iir->g);
715
716             av_log(ctx, AV_LOG_VERBOSE, "a=%f %f %f:b=%f %f %f\n",
717                    iir->biquads[current_biquad].a[0],
718                    iir->biquads[current_biquad].a[1],
719                    iir->biquads[current_biquad].a[2],
720                    iir->biquads[current_biquad].b[0],
721                    iir->biquads[current_biquad].b[1],
722                    iir->biquads[current_biquad].b[2]);
723
724             current_biquad++;
725         }
726     }
727
728     return 0;
729 }
730
731 static void biquad_process(double *x, double *y, int length,
732                            double b0, double b1, double b2,
733                            double a1, double a2)
734 {
735     double w1 = 0., w2 = 0.;
736
737     a1 = -a1;
738     a2 = -a2;
739
740     for (int n = 0; n < length; n++) {
741         double out, in = x[n];
742
743         y[n] = out = in * b0 + w1;
744         w1 = b1 * in + w2 + a1 * out;
745         w2 = b2 * in + a2 * out;
746     }
747 }
748
749 static void solve(double *matrix, double *vector, int n, double *y, double *x, double *lu)
750 {
751     double sum = 0.;
752
753     for (int i = 0; i < n; i++) {
754         for (int j = i; j < n; j++) {
755             sum = 0.;
756             for (int k = 0; k < i; k++)
757                 sum += lu[i * n + k] * lu[k * n + j];
758             lu[i * n + j] = matrix[j * n + i] - sum;
759         }
760         for (int j = i + 1; j < n; j++) {
761             sum = 0.;
762             for (int k = 0; k < i; k++)
763                 sum += lu[j * n + k] * lu[k * n + i];
764             lu[j * n + i] = (1. / lu[i * n + i]) * (matrix[i * n + j] - sum);
765         }
766     }
767
768     for (int i = 0; i < n; i++) {
769         sum = 0.;
770         for (int k = 0; k < i; k++)
771             sum += lu[i * n + k] * y[k];
772         y[i] = vector[i] - sum;
773     }
774
775     for (int i = n - 1; i >= 0; i--) {
776         sum = 0.;
777         for (int k = i + 1; k < n; k++)
778             sum += lu[i * n + k] * x[k];
779         x[i] = (1 / lu[i * n + i]) * (y[i] - sum);
780     }
781 }
782
783 static int convert_serial2parallel(AVFilterContext *ctx, int channels)
784 {
785     AudioIIRContext *s = ctx->priv;
786     int ret = 0;
787
788     for (int ch = 0; ch < channels; ch++) {
789         IIRChannel *iir = &s->iir[ch];
790         int nb_biquads = (FFMAX(iir->nb_ab[0], iir->nb_ab[1]) + 1) / 2;
791         int length = nb_biquads * 2 + 1;
792         double *impulse = av_calloc(length, sizeof(*impulse));
793         double *y = av_calloc(length, sizeof(*y));
794         double *resp = av_calloc(length, sizeof(*resp));
795         double *M = av_calloc((length - 1) * 2 * nb_biquads, sizeof(*M));
796         double *W = av_calloc((length - 1) * 2 * nb_biquads, sizeof(*W));
797
798         if (!impulse || !y || !resp || !M) {
799             av_free(impulse);
800             av_free(y);
801             av_free(resp);
802             av_free(M);
803             av_free(W);
804             return AVERROR(ENOMEM);
805         }
806
807         impulse[0] = 1.;
808
809         for (int n = 0; n < nb_biquads; n++) {
810             BiquadContext *biquad = &iir->biquads[n];
811
812             biquad_process(n ? y : impulse, y, length,
813                            biquad->b[0], biquad->b[1], biquad->b[2],
814                            biquad->a[1], biquad->a[2]);
815         }
816
817         for (int n = 0; n < nb_biquads; n++) {
818             BiquadContext *biquad = &iir->biquads[n];
819
820             biquad_process(impulse, resp, length - 1,
821                            1., 0., 0., biquad->a[1], biquad->a[2]);
822
823             memcpy(M + n * 2 * (length - 1), resp, sizeof(*resp) * (length - 1));
824             memcpy(M + n * 2 * (length - 1) + length, resp, sizeof(*resp) * (length - 2));
825             memset(resp, 0, length * sizeof(*resp));
826         }
827
828         solve(M, &y[1], length - 1, &impulse[1], resp, W);
829
830         iir->fir = y[0];
831
832         for (int n = 0; n < nb_biquads; n++) {
833             BiquadContext *biquad = &iir->biquads[n];
834
835             biquad->b[0] = 0.;
836             biquad->b[1] = resp[n * 2 + 0];
837             biquad->b[2] = resp[n * 2 + 1];
838         }
839
840         av_free(impulse);
841         av_free(y);
842         av_free(resp);
843         av_free(M);
844         av_free(W);
845
846         if (ret < 0)
847             return ret;
848     }
849
850     return 0;
851 }
852
853 static void convert_pr2zp(AVFilterContext *ctx, int channels)
854 {
855     AudioIIRContext *s = ctx->priv;
856     int ch;
857
858     for (ch = 0; ch < channels; ch++) {
859         IIRChannel *iir = &s->iir[ch];
860         int n;
861
862         for (n = 0; n < iir->nb_ab[0]; n++) {
863             double r = iir->ab[0][2*n];
864             double angle = iir->ab[0][2*n+1];
865
866             iir->ab[0][2*n]   = r * cos(angle);
867             iir->ab[0][2*n+1] = r * sin(angle);
868         }
869
870         for (n = 0; n < iir->nb_ab[1]; n++) {
871             double r = iir->ab[1][2*n];
872             double angle = iir->ab[1][2*n+1];
873
874             iir->ab[1][2*n]   = r * cos(angle);
875             iir->ab[1][2*n+1] = r * sin(angle);
876         }
877     }
878 }
879
880 static void convert_sp2zp(AVFilterContext *ctx, int channels)
881 {
882     AudioIIRContext *s = ctx->priv;
883     int ch;
884
885     for (ch = 0; ch < channels; ch++) {
886         IIRChannel *iir = &s->iir[ch];
887         int n;
888
889         for (n = 0; n < iir->nb_ab[0]; n++) {
890             double sr = iir->ab[0][2*n];
891             double si = iir->ab[0][2*n+1];
892             double snr = 1. + sr;
893             double sdr = 1. - sr;
894             double div = sdr * sdr + si * si;
895
896             iir->ab[0][2*n]   = (snr * sdr - si * si) / div;
897             iir->ab[0][2*n+1] = (sdr * si + snr * si) / div;
898         }
899
900         for (n = 0; n < iir->nb_ab[1]; n++) {
901             double sr = iir->ab[1][2*n];
902             double si = iir->ab[1][2*n+1];
903             double snr = 1. + sr;
904             double sdr = 1. - sr;
905             double div = sdr * sdr + si * si;
906
907             iir->ab[1][2*n]   = (snr * sdr - si * si) / div;
908             iir->ab[1][2*n+1] = (sdr * si + snr * si) / div;
909         }
910     }
911 }
912
913 static void convert_pd2zp(AVFilterContext *ctx, int channels)
914 {
915     AudioIIRContext *s = ctx->priv;
916     int ch;
917
918     for (ch = 0; ch < channels; ch++) {
919         IIRChannel *iir = &s->iir[ch];
920         int n;
921
922         for (n = 0; n < iir->nb_ab[0]; n++) {
923             double r = iir->ab[0][2*n];
924             double angle = M_PI*iir->ab[0][2*n+1]/180.;
925
926             iir->ab[0][2*n]   = r * cos(angle);
927             iir->ab[0][2*n+1] = r * sin(angle);
928         }
929
930         for (n = 0; n < iir->nb_ab[1]; n++) {
931             double r = iir->ab[1][2*n];
932             double angle = M_PI*iir->ab[1][2*n+1]/180.;
933
934             iir->ab[1][2*n]   = r * cos(angle);
935             iir->ab[1][2*n+1] = r * sin(angle);
936         }
937     }
938 }
939
940 static void check_stability(AVFilterContext *ctx, int channels)
941 {
942     AudioIIRContext *s = ctx->priv;
943     int ch;
944
945     for (ch = 0; ch < channels; ch++) {
946         IIRChannel *iir = &s->iir[ch];
947
948         for (int n = 0; n < iir->nb_ab[0]; n++) {
949             double pr = hypot(iir->ab[0][2*n], iir->ab[0][2*n+1]);
950
951             if (pr >= 1.) {
952                 av_log(ctx, AV_LOG_WARNING, "pole %d at channel %d is unstable\n", n, ch);
953                 break;
954             }
955         }
956     }
957 }
958
959 static void drawtext(AVFrame *pic, int x, int y, const char *txt, uint32_t color)
960 {
961     const uint8_t *font;
962     int font_height;
963     int i;
964
965     font = avpriv_cga_font, font_height = 8;
966
967     for (i = 0; txt[i]; i++) {
968         int char_y, mask;
969
970         uint8_t *p = pic->data[0] + y * pic->linesize[0] + (x + i * 8) * 4;
971         for (char_y = 0; char_y < font_height; char_y++) {
972             for (mask = 0x80; mask; mask >>= 1) {
973                 if (font[txt[i] * font_height + char_y] & mask)
974                     AV_WL32(p, color);
975                 p += 4;
976             }
977             p += pic->linesize[0] - 8 * 4;
978         }
979     }
980 }
981
982 static void draw_line(AVFrame *out, int x0, int y0, int x1, int y1, uint32_t color)
983 {
984     int dx = FFABS(x1-x0);
985     int dy = FFABS(y1-y0), sy = y0 < y1 ? 1 : -1;
986     int err = (dx>dy ? dx : -dy) / 2, e2;
987
988     for (;;) {
989         AV_WL32(out->data[0] + y0 * out->linesize[0] + x0 * 4, color);
990
991         if (x0 == x1 && y0 == y1)
992             break;
993
994         e2 = err;
995
996         if (e2 >-dx) {
997             err -= dy;
998             x0--;
999         }
1000
1001         if (e2 < dy) {
1002             err += dx;
1003             y0 += sy;
1004         }
1005     }
1006 }
1007
1008 static double distance(double x0, double x1, double y0, double y1)
1009 {
1010     return hypot(x0 - x1, y0 - y1);
1011 }
1012
1013 static void get_response(int channel, int format, double w,
1014                          const double *b, const double *a,
1015                          int nb_b, int nb_a, double *magnitude, double *phase)
1016 {
1017     double realz, realp;
1018     double imagz, imagp;
1019     double real, imag;
1020     double div;
1021
1022     if (format == 0) {
1023         realz = 0., realp = 0.;
1024         imagz = 0., imagp = 0.;
1025         for (int x = 0; x < nb_a; x++) {
1026             realz += cos(-x * w) * a[x];
1027             imagz += sin(-x * w) * a[x];
1028         }
1029
1030         for (int x = 0; x < nb_b; x++) {
1031             realp += cos(-x * w) * b[x];
1032             imagp += sin(-x * w) * b[x];
1033         }
1034
1035         div = realp * realp + imagp * imagp;
1036         real = (realz * realp + imagz * imagp) / div;
1037         imag = (imagz * realp - imagp * realz) / div;
1038
1039         *magnitude = hypot(real, imag);
1040         *phase = atan2(imag, real);
1041     } else {
1042         double p = 1., z = 1.;
1043         double acc = 0.;
1044
1045         for (int x = 0; x < nb_a; x++) {
1046             z *= distance(cos(w), a[2 * x], sin(w), a[2 * x + 1]);
1047             acc += atan2(sin(w) - a[2 * x + 1], cos(w) - a[2 * x]);
1048         }
1049
1050         for (int x = 0; x < nb_b; x++) {
1051             p *= distance(cos(w), b[2 * x], sin(w), b[2 * x + 1]);
1052             acc -= atan2(sin(w) - b[2 * x + 1], cos(w) - b[2 * x]);
1053         }
1054
1055         *magnitude = z / p;
1056         *phase = acc;
1057     }
1058 }
1059
1060 static void draw_response(AVFilterContext *ctx, AVFrame *out, int sample_rate)
1061 {
1062     AudioIIRContext *s = ctx->priv;
1063     double *mag, *phase, *temp, *delay, min = DBL_MAX, max = -DBL_MAX;
1064     double min_delay = DBL_MAX, max_delay = -DBL_MAX, min_phase, max_phase;
1065     int prev_ymag = -1, prev_yphase = -1, prev_ydelay = -1;
1066     char text[32];
1067     int ch, i;
1068
1069     memset(out->data[0], 0, s->h * out->linesize[0]);
1070
1071     phase = av_malloc_array(s->w, sizeof(*phase));
1072     temp = av_malloc_array(s->w, sizeof(*temp));
1073     mag = av_malloc_array(s->w, sizeof(*mag));
1074     delay = av_malloc_array(s->w, sizeof(*delay));
1075     if (!mag || !phase || !delay || !temp)
1076         goto end;
1077
1078     ch = av_clip(s->ir_channel, 0, s->channels - 1);
1079     for (i = 0; i < s->w; i++) {
1080         const double *b = s->iir[ch].ab[0];
1081         const double *a = s->iir[ch].ab[1];
1082         const int nb_b = s->iir[ch].nb_ab[0];
1083         const int nb_a = s->iir[ch].nb_ab[1];
1084         double w = i * M_PI / (s->w - 1);
1085         double m, p;
1086
1087         get_response(ch, s->format, w, b, a, nb_b, nb_a, &m, &p);
1088
1089         mag[i] = s->iir[ch].g * m;
1090         phase[i] = p;
1091         min = fmin(min, mag[i]);
1092         max = fmax(max, mag[i]);
1093     }
1094
1095     temp[0] = 0.;
1096     for (i = 0; i < s->w - 1; i++) {
1097         double d = phase[i] - phase[i + 1];
1098         temp[i + 1] = ceil(fabs(d) / (2. * M_PI)) * 2. * M_PI * ((d > M_PI) - (d < -M_PI));
1099     }
1100
1101     min_phase = phase[0];
1102     max_phase = phase[0];
1103     for (i = 1; i < s->w; i++) {
1104         temp[i] += temp[i - 1];
1105         phase[i] += temp[i];
1106         min_phase = fmin(min_phase, phase[i]);
1107         max_phase = fmax(max_phase, phase[i]);
1108     }
1109
1110     for (i = 0; i < s->w - 1; i++) {
1111         double div = s->w / (double)sample_rate;
1112
1113         delay[i + 1] = -(phase[i] - phase[i + 1]) / div;
1114         min_delay = fmin(min_delay, delay[i + 1]);
1115         max_delay = fmax(max_delay, delay[i + 1]);
1116     }
1117     delay[0] = delay[1];
1118
1119     for (i = 0; i < s->w; i++) {
1120         int ymag = mag[i] / max * (s->h - 1);
1121         int ydelay = (delay[i] - min_delay) / (max_delay - min_delay) * (s->h - 1);
1122         int yphase = (phase[i] - min_phase) / (max_phase - min_phase) * (s->h - 1);
1123
1124         ymag = s->h - 1 - av_clip(ymag, 0, s->h - 1);
1125         yphase = s->h - 1 - av_clip(yphase, 0, s->h - 1);
1126         ydelay = s->h - 1 - av_clip(ydelay, 0, s->h - 1);
1127
1128         if (prev_ymag < 0)
1129             prev_ymag = ymag;
1130         if (prev_yphase < 0)
1131             prev_yphase = yphase;
1132         if (prev_ydelay < 0)
1133             prev_ydelay = ydelay;
1134
1135         draw_line(out, i,   ymag, FFMAX(i - 1, 0),   prev_ymag, 0xFFFF00FF);
1136         draw_line(out, i, yphase, FFMAX(i - 1, 0), prev_yphase, 0xFF00FF00);
1137         draw_line(out, i, ydelay, FFMAX(i - 1, 0), prev_ydelay, 0xFF00FFFF);
1138
1139         prev_ymag   = ymag;
1140         prev_yphase = yphase;
1141         prev_ydelay = ydelay;
1142     }
1143
1144     if (s->w > 400 && s->h > 100) {
1145         drawtext(out, 2, 2, "Max Magnitude:", 0xDDDDDDDD);
1146         snprintf(text, sizeof(text), "%.2f", max);
1147         drawtext(out, 15 * 8 + 2, 2, text, 0xDDDDDDDD);
1148
1149         drawtext(out, 2, 12, "Min Magnitude:", 0xDDDDDDDD);
1150         snprintf(text, sizeof(text), "%.2f", min);
1151         drawtext(out, 15 * 8 + 2, 12, text, 0xDDDDDDDD);
1152
1153         drawtext(out, 2, 22, "Max Phase:", 0xDDDDDDDD);
1154         snprintf(text, sizeof(text), "%.2f", max_phase);
1155         drawtext(out, 15 * 8 + 2, 22, text, 0xDDDDDDDD);
1156
1157         drawtext(out, 2, 32, "Min Phase:", 0xDDDDDDDD);
1158         snprintf(text, sizeof(text), "%.2f", min_phase);
1159         drawtext(out, 15 * 8 + 2, 32, text, 0xDDDDDDDD);
1160
1161         drawtext(out, 2, 42, "Max Delay:", 0xDDDDDDDD);
1162         snprintf(text, sizeof(text), "%.2f", max_delay);
1163         drawtext(out, 11 * 8 + 2, 42, text, 0xDDDDDDDD);
1164
1165         drawtext(out, 2, 52, "Min Delay:", 0xDDDDDDDD);
1166         snprintf(text, sizeof(text), "%.2f", min_delay);
1167         drawtext(out, 11 * 8 + 2, 52, text, 0xDDDDDDDD);
1168     }
1169
1170 end:
1171     av_free(delay);
1172     av_free(temp);
1173     av_free(phase);
1174     av_free(mag);
1175 }
1176
1177 static int config_output(AVFilterLink *outlink)
1178 {
1179     AVFilterContext *ctx = outlink->src;
1180     AudioIIRContext *s = ctx->priv;
1181     AVFilterLink *inlink = ctx->inputs[0];
1182     int ch, ret, i;
1183
1184     s->channels = inlink->channels;
1185     s->iir = av_calloc(s->channels, sizeof(*s->iir));
1186     if (!s->iir)
1187         return AVERROR(ENOMEM);
1188
1189     ret = read_gains(ctx, s->g_str, inlink->channels);
1190     if (ret < 0)
1191         return ret;
1192
1193     ret = read_channels(ctx, inlink->channels, s->a_str, 0);
1194     if (ret < 0)
1195         return ret;
1196
1197     ret = read_channels(ctx, inlink->channels, s->b_str, 1);
1198     if (ret < 0)
1199         return ret;
1200
1201     if (s->format == 2) {
1202         convert_pr2zp(ctx, inlink->channels);
1203     } else if (s->format == 3) {
1204         convert_pd2zp(ctx, inlink->channels);
1205     } else if (s->format == 4) {
1206         convert_sp2zp(ctx, inlink->channels);
1207     }
1208     if (s->format > 0) {
1209         check_stability(ctx, inlink->channels);
1210     }
1211
1212     av_frame_free(&s->video);
1213     if (s->response) {
1214         s->video = ff_get_video_buffer(ctx->outputs[1], s->w, s->h);
1215         if (!s->video)
1216             return AVERROR(ENOMEM);
1217
1218         draw_response(ctx, s->video, inlink->sample_rate);
1219     }
1220
1221     if (s->format == 0)
1222         av_log(ctx, AV_LOG_WARNING, "tf coefficients format is not recommended for too high number of zeros/poles.\n");
1223
1224     if (s->format > 0 && s->process == 0) {
1225         av_log(ctx, AV_LOG_WARNING, "Direct processsing is not recommended for zp coefficients format.\n");
1226
1227         ret = convert_zp2tf(ctx, inlink->channels);
1228         if (ret < 0)
1229             return ret;
1230     } else if (s->format == 0 && s->process == 1) {
1231         av_log(ctx, AV_LOG_ERROR, "Serial processing is not implemented for transfer function.\n");
1232         return AVERROR_PATCHWELCOME;
1233     } else if (s->format == 0 && s->process == 2) {
1234         av_log(ctx, AV_LOG_ERROR, "Parallel processing is not implemented for transfer function.\n");
1235         return AVERROR_PATCHWELCOME;
1236     } else if (s->format > 0 && s->process == 1) {
1237         ret = decompose_zp2biquads(ctx, inlink->channels);
1238         if (ret < 0)
1239             return ret;
1240     } else if (s->format > 0 && s->process == 2) {
1241         ret = decompose_zp2biquads(ctx, inlink->channels);
1242         if (ret < 0)
1243             return ret;
1244         ret = convert_serial2parallel(ctx, inlink->channels);
1245         if (ret < 0)
1246             return ret;
1247     }
1248
1249     for (ch = 0; s->format == 0 && ch < inlink->channels; ch++) {
1250         IIRChannel *iir = &s->iir[ch];
1251
1252         for (i = 1; i < iir->nb_ab[0]; i++) {
1253             iir->ab[0][i] /= iir->ab[0][0];
1254         }
1255
1256         iir->ab[0][0] = 1.0;
1257         for (i = 0; i < iir->nb_ab[1]; i++) {
1258             iir->ab[1][i] *= iir->g;
1259         }
1260
1261         normalize_coeffs(ctx, ch);
1262     }
1263
1264     switch (inlink->format) {
1265     case AV_SAMPLE_FMT_DBLP: s->iir_channel = s->process == 2 ? iir_ch_parallel_dblp : s->process == 1 ? iir_ch_serial_dblp : iir_ch_dblp; break;
1266     case AV_SAMPLE_FMT_FLTP: s->iir_channel = s->process == 2 ? iir_ch_parallel_fltp : s->process == 1 ? iir_ch_serial_fltp : iir_ch_fltp; break;
1267     case AV_SAMPLE_FMT_S32P: s->iir_channel = s->process == 2 ? iir_ch_parallel_s32p : s->process == 1 ? iir_ch_serial_s32p : iir_ch_s32p; break;
1268     case AV_SAMPLE_FMT_S16P: s->iir_channel = s->process == 2 ? iir_ch_parallel_s16p : s->process == 1 ? iir_ch_serial_s16p : iir_ch_s16p; break;
1269     }
1270
1271     return 0;
1272 }
1273
1274 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
1275 {
1276     AVFilterContext *ctx = inlink->dst;
1277     AudioIIRContext *s = ctx->priv;
1278     AVFilterLink *outlink = ctx->outputs[0];
1279     ThreadData td;
1280     AVFrame *out;
1281     int ch, ret;
1282
1283     if (av_frame_is_writable(in) && s->process != 2) {
1284         out = in;
1285     } else {
1286         out = ff_get_audio_buffer(outlink, in->nb_samples);
1287         if (!out) {
1288             av_frame_free(&in);
1289             return AVERROR(ENOMEM);
1290         }
1291         av_frame_copy_props(out, in);
1292     }
1293
1294     td.in  = in;
1295     td.out = out;
1296     ctx->internal->execute(ctx, s->iir_channel, &td, NULL, outlink->channels);
1297
1298     for (ch = 0; ch < outlink->channels; ch++) {
1299         if (s->iir[ch].clippings > 0)
1300             av_log(ctx, AV_LOG_WARNING, "Channel %d clipping %d times. Please reduce gain.\n",
1301                    ch, s->iir[ch].clippings);
1302         s->iir[ch].clippings = 0;
1303     }
1304
1305     if (in != out)
1306         av_frame_free(&in);
1307
1308     if (s->response) {
1309         AVFilterLink *outlink = ctx->outputs[1];
1310         int64_t old_pts = s->video->pts;
1311         int64_t new_pts = av_rescale_q(out->pts, ctx->inputs[0]->time_base, outlink->time_base);
1312
1313         if (new_pts > old_pts) {
1314             AVFrame *clone;
1315
1316             s->video->pts = new_pts;
1317             clone = av_frame_clone(s->video);
1318             if (!clone)
1319                 return AVERROR(ENOMEM);
1320             ret = ff_filter_frame(outlink, clone);
1321             if (ret < 0)
1322                 return ret;
1323         }
1324     }
1325
1326     return ff_filter_frame(outlink, out);
1327 }
1328
1329 static int config_video(AVFilterLink *outlink)
1330 {
1331     AVFilterContext *ctx = outlink->src;
1332     AudioIIRContext *s = ctx->priv;
1333
1334     outlink->sample_aspect_ratio = (AVRational){1,1};
1335     outlink->w = s->w;
1336     outlink->h = s->h;
1337     outlink->frame_rate = s->rate;
1338     outlink->time_base = av_inv_q(outlink->frame_rate);
1339
1340     return 0;
1341 }
1342
1343 static av_cold int init(AVFilterContext *ctx)
1344 {
1345     AudioIIRContext *s = ctx->priv;
1346     AVFilterPad pad, vpad;
1347     int ret;
1348
1349     if (!s->a_str || !s->b_str || !s->g_str) {
1350         av_log(ctx, AV_LOG_ERROR, "Valid coefficients are mandatory.\n");
1351         return AVERROR(EINVAL);
1352     }
1353
1354     switch (s->precision) {
1355     case 0: s->sample_format = AV_SAMPLE_FMT_DBLP; break;
1356     case 1: s->sample_format = AV_SAMPLE_FMT_FLTP; break;
1357     case 2: s->sample_format = AV_SAMPLE_FMT_S32P; break;
1358     case 3: s->sample_format = AV_SAMPLE_FMT_S16P; break;
1359     default: return AVERROR_BUG;
1360     }
1361
1362     pad = (AVFilterPad){
1363         .name         = "default",
1364         .type         = AVMEDIA_TYPE_AUDIO,
1365         .config_props = config_output,
1366     };
1367
1368     ret = ff_insert_outpad(ctx, 0, &pad);
1369     if (ret < 0)
1370         return ret;
1371
1372     if (s->response) {
1373         vpad = (AVFilterPad){
1374             .name         = "filter_response",
1375             .type         = AVMEDIA_TYPE_VIDEO,
1376             .config_props = config_video,
1377         };
1378
1379         ret = ff_insert_outpad(ctx, 1, &vpad);
1380         if (ret < 0)
1381             return ret;
1382     }
1383
1384     return 0;
1385 }
1386
1387 static av_cold void uninit(AVFilterContext *ctx)
1388 {
1389     AudioIIRContext *s = ctx->priv;
1390     int ch;
1391
1392     if (s->iir) {
1393         for (ch = 0; ch < s->channels; ch++) {
1394             IIRChannel *iir = &s->iir[ch];
1395             av_freep(&iir->ab[0]);
1396             av_freep(&iir->ab[1]);
1397             av_freep(&iir->cache[0]);
1398             av_freep(&iir->cache[1]);
1399             av_freep(&iir->biquads);
1400         }
1401     }
1402     av_freep(&s->iir);
1403
1404     av_frame_free(&s->video);
1405 }
1406
1407 static const AVFilterPad inputs[] = {
1408     {
1409         .name         = "default",
1410         .type         = AVMEDIA_TYPE_AUDIO,
1411         .filter_frame = filter_frame,
1412     },
1413     { NULL }
1414 };
1415
1416 #define OFFSET(x) offsetof(AudioIIRContext, x)
1417 #define AF AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
1418 #define VF AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
1419
1420 static const AVOption aiir_options[] = {
1421     { "zeros", "set B/numerator/zeros coefficients", OFFSET(b_str),  AV_OPT_TYPE_STRING, {.str="1+0i 1-0i"}, 0, 0, AF },
1422     { "z", "set B/numerator/zeros coefficients",   OFFSET(b_str),    AV_OPT_TYPE_STRING, {.str="1+0i 1-0i"}, 0, 0, AF },
1423     { "poles", "set A/denominator/poles coefficients", OFFSET(a_str),AV_OPT_TYPE_STRING, {.str="1+0i 1-0i"}, 0, 0, AF },
1424     { "p", "set A/denominator/poles coefficients", OFFSET(a_str),    AV_OPT_TYPE_STRING, {.str="1+0i 1-0i"}, 0, 0, AF },
1425     { "gains", "set channels gains",               OFFSET(g_str),    AV_OPT_TYPE_STRING, {.str="1|1"}, 0, 0, AF },
1426     { "k", "set channels gains",                   OFFSET(g_str),    AV_OPT_TYPE_STRING, {.str="1|1"}, 0, 0, AF },
1427     { "dry", "set dry gain",                       OFFSET(dry_gain), AV_OPT_TYPE_DOUBLE, {.dbl=1},     0, 1, AF },
1428     { "wet", "set wet gain",                       OFFSET(wet_gain), AV_OPT_TYPE_DOUBLE, {.dbl=1},     0, 1, AF },
1429     { "format", "set coefficients format",         OFFSET(format),   AV_OPT_TYPE_INT,    {.i64=1},     0, 4, AF, "format" },
1430     { "f", "set coefficients format",              OFFSET(format),   AV_OPT_TYPE_INT,    {.i64=1},     0, 4, AF, "format" },
1431     { "tf", "digital transfer function",           0,                AV_OPT_TYPE_CONST,  {.i64=0},     0, 0, AF, "format" },
1432     { "zp", "Z-plane zeros/poles",                 0,                AV_OPT_TYPE_CONST,  {.i64=1},     0, 0, AF, "format" },
1433     { "pr", "Z-plane zeros/poles (polar radians)", 0,                AV_OPT_TYPE_CONST,  {.i64=2},     0, 0, AF, "format" },
1434     { "pd", "Z-plane zeros/poles (polar degrees)", 0,                AV_OPT_TYPE_CONST,  {.i64=3},     0, 0, AF, "format" },
1435     { "sp", "S-plane zeros/poles",                 0,                AV_OPT_TYPE_CONST,  {.i64=4},     0, 0, AF, "format" },
1436     { "process", "set kind of processing",         OFFSET(process),  AV_OPT_TYPE_INT,    {.i64=1},     0, 2, AF, "process" },
1437     { "r", "set kind of processing",               OFFSET(process),  AV_OPT_TYPE_INT,    {.i64=1},     0, 2, AF, "process" },
1438     { "d", "direct",                               0,                AV_OPT_TYPE_CONST,  {.i64=0},     0, 0, AF, "process" },
1439     { "s", "serial",                               0,                AV_OPT_TYPE_CONST,  {.i64=1},     0, 0, AF, "process" },
1440     { "p", "parallel",                             0,                AV_OPT_TYPE_CONST,  {.i64=2},     0, 0, AF, "process" },
1441     { "precision", "set filtering precision",      OFFSET(precision),AV_OPT_TYPE_INT,    {.i64=0},     0, 3, AF, "precision" },
1442     { "e", "set precision",                        OFFSET(precision),AV_OPT_TYPE_INT,    {.i64=0},     0, 3, AF, "precision" },
1443     { "dbl", "double-precision floating-point",    0,                AV_OPT_TYPE_CONST,  {.i64=0},     0, 0, AF, "precision" },
1444     { "flt", "single-precision floating-point",    0,                AV_OPT_TYPE_CONST,  {.i64=1},     0, 0, AF, "precision" },
1445     { "i32", "32-bit integers",                    0,                AV_OPT_TYPE_CONST,  {.i64=2},     0, 0, AF, "precision" },
1446     { "i16", "16-bit integers",                    0,                AV_OPT_TYPE_CONST,  {.i64=3},     0, 0, AF, "precision" },
1447     { "normalize", "normalize coefficients",       OFFSET(normalize),AV_OPT_TYPE_BOOL,   {.i64=1},     0, 1, AF },
1448     { "n", "normalize coefficients",               OFFSET(normalize),AV_OPT_TYPE_BOOL,   {.i64=1},     0, 1, AF },
1449     { "mix", "set mix",                            OFFSET(mix),      AV_OPT_TYPE_DOUBLE, {.dbl=1},     0, 1, AF },
1450     { "response", "show IR frequency response",    OFFSET(response), AV_OPT_TYPE_BOOL,   {.i64=0},     0, 1, VF },
1451     { "channel", "set IR channel to display frequency response", OFFSET(ir_channel), AV_OPT_TYPE_INT, {.i64=0}, 0, 1024, VF },
1452     { "size",   "set video size",                  OFFSET(w),        AV_OPT_TYPE_IMAGE_SIZE, {.str = "hd720"}, 0, 0, VF },
1453     { "rate",   "set video rate",                  OFFSET(rate),     AV_OPT_TYPE_VIDEO_RATE, {.str = "25"}, 0, INT32_MAX, VF },
1454     { NULL },
1455 };
1456
1457 AVFILTER_DEFINE_CLASS(aiir);
1458
1459 AVFilter ff_af_aiir = {
1460     .name          = "aiir",
1461     .description   = NULL_IF_CONFIG_SMALL("Apply Infinite Impulse Response filter with supplied coefficients."),
1462     .priv_size     = sizeof(AudioIIRContext),
1463     .priv_class    = &aiir_class,
1464     .init          = init,
1465     .uninit        = uninit,
1466     .query_formats = query_formats,
1467     .inputs        = inputs,
1468     .flags         = AVFILTER_FLAG_DYNAMIC_OUTPUTS |
1469                      AVFILTER_FLAG_SLICE_THREADS,
1470 };