2 * Copyright (c) 2018 Paul B Mahol
4 * This file is part of FFmpeg.
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.
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.
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
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"
32 typedef struct ThreadData {
40 typedef struct BiquadContext {
47 typedef struct IIRChannel {
52 BiquadContext *biquads;
56 typedef struct AudioIIRContext {
58 char *a_str, *b_str, *g_str;
59 double dry_gain, wet_gain;
73 enum AVSampleFormat sample_format;
75 int (*iir_channel)(AVFilterContext *ctx, void *arg, int ch, int nb_jobs);
78 static int query_formats(AVFilterContext *ctx)
80 AudioIIRContext *s = ctx->priv;
81 AVFilterFormats *formats;
82 AVFilterChannelLayouts *layouts;
83 enum AVSampleFormat sample_fmts[] = {
87 static const enum AVPixelFormat pix_fmts[] = {
94 AVFilterLink *videolink = ctx->outputs[1];
96 formats = ff_make_format_list(pix_fmts);
97 if ((ret = ff_formats_ref(formats, &videolink->in_formats)) < 0)
101 layouts = ff_all_channel_counts();
103 return AVERROR(ENOMEM);
104 ret = ff_set_common_channel_layouts(ctx, layouts);
108 sample_fmts[0] = s->sample_format;
109 formats = ff_make_format_list(sample_fmts);
111 return AVERROR(ENOMEM);
112 ret = ff_set_common_formats(ctx, formats);
116 formats = ff_all_samplerates();
118 return AVERROR(ENOMEM);
119 return ff_set_common_samplerates(ctx, formats);
122 #define IIR_CH(name, type, min, max, need_clipping) \
123 static int iir_ch_## name(AVFilterContext *ctx, void *arg, int ch, int nb_jobs) \
125 AudioIIRContext *s = ctx->priv; \
126 const double ig = s->dry_gain; \
127 const double og = s->wet_gain; \
128 const double mix = s->mix; \
129 ThreadData *td = arg; \
130 AVFrame *in = td->in, *out = td->out; \
131 const type *src = (const type *)in->extended_data[ch]; \
132 double *oc = (double *)s->iir[ch].cache[0]; \
133 double *ic = (double *)s->iir[ch].cache[1]; \
134 const int nb_a = s->iir[ch].nb_ab[0]; \
135 const int nb_b = s->iir[ch].nb_ab[1]; \
136 const double *a = s->iir[ch].ab[0]; \
137 const double *b = s->iir[ch].ab[1]; \
138 const double g = s->iir[ch].g; \
139 int *clippings = &s->iir[ch].clippings; \
140 type *dst = (type *)out->extended_data[ch]; \
143 for (n = 0; n < in->nb_samples; n++) { \
144 double sample = 0.; \
147 memmove(&ic[1], &ic[0], (nb_b - 1) * sizeof(*ic)); \
148 memmove(&oc[1], &oc[0], (nb_a - 1) * sizeof(*oc)); \
149 ic[0] = src[n] * ig; \
150 for (x = 0; x < nb_b; x++) \
151 sample += b[x] * ic[x]; \
153 for (x = 1; x < nb_a; x++) \
154 sample -= a[x] * oc[x]; \
158 sample = sample * mix + ic[0] * (1. - mix); \
159 if (need_clipping && sample < min) { \
162 } else if (need_clipping && sample > max) { \
173 IIR_CH(s16p, int16_t, INT16_MIN, INT16_MAX, 1)
174 IIR_CH(s32p, int32_t, INT32_MIN, INT32_MAX, 1)
175 IIR_CH(fltp, float, -1., 1., 0)
176 IIR_CH(dblp, double, -1., 1., 0)
178 #define SERIAL_IIR_CH(name, type, min, max, need_clipping) \
179 static int iir_ch_serial_## name(AVFilterContext *ctx, void *arg, int ch, int nb_jobs) \
181 AudioIIRContext *s = ctx->priv; \
182 const double ig = s->dry_gain; \
183 const double og = s->wet_gain; \
184 const double mix = s->mix; \
185 ThreadData *td = arg; \
186 AVFrame *in = td->in, *out = td->out; \
187 const type *src = (const type *)in->extended_data[ch]; \
188 type *dst = (type *)out->extended_data[ch]; \
189 IIRChannel *iir = &s->iir[ch]; \
190 const double g = iir->g; \
191 int *clippings = &iir->clippings; \
192 int nb_biquads = (FFMAX(iir->nb_ab[0], iir->nb_ab[1]) + 1) / 2; \
195 for (i = 0; i < nb_biquads; i++) { \
196 const double a1 = -iir->biquads[i].a[1]; \
197 const double a2 = -iir->biquads[i].a[2]; \
198 const double b0 = iir->biquads[i].b[0]; \
199 const double b1 = iir->biquads[i].b[1]; \
200 const double b2 = iir->biquads[i].b[2]; \
201 double i1 = iir->biquads[i].i1; \
202 double i2 = iir->biquads[i].i2; \
203 double o1 = iir->biquads[i].o1; \
204 double o2 = iir->biquads[i].o2; \
206 for (n = 0; n < in->nb_samples; n++) { \
207 double sample = ig * (i ? dst[n] : src[n]); \
208 double o0 = sample * b0 + i1 * b1 + i2 * b2 + o1 * a1 + o2 * a2; \
216 o0 = o0 * mix + (1. - mix) * sample; \
217 if (need_clipping && o0 < min) { \
220 } else if (need_clipping && o0 > max) { \
227 iir->biquads[i].i1 = i1; \
228 iir->biquads[i].i2 = i2; \
229 iir->biquads[i].o1 = o1; \
230 iir->biquads[i].o2 = o2; \
236 SERIAL_IIR_CH(s16p, int16_t, INT16_MIN, INT16_MAX, 1)
237 SERIAL_IIR_CH(s32p, int32_t, INT32_MIN, INT32_MAX, 1)
238 SERIAL_IIR_CH(fltp, float, -1., 1., 0)
239 SERIAL_IIR_CH(dblp, double, -1., 1., 0)
241 static void count_coefficients(char *item_str, int *nb_items)
249 for (p = item_str; *p && *p != '|'; p++) {
255 static int read_gains(AVFilterContext *ctx, char *item_str, int nb_items)
257 AudioIIRContext *s = ctx->priv;
258 char *p, *arg, *old_str, *prev_arg = NULL, *saveptr = NULL;
261 p = old_str = av_strdup(item_str);
263 return AVERROR(ENOMEM);
264 for (i = 0; i < nb_items; i++) {
265 if (!(arg = av_strtok(p, "|", &saveptr)))
270 return AVERROR(EINVAL);
274 if (sscanf(arg, "%lf", &s->iir[i].g) != 1) {
275 av_log(ctx, AV_LOG_ERROR, "Invalid gains supplied: %s\n", arg);
277 return AVERROR(EINVAL);
288 static int read_tf_coefficients(AVFilterContext *ctx, char *item_str, int nb_items, double *dst)
290 char *p, *arg, *old_str, *saveptr = NULL;
293 p = old_str = av_strdup(item_str);
295 return AVERROR(ENOMEM);
296 for (i = 0; i < nb_items; i++) {
297 if (!(arg = av_strtok(p, " ", &saveptr)))
301 if (sscanf(arg, "%lf", &dst[i]) != 1) {
302 av_log(ctx, AV_LOG_ERROR, "Invalid coefficients supplied: %s\n", arg);
304 return AVERROR(EINVAL);
313 static int read_zp_coefficients(AVFilterContext *ctx, char *item_str, int nb_items, double *dst, const char *format)
315 char *p, *arg, *old_str, *saveptr = NULL;
318 p = old_str = av_strdup(item_str);
320 return AVERROR(ENOMEM);
321 for (i = 0; i < nb_items; i++) {
322 if (!(arg = av_strtok(p, " ", &saveptr)))
326 if (sscanf(arg, format, &dst[i*2], &dst[i*2+1]) != 2) {
327 av_log(ctx, AV_LOG_ERROR, "Invalid coefficients supplied: %s\n", arg);
329 return AVERROR(EINVAL);
338 static const char *format[] = { "%lf", "%lf %lfi", "%lf %lfr", "%lf %lfd" };
340 static int read_channels(AVFilterContext *ctx, int channels, uint8_t *item_str, int ab)
342 AudioIIRContext *s = ctx->priv;
343 char *p, *arg, *old_str, *prev_arg = NULL, *saveptr = NULL;
346 p = old_str = av_strdup(item_str);
348 return AVERROR(ENOMEM);
349 for (i = 0; i < channels; i++) {
350 IIRChannel *iir = &s->iir[i];
352 if (!(arg = av_strtok(p, "|", &saveptr)))
357 return AVERROR(EINVAL);
360 count_coefficients(arg, &iir->nb_ab[ab]);
363 iir->cache[ab] = av_calloc(iir->nb_ab[ab] + 1, sizeof(double));
364 iir->ab[ab] = av_calloc(iir->nb_ab[ab] * (!!s->format + 1), sizeof(double));
365 if (!iir->ab[ab] || !iir->cache[ab]) {
367 return AVERROR(ENOMEM);
371 ret = read_zp_coefficients(ctx, arg, iir->nb_ab[ab], iir->ab[ab], format[s->format]);
373 ret = read_tf_coefficients(ctx, arg, iir->nb_ab[ab], iir->ab[ab]);
387 static void multiply(double wre, double wim, int npz, double *coeffs)
389 double nwre = -wre, nwim = -wim;
393 for (i = npz; i >= 1; i--) {
394 cre = coeffs[2 * i + 0];
395 cim = coeffs[2 * i + 1];
397 coeffs[2 * i + 0] = (nwre * cre - nwim * cim) + coeffs[2 * (i - 1) + 0];
398 coeffs[2 * i + 1] = (nwre * cim + nwim * cre) + coeffs[2 * (i - 1) + 1];
403 coeffs[0] = nwre * cre - nwim * cim;
404 coeffs[1] = nwre * cim + nwim * cre;
407 static int expand(AVFilterContext *ctx, double *pz, int nb, double *coeffs)
414 for (i = 0; i < nb; i++) {
415 coeffs[2 * (i + 1) ] = 0.0;
416 coeffs[2 * (i + 1) + 1] = 0.0;
419 for (i = 0; i < nb; i++)
420 multiply(pz[2 * i], pz[2 * i + 1], nb, coeffs);
422 for (i = 0; i < nb + 1; i++) {
423 if (fabs(coeffs[2 * i + 1]) > FLT_EPSILON) {
424 av_log(ctx, AV_LOG_ERROR, "coeff: %f of z^%d is not real; poles/zeros are not complex conjugates.\n",
425 coeffs[2 * i + 1], i);
426 return AVERROR(EINVAL);
433 static int convert_zp2tf(AVFilterContext *ctx, int channels)
435 AudioIIRContext *s = ctx->priv;
436 int ch, i, j, ret = 0;
438 for (ch = 0; ch < channels; ch++) {
439 IIRChannel *iir = &s->iir[ch];
442 topc = av_calloc((iir->nb_ab[0] + 1) * 2, sizeof(*topc));
443 botc = av_calloc((iir->nb_ab[1] + 1) * 2, sizeof(*botc));
444 if (!topc || !botc) {
445 ret = AVERROR(ENOMEM);
449 ret = expand(ctx, iir->ab[0], iir->nb_ab[0], botc);
454 ret = expand(ctx, iir->ab[1], iir->nb_ab[1], topc);
459 for (j = 0, i = iir->nb_ab[1]; i >= 0; j++, i--) {
460 iir->ab[1][j] = topc[2 * i];
464 for (j = 0, i = iir->nb_ab[0]; i >= 0; j++, i--) {
465 iir->ab[0][j] = botc[2 * i];
479 static int decompose_zp2biquads(AVFilterContext *ctx, int channels)
481 AudioIIRContext *s = ctx->priv;
484 for (ch = 0; ch < channels; ch++) {
485 IIRChannel *iir = &s->iir[ch];
486 int nb_biquads = (FFMAX(iir->nb_ab[0], iir->nb_ab[1]) + 1) / 2;
487 int current_biquad = 0;
489 iir->biquads = av_calloc(nb_biquads, sizeof(BiquadContext));
491 return AVERROR(ENOMEM);
493 while (nb_biquads--) {
494 Pair outmost_pole = { -1, -1 };
495 Pair nearest_zero = { -1, -1 };
496 double zeros[4] = { 0 };
497 double poles[4] = { 0 };
500 double min_distance = DBL_MAX;
505 for (i = 0; i < iir->nb_ab[0]; i++) {
508 if (isnan(iir->ab[0][2 * i]) || isnan(iir->ab[0][2 * i + 1]))
510 mag = hypot(iir->ab[0][2 * i], iir->ab[0][2 * i + 1]);
518 for (i = 0; i < iir->nb_ab[0]; i++) {
519 if (isnan(iir->ab[0][2 * i]) || isnan(iir->ab[0][2 * i + 1]))
522 if (iir->ab[0][2 * i ] == iir->ab[0][2 * outmost_pole.a ] &&
523 iir->ab[0][2 * i + 1] == -iir->ab[0][2 * outmost_pole.a + 1]) {
529 av_log(ctx, AV_LOG_VERBOSE, "outmost_pole is %d.%d\n", outmost_pole.a, outmost_pole.b);
531 if (outmost_pole.a < 0 || outmost_pole.b < 0)
532 return AVERROR(EINVAL);
534 for (i = 0; i < iir->nb_ab[1]; i++) {
537 if (isnan(iir->ab[1][2 * i]) || isnan(iir->ab[1][2 * i + 1]))
539 distance = hypot(iir->ab[0][2 * outmost_pole.a ] - iir->ab[1][2 * i ],
540 iir->ab[0][2 * outmost_pole.a + 1] - iir->ab[1][2 * i + 1]);
542 if (distance < min_distance) {
543 min_distance = distance;
548 for (i = 0; i < iir->nb_ab[1]; i++) {
549 if (isnan(iir->ab[1][2 * i]) || isnan(iir->ab[1][2 * i + 1]))
552 if (iir->ab[1][2 * i ] == iir->ab[1][2 * nearest_zero.a ] &&
553 iir->ab[1][2 * i + 1] == -iir->ab[1][2 * nearest_zero.a + 1]) {
559 av_log(ctx, AV_LOG_VERBOSE, "nearest_zero is %d.%d\n", nearest_zero.a, nearest_zero.b);
561 if (nearest_zero.a < 0 || nearest_zero.b < 0)
562 return AVERROR(EINVAL);
564 poles[0] = iir->ab[0][2 * outmost_pole.a ];
565 poles[1] = iir->ab[0][2 * outmost_pole.a + 1];
567 zeros[0] = iir->ab[1][2 * nearest_zero.a ];
568 zeros[1] = iir->ab[1][2 * nearest_zero.a + 1];
570 if (nearest_zero.a == nearest_zero.b && outmost_pole.a == outmost_pole.b) {
577 poles[2] = iir->ab[0][2 * outmost_pole.b ];
578 poles[3] = iir->ab[0][2 * outmost_pole.b + 1];
580 zeros[2] = iir->ab[1][2 * nearest_zero.b ];
581 zeros[3] = iir->ab[1][2 * nearest_zero.b + 1];
584 ret = expand(ctx, zeros, 2, b);
588 ret = expand(ctx, poles, 2, a);
592 iir->ab[0][2 * outmost_pole.a] = iir->ab[0][2 * outmost_pole.a + 1] = NAN;
593 iir->ab[0][2 * outmost_pole.b] = iir->ab[0][2 * outmost_pole.b + 1] = NAN;
594 iir->ab[1][2 * nearest_zero.a] = iir->ab[1][2 * nearest_zero.a + 1] = NAN;
595 iir->ab[1][2 * nearest_zero.b] = iir->ab[1][2 * nearest_zero.b + 1] = NAN;
597 iir->biquads[current_biquad].a[0] = 1.;
598 iir->biquads[current_biquad].a[1] = a[2] / a[4];
599 iir->biquads[current_biquad].a[2] = a[0] / a[4];
600 iir->biquads[current_biquad].b[0] = b[4] / a[4];
601 iir->biquads[current_biquad].b[1] = b[2] / a[4];
602 iir->biquads[current_biquad].b[2] = b[0] / a[4];
604 if (fabs(iir->biquads[current_biquad].b[0] +
605 iir->biquads[current_biquad].b[1] +
606 iir->biquads[current_biquad].b[2]) > 1e-6) {
607 factor = (iir->biquads[current_biquad].a[0] +
608 iir->biquads[current_biquad].a[1] +
609 iir->biquads[current_biquad].a[2]) /
610 (iir->biquads[current_biquad].b[0] +
611 iir->biquads[current_biquad].b[1] +
612 iir->biquads[current_biquad].b[2]);
614 av_log(ctx, AV_LOG_VERBOSE, "factor=%f\n", factor);
616 iir->biquads[current_biquad].b[0] *= factor;
617 iir->biquads[current_biquad].b[1] *= factor;
618 iir->biquads[current_biquad].b[2] *= factor;
621 iir->biquads[current_biquad].b[0] *= (current_biquad ? 1.0 : iir->g);
622 iir->biquads[current_biquad].b[1] *= (current_biquad ? 1.0 : iir->g);
623 iir->biquads[current_biquad].b[2] *= (current_biquad ? 1.0 : iir->g);
625 av_log(ctx, AV_LOG_VERBOSE, "a=%f %f %f:b=%f %f %f\n",
626 iir->biquads[current_biquad].a[0],
627 iir->biquads[current_biquad].a[1],
628 iir->biquads[current_biquad].a[2],
629 iir->biquads[current_biquad].b[0],
630 iir->biquads[current_biquad].b[1],
631 iir->biquads[current_biquad].b[2]);
640 static void convert_pr2zp(AVFilterContext *ctx, int channels)
642 AudioIIRContext *s = ctx->priv;
645 for (ch = 0; ch < channels; ch++) {
646 IIRChannel *iir = &s->iir[ch];
649 for (n = 0; n < iir->nb_ab[0]; n++) {
650 double r = iir->ab[0][2*n];
651 double angle = iir->ab[0][2*n+1];
653 iir->ab[0][2*n] = r * cos(angle);
654 iir->ab[0][2*n+1] = r * sin(angle);
657 for (n = 0; n < iir->nb_ab[1]; n++) {
658 double r = iir->ab[1][2*n];
659 double angle = iir->ab[1][2*n+1];
661 iir->ab[1][2*n] = r * cos(angle);
662 iir->ab[1][2*n+1] = r * sin(angle);
667 static void convert_pd2zp(AVFilterContext *ctx, int channels)
669 AudioIIRContext *s = ctx->priv;
672 for (ch = 0; ch < channels; ch++) {
673 IIRChannel *iir = &s->iir[ch];
676 for (n = 0; n < iir->nb_ab[0]; n++) {
677 double r = iir->ab[0][2*n];
678 double angle = M_PI*iir->ab[0][2*n+1]/180.;
680 iir->ab[0][2*n] = r * cos(angle);
681 iir->ab[0][2*n+1] = r * sin(angle);
684 for (n = 0; n < iir->nb_ab[1]; n++) {
685 double r = iir->ab[1][2*n];
686 double angle = M_PI*iir->ab[1][2*n+1]/180.;
688 iir->ab[1][2*n] = r * cos(angle);
689 iir->ab[1][2*n+1] = r * sin(angle);
694 static void check_stability(AVFilterContext *ctx, int channels)
696 AudioIIRContext *s = ctx->priv;
699 for (ch = 0; ch < channels; ch++) {
700 IIRChannel *iir = &s->iir[ch];
702 for (int n = 0; n < iir->nb_ab[0]; n++) {
703 double pr = hypot(iir->ab[0][2*n], iir->ab[0][2*n+1]);
706 av_log(ctx, AV_LOG_WARNING, "pole %d at channel %d is unstable\n", n, ch);
713 static void drawtext(AVFrame *pic, int x, int y, const char *txt, uint32_t color)
719 font = avpriv_cga_font, font_height = 8;
721 for (i = 0; txt[i]; i++) {
724 uint8_t *p = pic->data[0] + y * pic->linesize[0] + (x + i * 8) * 4;
725 for (char_y = 0; char_y < font_height; char_y++) {
726 for (mask = 0x80; mask; mask >>= 1) {
727 if (font[txt[i] * font_height + char_y] & mask)
731 p += pic->linesize[0] - 8 * 4;
736 static void draw_line(AVFrame *out, int x0, int y0, int x1, int y1, uint32_t color)
738 int dx = FFABS(x1-x0);
739 int dy = FFABS(y1-y0), sy = y0 < y1 ? 1 : -1;
740 int err = (dx>dy ? dx : -dy) / 2, e2;
743 AV_WL32(out->data[0] + y0 * out->linesize[0] + x0 * 4, color);
745 if (x0 == x1 && y0 == y1)
762 static void get_response(int channel, int format, double w,
763 const double *b, const double *a,
764 int nb_b, int nb_a, double *r, double *i)
772 realz = 0., realp = 0.;
773 imagz = 0., imagp = 0.;
774 for (int x = 0; x < nb_a; x++) {
775 realz += cos(-x * w) * a[x];
776 imagz += sin(-x * w) * a[x];
779 for (int x = 0; x < nb_b; x++) {
780 realp += cos(-x * w) * b[x];
781 imagp += sin(-x * w) * b[x];
784 div = realp * realp + imagp * imagp;
785 real = (realz * realp + imagz * imagp) / div;
786 imag = (imagz * realp - imagp * realz) / div;
790 for (int x = 0; x < nb_a; x++) {
791 double ore, oim, re, im;
793 re = cos(w) - a[2 * x];
794 im = sin(w) - a[2 * x + 1];
799 real = ore * re - oim * im;
800 imag = ore * im + oim * re;
803 for (int x = 0; x < nb_b; x++) {
804 double ore, oim, re, im;
806 re = cos(w) - b[2 * x];
807 im = sin(w) - b[2 * x + 1];
811 div = re * re + im * im;
813 real = (ore * re + oim * im) / div;
814 imag = (oim * re - ore * im) / div;
822 static void draw_response(AVFilterContext *ctx, AVFrame *out, int sample_rate)
824 AudioIIRContext *s = ctx->priv;
825 double *mag, *phase, *temp, *delay, min = DBL_MAX, max = -DBL_MAX;
826 double min_delay, max_delay, min_phase, max_phase;
827 int prev_ymag = -1, prev_yphase = -1, prev_ydelay = -1;
831 memset(out->data[0], 0, s->h * out->linesize[0]);
833 phase = av_malloc_array(s->w, sizeof(*phase));
834 temp = av_malloc_array(s->w, sizeof(*temp));
835 mag = av_malloc_array(s->w, sizeof(*mag));
836 delay = av_malloc_array(s->w, sizeof(*delay));
837 if (!mag || !phase || !delay || !temp)
840 ch = av_clip(s->ir_channel, 0, s->channels - 1);
841 for (i = 0; i < s->w; i++) {
842 const double *b = s->iir[ch].ab[0];
843 const double *a = s->iir[ch].ab[1];
844 const int nb_b = s->iir[ch].nb_ab[0];
845 const int nb_a = s->iir[ch].nb_ab[1];
846 double w = i * M_PI / (s->w - 1);
849 get_response(ch, s->format, w, b, a, nb_b, nb_a, &real, &imag);
851 mag[i] = s->iir[ch].g * hypot(real, imag);
852 phase[i] = atan2(imag, real);
853 min = fmin(min, mag[i]);
854 max = fmax(max, mag[i]);
858 for (i = 0; i < s->w - 1; i++) {
859 double d = phase[i] - phase[i + 1];
860 temp[i + 1] = ceil(fabs(d) / (2. * M_PI)) * 2. * M_PI * ((d > M_PI) - (d < -M_PI));
863 min_phase = phase[0];
864 max_phase = phase[0];
865 for (i = 1; i < s->w; i++) {
866 temp[i] += temp[i - 1];
868 min_phase = fmin(min_phase, phase[i]);
869 max_phase = fmax(max_phase, phase[i]);
875 for (i = 0; i < s->w - 1; i++) {
876 double div = s->w / (double)sample_rate;
878 delay[i + 1] = -(phase[i] - phase[i + 1]) / div;
879 min_delay = fmin(min_delay, delay[i + 1]);
880 max_delay = fmax(max_delay, delay[i + 1]);
883 delay[i] = delay[i - 1];
885 for (i = 0; i < s->w; i++) {
886 int ymag = mag[i] / max * (s->h - 1);
887 int ydelay = (delay[i] - min_delay) / (max_delay - min_delay) * (s->h - 1);
888 int yphase = (phase[i] - min_phase) / (max_phase - min_phase) * (s->h - 1);
890 ymag = s->h - 1 - av_clip(ymag, 0, s->h - 1);
891 yphase = s->h - 1 - av_clip(yphase, 0, s->h - 1);
892 ydelay = s->h - 1 - av_clip(ydelay, 0, s->h - 1);
897 prev_yphase = yphase;
899 prev_ydelay = ydelay;
901 draw_line(out, i, ymag, FFMAX(i - 1, 0), prev_ymag, 0xFFFF00FF);
902 draw_line(out, i, yphase, FFMAX(i - 1, 0), prev_yphase, 0xFF00FF00);
903 draw_line(out, i, ydelay, FFMAX(i - 1, 0), prev_ydelay, 0xFF00FFFF);
906 prev_yphase = yphase;
907 prev_ydelay = ydelay;
910 if (s->w > 400 && s->h > 100) {
911 drawtext(out, 2, 2, "Max Magnitude:", 0xDDDDDDDD);
912 snprintf(text, sizeof(text), "%.2f", max);
913 drawtext(out, 15 * 8 + 2, 2, text, 0xDDDDDDDD);
915 drawtext(out, 2, 12, "Min Magnitude:", 0xDDDDDDDD);
916 snprintf(text, sizeof(text), "%.2f", min);
917 drawtext(out, 15 * 8 + 2, 12, text, 0xDDDDDDDD);
919 drawtext(out, 2, 22, "Max Phase:", 0xDDDDDDDD);
920 snprintf(text, sizeof(text), "%.2f", max_phase);
921 drawtext(out, 15 * 8 + 2, 22, text, 0xDDDDDDDD);
923 drawtext(out, 2, 32, "Min Phase:", 0xDDDDDDDD);
924 snprintf(text, sizeof(text), "%.2f", min_phase);
925 drawtext(out, 15 * 8 + 2, 32, text, 0xDDDDDDDD);
927 drawtext(out, 2, 42, "Max Delay:", 0xDDDDDDDD);
928 snprintf(text, sizeof(text), "%.2f", max_delay);
929 drawtext(out, 11 * 8 + 2, 42, text, 0xDDDDDDDD);
931 drawtext(out, 2, 52, "Min Delay:", 0xDDDDDDDD);
932 snprintf(text, sizeof(text), "%.2f", min_delay);
933 drawtext(out, 11 * 8 + 2, 52, text, 0xDDDDDDDD);
943 static int config_output(AVFilterLink *outlink)
945 AVFilterContext *ctx = outlink->src;
946 AudioIIRContext *s = ctx->priv;
947 AVFilterLink *inlink = ctx->inputs[0];
950 s->channels = inlink->channels;
951 s->iir = av_calloc(s->channels, sizeof(*s->iir));
953 return AVERROR(ENOMEM);
955 ret = read_gains(ctx, s->g_str, inlink->channels);
959 ret = read_channels(ctx, inlink->channels, s->a_str, 0);
963 ret = read_channels(ctx, inlink->channels, s->b_str, 1);
967 if (s->format == 2) {
968 convert_pr2zp(ctx, inlink->channels);
969 } else if (s->format == 3) {
970 convert_pd2zp(ctx, inlink->channels);
973 check_stability(ctx, inlink->channels);
976 av_frame_free(&s->video);
978 s->video = ff_get_video_buffer(ctx->outputs[1], s->w, s->h);
980 return AVERROR(ENOMEM);
982 draw_response(ctx, s->video, inlink->sample_rate);
986 av_log(ctx, AV_LOG_WARNING, "tf coefficients format is not recommended for too high number of zeros/poles.\n");
988 if (s->format > 0 && s->process == 0) {
989 av_log(ctx, AV_LOG_WARNING, "Direct processsing is not recommended for zp coefficients format.\n");
991 ret = convert_zp2tf(ctx, inlink->channels);
994 } else if (s->format == 0 && s->process == 1) {
995 av_log(ctx, AV_LOG_ERROR, "Serial cascading is not implemented for transfer function.\n");
996 return AVERROR_PATCHWELCOME;
997 } else if (s->format > 0 && s->process == 1) {
998 if (inlink->format == AV_SAMPLE_FMT_S16P)
999 av_log(ctx, AV_LOG_WARNING, "Serial cascading is not recommended for i16 precision.\n");
1001 ret = decompose_zp2biquads(ctx, inlink->channels);
1006 for (ch = 0; s->format == 0 && ch < inlink->channels; ch++) {
1007 IIRChannel *iir = &s->iir[ch];
1009 for (i = 1; i < iir->nb_ab[0]; i++) {
1010 iir->ab[0][i] /= iir->ab[0][0];
1013 for (i = 0; i < iir->nb_ab[1]; i++) {
1014 iir->ab[1][i] *= iir->g / iir->ab[0][0];
1018 switch (inlink->format) {
1019 case AV_SAMPLE_FMT_DBLP: s->iir_channel = s->process == 1 ? iir_ch_serial_dblp : iir_ch_dblp; break;
1020 case AV_SAMPLE_FMT_FLTP: s->iir_channel = s->process == 1 ? iir_ch_serial_fltp : iir_ch_fltp; break;
1021 case AV_SAMPLE_FMT_S32P: s->iir_channel = s->process == 1 ? iir_ch_serial_s32p : iir_ch_s32p; break;
1022 case AV_SAMPLE_FMT_S16P: s->iir_channel = s->process == 1 ? iir_ch_serial_s16p : iir_ch_s16p; break;
1028 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
1030 AVFilterContext *ctx = inlink->dst;
1031 AudioIIRContext *s = ctx->priv;
1032 AVFilterLink *outlink = ctx->outputs[0];
1037 if (av_frame_is_writable(in)) {
1040 out = ff_get_audio_buffer(outlink, in->nb_samples);
1043 return AVERROR(ENOMEM);
1045 av_frame_copy_props(out, in);
1050 ctx->internal->execute(ctx, s->iir_channel, &td, NULL, outlink->channels);
1052 for (ch = 0; ch < outlink->channels; ch++) {
1053 if (s->iir[ch].clippings > 0)
1054 av_log(ctx, AV_LOG_WARNING, "Channel %d clipping %d times. Please reduce gain.\n",
1055 ch, s->iir[ch].clippings);
1056 s->iir[ch].clippings = 0;
1063 AVFilterLink *outlink = ctx->outputs[1];
1064 int64_t old_pts = s->video->pts;
1065 int64_t new_pts = av_rescale_q(out->pts, ctx->inputs[0]->time_base, outlink->time_base);
1067 if (new_pts > old_pts) {
1070 s->video->pts = new_pts;
1071 clone = av_frame_clone(s->video);
1073 return AVERROR(ENOMEM);
1074 ret = ff_filter_frame(outlink, clone);
1080 return ff_filter_frame(outlink, out);
1083 static int config_video(AVFilterLink *outlink)
1085 AVFilterContext *ctx = outlink->src;
1086 AudioIIRContext *s = ctx->priv;
1088 outlink->sample_aspect_ratio = (AVRational){1,1};
1091 outlink->frame_rate = s->rate;
1092 outlink->time_base = av_inv_q(outlink->frame_rate);
1097 static av_cold int init(AVFilterContext *ctx)
1099 AudioIIRContext *s = ctx->priv;
1100 AVFilterPad pad, vpad;
1103 if (!s->a_str || !s->b_str || !s->g_str) {
1104 av_log(ctx, AV_LOG_ERROR, "Valid coefficients are mandatory.\n");
1105 return AVERROR(EINVAL);
1108 switch (s->precision) {
1109 case 0: s->sample_format = AV_SAMPLE_FMT_DBLP; break;
1110 case 1: s->sample_format = AV_SAMPLE_FMT_FLTP; break;
1111 case 2: s->sample_format = AV_SAMPLE_FMT_S32P; break;
1112 case 3: s->sample_format = AV_SAMPLE_FMT_S16P; break;
1113 default: return AVERROR_BUG;
1116 pad = (AVFilterPad){
1117 .name = av_strdup("default"),
1118 .type = AVMEDIA_TYPE_AUDIO,
1119 .config_props = config_output,
1123 return AVERROR(ENOMEM);
1126 vpad = (AVFilterPad){
1127 .name = av_strdup("filter_response"),
1128 .type = AVMEDIA_TYPE_VIDEO,
1129 .config_props = config_video,
1132 return AVERROR(ENOMEM);
1135 ret = ff_insert_outpad(ctx, 0, &pad);
1140 ret = ff_insert_outpad(ctx, 1, &vpad);
1148 static av_cold void uninit(AVFilterContext *ctx)
1150 AudioIIRContext *s = ctx->priv;
1154 for (ch = 0; ch < s->channels; ch++) {
1155 IIRChannel *iir = &s->iir[ch];
1156 av_freep(&iir->ab[0]);
1157 av_freep(&iir->ab[1]);
1158 av_freep(&iir->cache[0]);
1159 av_freep(&iir->cache[1]);
1160 av_freep(&iir->biquads);
1165 av_freep(&ctx->output_pads[0].name);
1167 av_freep(&ctx->output_pads[1].name);
1168 av_frame_free(&s->video);
1171 static const AVFilterPad inputs[] = {
1174 .type = AVMEDIA_TYPE_AUDIO,
1175 .filter_frame = filter_frame,
1180 #define OFFSET(x) offsetof(AudioIIRContext, x)
1181 #define AF AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
1182 #define VF AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
1184 static const AVOption aiir_options[] = {
1185 { "z", "set B/numerator/zeros coefficients", OFFSET(b_str), AV_OPT_TYPE_STRING, {.str="1+0i 1-0i"}, 0, 0, AF },
1186 { "p", "set A/denominator/poles coefficients", OFFSET(a_str), AV_OPT_TYPE_STRING, {.str="1+0i 1-0i"}, 0, 0, AF },
1187 { "k", "set channels gains", OFFSET(g_str), AV_OPT_TYPE_STRING, {.str="1|1"}, 0, 0, AF },
1188 { "dry", "set dry gain", OFFSET(dry_gain), AV_OPT_TYPE_DOUBLE, {.dbl=1}, 0, 1, AF },
1189 { "wet", "set wet gain", OFFSET(wet_gain), AV_OPT_TYPE_DOUBLE, {.dbl=1}, 0, 1, AF },
1190 { "f", "set coefficients format", OFFSET(format), AV_OPT_TYPE_INT, {.i64=1}, 0, 3, AF, "format" },
1191 { "tf", "transfer function", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, AF, "format" },
1192 { "zp", "Z-plane zeros/poles", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, AF, "format" },
1193 { "pr", "Z-plane zeros/poles (polar radians)", 0, AV_OPT_TYPE_CONST, {.i64=2}, 0, 0, AF, "format" },
1194 { "pd", "Z-plane zeros/poles (polar degrees)", 0, AV_OPT_TYPE_CONST, {.i64=3}, 0, 0, AF, "format" },
1195 { "r", "set kind of processing", OFFSET(process), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, AF, "process" },
1196 { "d", "direct", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, AF, "process" },
1197 { "s", "serial cascading", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, AF, "process" },
1198 { "e", "set precision", OFFSET(precision),AV_OPT_TYPE_INT, {.i64=0}, 0, 3, AF, "precision" },
1199 { "dbl", "double-precision floating-point", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, AF, "precision" },
1200 { "flt", "single-precision floating-point", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, AF, "precision" },
1201 { "i32", "32-bit integers", 0, AV_OPT_TYPE_CONST, {.i64=2}, 0, 0, AF, "precision" },
1202 { "i16", "16-bit integers", 0, AV_OPT_TYPE_CONST, {.i64=3}, 0, 0, AF, "precision" },
1203 { "mix", "set mix", OFFSET(mix), AV_OPT_TYPE_DOUBLE, {.dbl=1}, 0, 1, AF },
1204 { "response", "show IR frequency response", OFFSET(response), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, VF },
1205 { "channel", "set IR channel to display frequency response", OFFSET(ir_channel), AV_OPT_TYPE_INT, {.i64=0}, 0, 1024, VF },
1206 { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "hd720"}, 0, 0, VF },
1207 { "rate", "set video rate", OFFSET(rate), AV_OPT_TYPE_VIDEO_RATE, {.str = "25"}, 0, INT32_MAX, VF },
1211 AVFILTER_DEFINE_CLASS(aiir);
1213 AVFilter ff_af_aiir = {
1215 .description = NULL_IF_CONFIG_SMALL("Apply Infinite Impulse Response filter with supplied coefficients."),
1216 .priv_size = sizeof(AudioIIRContext),
1217 .priv_class = &aiir_class,
1220 .query_formats = query_formats,
1222 .flags = AVFILTER_FLAG_DYNAMIC_OUTPUTS |
1223 AVFILTER_FLAG_SLICE_THREADS,