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