]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_afir.c
avfilter/af_afir: remove not needed nb_samples from filter context
[ffmpeg] / libavfilter / af_afir.c
1 /*
2  * Copyright (c) 2017 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 /**
22  * @file
23  * An arbitrary audio FIR filter
24  */
25
26 #include <float.h>
27
28 #include "libavutil/common.h"
29 #include "libavutil/float_dsp.h"
30 #include "libavutil/intreadwrite.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/xga_font_data.h"
33 #include "libavcodec/avfft.h"
34
35 #include "audio.h"
36 #include "avfilter.h"
37 #include "filters.h"
38 #include "formats.h"
39 #include "internal.h"
40 #include "af_afir.h"
41
42 static void fcmul_add_c(float *sum, const float *t, const float *c, ptrdiff_t len)
43 {
44     int n;
45
46     for (n = 0; n < len; n++) {
47         const float cre = c[2 * n    ];
48         const float cim = c[2 * n + 1];
49         const float tre = t[2 * n    ];
50         const float tim = t[2 * n + 1];
51
52         sum[2 * n    ] += tre * cre - tim * cim;
53         sum[2 * n + 1] += tre * cim + tim * cre;
54     }
55
56     sum[2 * n] += t[2 * n] * c[2 * n];
57 }
58
59 static int fir_channel(AVFilterContext *ctx, void *arg, int ch, int nb_jobs)
60 {
61     AudioFIRContext *s = ctx->priv;
62     const float *src = (const float *)s->in[0]->extended_data[ch];
63     int index1 = (s->index + 1) % 3;
64     int index2 = (s->index + 2) % 3;
65     float *sum = s->sum[ch];
66     AVFrame *out = arg;
67     float *block;
68     float *dst;
69     int n, i, j;
70
71     memset(sum, 0, sizeof(*sum) * s->fft_length);
72     block = s->block[ch] + s->part_index * s->block_size;
73     memset(block, 0, sizeof(*block) * s->fft_length);
74
75     s->fdsp->vector_fmul_scalar(block, src, s->dry_gain, FFALIGN(out->nb_samples, 4));
76     emms_c();
77
78     av_rdft_calc(s->rdft[ch], block);
79     block[2 * s->part_size] = block[1];
80     block[1] = 0;
81
82     j = s->part_index;
83
84     for (i = 0; i < s->nb_partitions; i++) {
85         const int coffset = i * s->coeff_size;
86         const FFTComplex *coeff = s->coeff[ch * !s->one2many] + coffset;
87
88         block = s->block[ch] + j * s->block_size;
89         s->fcmul_add(sum, block, (const float *)coeff, s->part_size);
90
91         if (j == 0)
92             j = s->nb_partitions;
93         j--;
94     }
95
96     sum[1] = sum[2 * s->part_size];
97     av_rdft_calc(s->irdft[ch], sum);
98
99     dst = (float *)s->buffer->extended_data[ch] + index1 * s->part_size;
100     for (n = 0; n < s->part_size; n++) {
101         dst[n] += sum[n];
102     }
103
104     dst = (float *)s->buffer->extended_data[ch] + index2 * s->part_size;
105
106     memcpy(dst, sum + s->part_size, s->part_size * sizeof(*dst));
107
108     dst = (float *)s->buffer->extended_data[ch] + s->index * s->part_size;
109
110     if (out) {
111         float *ptr = (float *)out->extended_data[ch];
112         s->fdsp->vector_fmul_scalar(ptr, dst, s->wet_gain, FFALIGN(out->nb_samples, 4));
113         emms_c();
114     }
115
116     return 0;
117 }
118
119 static int fir_frame(AudioFIRContext *s, AVFrame *in, AVFilterLink *outlink)
120 {
121     AVFilterContext *ctx = outlink->src;
122     AVFrame *out = NULL;
123
124     out = ff_get_audio_buffer(outlink, in->nb_samples);
125     if (!out) {
126         av_frame_free(&in);
127         return AVERROR(ENOMEM);
128     }
129
130     if (s->pts == AV_NOPTS_VALUE)
131         s->pts = in->pts;
132     s->in[0] = in;
133     ctx->internal->execute(ctx, fir_channel, out, NULL, outlink->channels);
134
135     s->part_index = (s->part_index + 1) % s->nb_partitions;
136
137     out->pts = s->pts;
138     if (s->pts != AV_NOPTS_VALUE)
139         s->pts += av_rescale_q(out->nb_samples, (AVRational){1, outlink->sample_rate}, outlink->time_base);
140
141     s->index++;
142     if (s->index == 3)
143         s->index = 0;
144
145     av_frame_free(&in);
146     s->in[0] = NULL;
147
148     return ff_filter_frame(outlink, out);
149 }
150
151 static void drawtext(AVFrame *pic, int x, int y, const char *txt, uint32_t color)
152 {
153     const uint8_t *font;
154     int font_height;
155     int i;
156
157     font = avpriv_cga_font, font_height = 8;
158
159     for (i = 0; txt[i]; i++) {
160         int char_y, mask;
161
162         uint8_t *p = pic->data[0] + y * pic->linesize[0] + (x + i * 8) * 4;
163         for (char_y = 0; char_y < font_height; char_y++) {
164             for (mask = 0x80; mask; mask >>= 1) {
165                 if (font[txt[i] * font_height + char_y] & mask)
166                     AV_WL32(p, color);
167                 p += 4;
168             }
169             p += pic->linesize[0] - 8 * 4;
170         }
171     }
172 }
173
174 static void draw_line(AVFrame *out, int x0, int y0, int x1, int y1, uint32_t color)
175 {
176     int dx = FFABS(x1-x0);
177     int dy = FFABS(y1-y0), sy = y0 < y1 ? 1 : -1;
178     int err = (dx>dy ? dx : -dy) / 2, e2;
179
180     for (;;) {
181         AV_WL32(out->data[0] + y0 * out->linesize[0] + x0 * 4, color);
182
183         if (x0 == x1 && y0 == y1)
184             break;
185
186         e2 = err;
187
188         if (e2 >-dx) {
189             err -= dy;
190             x0--;
191         }
192
193         if (e2 < dy) {
194             err += dx;
195             y0 += sy;
196         }
197     }
198 }
199
200 static void draw_response(AVFilterContext *ctx, AVFrame *out)
201 {
202     AudioFIRContext *s = ctx->priv;
203     float *mag, *phase, *delay, min = FLT_MAX, max = FLT_MIN;
204     float min_delay = FLT_MAX, max_delay = FLT_MIN;
205     int prev_ymag = -1, prev_yphase = -1, prev_ydelay = -1;
206     char text[32];
207     int channel, i, x;
208
209     memset(out->data[0], 0, s->h * out->linesize[0]);
210
211     phase = av_malloc_array(s->w, sizeof(*phase));
212     mag = av_malloc_array(s->w, sizeof(*mag));
213     delay = av_malloc_array(s->w, sizeof(*delay));
214     if (!mag || !phase || !delay)
215         goto end;
216
217     channel = av_clip(s->ir_channel, 0, s->in[1]->channels - 1);
218     for (i = 0; i < s->w; i++) {
219         const float *src = (const float *)s->in[1]->extended_data[channel];
220         double w = i * M_PI / (s->w - 1);
221         double div, real_num = 0., imag_num = 0., real = 0., imag = 0.;
222
223         for (x = 0; x < s->nb_taps; x++) {
224             real += cos(-x * w) * src[x];
225             imag += sin(-x * w) * src[x];
226             real_num += cos(-x * w) * src[x] * x;
227             imag_num += sin(-x * w) * src[x] * x;
228         }
229
230         mag[i] = hypot(real, imag);
231         phase[i] = atan2(imag, real);
232         div = real * real + imag * imag;
233         delay[i] = (real_num * real + imag_num * imag) / div;
234         min = fminf(min, mag[i]);
235         max = fmaxf(max, mag[i]);
236         min_delay = fminf(min_delay, delay[i]);
237         max_delay = fmaxf(max_delay, delay[i]);
238     }
239
240     for (i = 0; i < s->w; i++) {
241         int ymag = mag[i] / max * (s->h - 1);
242         int ydelay = (delay[i] - min_delay) / (max_delay - min_delay) * (s->h - 1);
243         int yphase = (0.5 * (1. + phase[i] / M_PI)) * (s->h - 1);
244
245         ymag = s->h - 1 - av_clip(ymag, 0, s->h - 1);
246         yphase = s->h - 1 - av_clip(yphase, 0, s->h - 1);
247         ydelay = s->h - 1 - av_clip(ydelay, 0, s->h - 1);
248
249         if (prev_ymag < 0)
250             prev_ymag = ymag;
251         if (prev_yphase < 0)
252             prev_yphase = yphase;
253         if (prev_ydelay < 0)
254             prev_ydelay = ydelay;
255
256         draw_line(out, i,   ymag, FFMAX(i - 1, 0),   prev_ymag, 0xFFFF00FF);
257         draw_line(out, i, yphase, FFMAX(i - 1, 0), prev_yphase, 0xFF00FF00);
258         draw_line(out, i, ydelay, FFMAX(i - 1, 0), prev_ydelay, 0xFF00FFFF);
259
260         prev_ymag   = ymag;
261         prev_yphase = yphase;
262         prev_ydelay = ydelay;
263     }
264
265     if (s->w > 400 && s->h > 100) {
266         drawtext(out, 2, 2, "Max Magnitude:", 0xDDDDDDDD);
267         snprintf(text, sizeof(text), "%.2f", max);
268         drawtext(out, 15 * 8 + 2, 2, text, 0xDDDDDDDD);
269
270         drawtext(out, 2, 12, "Min Magnitude:", 0xDDDDDDDD);
271         snprintf(text, sizeof(text), "%.2f", min);
272         drawtext(out, 15 * 8 + 2, 12, text, 0xDDDDDDDD);
273
274         drawtext(out, 2, 22, "Max Delay:", 0xDDDDDDDD);
275         snprintf(text, sizeof(text), "%.2f", max_delay);
276         drawtext(out, 11 * 8 + 2, 22, text, 0xDDDDDDDD);
277
278         drawtext(out, 2, 32, "Min Delay:", 0xDDDDDDDD);
279         snprintf(text, sizeof(text), "%.2f", min_delay);
280         drawtext(out, 11 * 8 + 2, 32, text, 0xDDDDDDDD);
281     }
282
283 end:
284     av_free(delay);
285     av_free(phase);
286     av_free(mag);
287 }
288
289 static int convert_coeffs(AVFilterContext *ctx)
290 {
291     AudioFIRContext *s = ctx->priv;
292     int ret, i, ch, n, N;
293     float power = 0;
294
295     s->nb_taps = ff_inlink_queued_samples(ctx->inputs[1]);
296     if (s->nb_taps <= 0)
297         return AVERROR(EINVAL);
298
299     for (n = av_log2(s->minp); (1 << n) < s->nb_taps; n++);
300     N = FFMIN(n, av_log2(s->maxp));
301     s->fft_length = (1 << (N + 1)) + 1;
302     s->part_size = 1 << (N - 1);
303     s->block_size = FFALIGN(s->fft_length, 32);
304     s->coeff_size = FFALIGN(s->part_size + 1, 32);
305     s->nb_partitions = (s->nb_taps + s->part_size - 1) / s->part_size;
306
307     for (ch = 0; ch < ctx->inputs[0]->channels; ch++) {
308         s->sum[ch] = av_calloc(s->fft_length, sizeof(**s->sum));
309         if (!s->sum[ch])
310             return AVERROR(ENOMEM);
311     }
312
313     for (ch = 0; ch < ctx->inputs[1]->channels; ch++) {
314         s->coeff[ch] = av_calloc(s->nb_partitions * s->coeff_size, sizeof(**s->coeff));
315         if (!s->coeff[ch])
316             return AVERROR(ENOMEM);
317     }
318
319     for (ch = 0; ch < ctx->inputs[0]->channels; ch++) {
320         s->block[ch] = av_calloc(s->nb_partitions * s->block_size, sizeof(**s->block));
321         if (!s->block[ch])
322             return AVERROR(ENOMEM);
323     }
324
325     for (ch = 0; ch < ctx->inputs[0]->channels; ch++) {
326         s->rdft[ch]  = av_rdft_init(N, DFT_R2C);
327         s->irdft[ch] = av_rdft_init(N, IDFT_C2R);
328         if (!s->rdft[ch] || !s->irdft[ch])
329             return AVERROR(ENOMEM);
330     }
331
332     s->buffer = ff_get_audio_buffer(ctx->inputs[0], s->part_size * 3);
333     if (!s->buffer)
334         return AVERROR(ENOMEM);
335
336     ret = ff_inlink_consume_samples(ctx->inputs[1], s->nb_taps, s->nb_taps, &s->in[1]);
337     if (ret < 0)
338         return ret;
339     if (ret == 0)
340         return AVERROR_BUG;
341
342     if (s->response)
343         draw_response(ctx, s->video);
344
345     s->gain = 1;
346
347     switch (s->gtype) {
348     case -1:
349         /* nothing to do */
350         break;
351     case 0:
352         for (ch = 0; ch < ctx->inputs[1]->channels; ch++) {
353             float *time = (float *)s->in[1]->extended_data[!s->one2many * ch];
354
355             for (i = 0; i < s->nb_taps; i++)
356                 power += FFABS(time[i]);
357         }
358         s->gain = ctx->inputs[1]->channels / power;
359         break;
360     case 1:
361         for (ch = 0; ch < ctx->inputs[1]->channels; ch++) {
362             float *time = (float *)s->in[1]->extended_data[!s->one2many * ch];
363
364             for (i = 0; i < s->nb_taps; i++)
365                 power += time[i];
366         }
367         s->gain = ctx->inputs[1]->channels / power;
368         break;
369     case 2:
370         for (ch = 0; ch < ctx->inputs[1]->channels; ch++) {
371             float *time = (float *)s->in[1]->extended_data[!s->one2many * ch];
372
373             for (i = 0; i < s->nb_taps; i++)
374                 power += time[i] * time[i];
375         }
376         s->gain = sqrtf(ch / power);
377         break;
378     default:
379         return AVERROR_BUG;
380     }
381
382     s->gain = FFMIN(s->gain * s->ir_gain, 1.f);
383     av_log(ctx, AV_LOG_DEBUG, "power %f, gain %f\n", power, s->gain);
384     for (ch = 0; ch < ctx->inputs[1]->channels; ch++) {
385         float *time = (float *)s->in[1]->extended_data[!s->one2many * ch];
386
387         s->fdsp->vector_fmul_scalar(time, time, s->gain, FFALIGN(s->nb_taps, 4));
388     }
389
390     for (ch = 0; ch < ctx->inputs[1]->channels; ch++) {
391         float *time = (float *)s->in[1]->extended_data[!s->one2many * ch];
392         float *block = s->block[ch];
393         FFTComplex *coeff = s->coeff[ch];
394
395         for (i = FFMAX(1, s->length * s->nb_taps); i < s->nb_taps; i++)
396             time[i] = 0;
397
398         for (i = 0; i < s->nb_partitions; i++) {
399             const float scale = 1.f / s->part_size;
400             const int toffset = i * s->part_size;
401             const int coffset = i * s->coeff_size;
402             const int remaining = s->nb_taps - (i * s->part_size);
403             const int size = remaining >= s->part_size ? s->part_size : remaining;
404
405             memset(block, 0, sizeof(*block) * s->fft_length);
406             memcpy(block, time + toffset, size * sizeof(*block));
407
408             av_rdft_calc(s->rdft[0], block);
409
410             coeff[coffset].re = block[0] * scale;
411             coeff[coffset].im = 0;
412             for (n = 1; n < s->part_size; n++) {
413                 coeff[coffset + n].re = block[2 * n] * scale;
414                 coeff[coffset + n].im = block[2 * n + 1] * scale;
415             }
416             coeff[coffset + s->part_size].re = block[1] * scale;
417             coeff[coffset + s->part_size].im = 0;
418         }
419     }
420
421     av_frame_free(&s->in[1]);
422     av_log(ctx, AV_LOG_DEBUG, "nb_taps: %d\n", s->nb_taps);
423     av_log(ctx, AV_LOG_DEBUG, "nb_partitions: %d\n", s->nb_partitions);
424     av_log(ctx, AV_LOG_DEBUG, "partition size: %d\n", s->part_size);
425     av_log(ctx, AV_LOG_DEBUG, "fft_length: %d\n", s->fft_length);
426
427     s->have_coeffs = 1;
428
429     return 0;
430 }
431
432 static int check_ir(AVFilterLink *link, AVFrame *frame)
433 {
434     AVFilterContext *ctx = link->dst;
435     AudioFIRContext *s = ctx->priv;
436     int nb_taps, max_nb_taps;
437
438     nb_taps = ff_inlink_queued_samples(link);
439     max_nb_taps = s->max_ir_len * ctx->outputs[0]->sample_rate;
440     if (nb_taps > max_nb_taps) {
441         av_log(ctx, AV_LOG_ERROR, "Too big number of coefficients: %d > %d.\n", nb_taps, max_nb_taps);
442         return AVERROR(EINVAL);
443     }
444
445     return 0;
446 }
447
448 static int activate(AVFilterContext *ctx)
449 {
450     AudioFIRContext *s = ctx->priv;
451     AVFilterLink *outlink = ctx->outputs[0];
452     AVFrame *in = NULL;
453     int ret, status;
454     int64_t pts;
455
456     FF_FILTER_FORWARD_STATUS_BACK_ALL(ctx->outputs[0], ctx);
457     if (s->response)
458         FF_FILTER_FORWARD_STATUS_BACK_ALL(ctx->outputs[1], ctx);
459     if (!s->eof_coeffs) {
460         AVFrame *ir = NULL;
461
462         ret = check_ir(ctx->inputs[1], ir);
463         if (ret < 0)
464             return ret;
465
466         if (ff_outlink_get_status(ctx->inputs[1]) == AVERROR_EOF)
467             s->eof_coeffs = 1;
468
469         if (!s->eof_coeffs) {
470             if (ff_outlink_frame_wanted(ctx->outputs[0]))
471                 ff_inlink_request_frame(ctx->inputs[1]);
472             else if (s->response && ff_outlink_frame_wanted(ctx->outputs[1]))
473                 ff_inlink_request_frame(ctx->inputs[1]);
474             return 0;
475         }
476     }
477
478     if (!s->have_coeffs && s->eof_coeffs) {
479         ret = convert_coeffs(ctx);
480         if (ret < 0)
481             return ret;
482     }
483
484     ret = ff_inlink_consume_samples(ctx->inputs[0], s->part_size, s->part_size, &in);
485     if (ret > 0)
486         ret = fir_frame(s, in, outlink);
487
488     if (ret < 0)
489         return ret;
490
491     if (s->response && s->have_coeffs) {
492         int64_t old_pts = s->video->pts;
493         int64_t new_pts = av_rescale_q(s->pts, ctx->inputs[0]->time_base, ctx->outputs[1]->time_base);
494
495         if (ff_outlink_frame_wanted(ctx->outputs[1]) && old_pts < new_pts) {
496             s->video->pts = new_pts;
497             return ff_filter_frame(ctx->outputs[1], av_frame_clone(s->video));
498         }
499     }
500
501     if (ff_inlink_queued_samples(ctx->inputs[0]) >= s->part_size) {
502         ff_filter_set_ready(ctx, 10);
503         return 0;
504     }
505
506     if (ff_inlink_acknowledge_status(ctx->inputs[0], &status, &pts)) {
507         if (status == AVERROR_EOF) {
508             ff_outlink_set_status(ctx->outputs[0], status, pts);
509             if (s->response)
510                 ff_outlink_set_status(ctx->outputs[1], status, pts);
511             return 0;
512         }
513     }
514
515     if (ff_outlink_frame_wanted(ctx->outputs[0]) &&
516         !ff_outlink_get_status(ctx->inputs[0])) {
517         ff_inlink_request_frame(ctx->inputs[0]);
518         return 0;
519     }
520
521     if (s->response &&
522         ff_outlink_frame_wanted(ctx->outputs[1]) &&
523         !ff_outlink_get_status(ctx->inputs[0])) {
524         ff_inlink_request_frame(ctx->inputs[0]);
525         return 0;
526     }
527
528     return FFERROR_NOT_READY;
529 }
530
531 static int query_formats(AVFilterContext *ctx)
532 {
533     AudioFIRContext *s = ctx->priv;
534     AVFilterFormats *formats;
535     AVFilterChannelLayouts *layouts;
536     static const enum AVSampleFormat sample_fmts[] = {
537         AV_SAMPLE_FMT_FLTP,
538         AV_SAMPLE_FMT_NONE
539     };
540     static const enum AVPixelFormat pix_fmts[] = {
541         AV_PIX_FMT_RGB0,
542         AV_PIX_FMT_NONE
543     };
544     int ret;
545
546     if (s->response) {
547         AVFilterLink *videolink = ctx->outputs[1];
548         formats = ff_make_format_list(pix_fmts);
549         if ((ret = ff_formats_ref(formats, &videolink->in_formats)) < 0)
550             return ret;
551     }
552
553     layouts = ff_all_channel_counts();
554     if (!layouts)
555         return AVERROR(ENOMEM);
556
557     if (s->ir_format) {
558         ret = ff_set_common_channel_layouts(ctx, layouts);
559         if (ret < 0)
560             return ret;
561     } else {
562         AVFilterChannelLayouts *mono = NULL;
563
564         ret = ff_add_channel_layout(&mono, AV_CH_LAYOUT_MONO);
565         if (ret)
566             return ret;
567
568         if ((ret = ff_channel_layouts_ref(layouts, &ctx->inputs[0]->out_channel_layouts)) < 0)
569             return ret;
570         if ((ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts)) < 0)
571             return ret;
572         if ((ret = ff_channel_layouts_ref(mono, &ctx->inputs[1]->out_channel_layouts)) < 0)
573             return ret;
574     }
575
576     formats = ff_make_format_list(sample_fmts);
577     if ((ret = ff_set_common_formats(ctx, formats)) < 0)
578         return ret;
579
580     formats = ff_all_samplerates();
581     return ff_set_common_samplerates(ctx, formats);
582 }
583
584 static int config_output(AVFilterLink *outlink)
585 {
586     AVFilterContext *ctx = outlink->src;
587     AudioFIRContext *s = ctx->priv;
588
589     s->one2many = ctx->inputs[1]->channels == 1;
590     outlink->sample_rate = ctx->inputs[0]->sample_rate;
591     outlink->time_base   = ctx->inputs[0]->time_base;
592     outlink->channel_layout = ctx->inputs[0]->channel_layout;
593     outlink->channels = ctx->inputs[0]->channels;
594
595     s->sum = av_calloc(outlink->channels, sizeof(*s->sum));
596     s->coeff = av_calloc(ctx->inputs[1]->channels, sizeof(*s->coeff));
597     s->block = av_calloc(ctx->inputs[0]->channels, sizeof(*s->block));
598     s->rdft = av_calloc(outlink->channels, sizeof(*s->rdft));
599     s->irdft = av_calloc(outlink->channels, sizeof(*s->irdft));
600     if (!s->sum || !s->coeff || !s->block || !s->rdft || !s->irdft)
601         return AVERROR(ENOMEM);
602
603     s->nb_channels = outlink->channels;
604     s->nb_coef_channels = ctx->inputs[1]->channels;
605     s->pts = AV_NOPTS_VALUE;
606
607     return 0;
608 }
609
610 static av_cold void uninit(AVFilterContext *ctx)
611 {
612     AudioFIRContext *s = ctx->priv;
613     int ch;
614
615     if (s->sum) {
616         for (ch = 0; ch < s->nb_channels; ch++) {
617             av_freep(&s->sum[ch]);
618         }
619     }
620     av_freep(&s->sum);
621
622     if (s->coeff) {
623         for (ch = 0; ch < s->nb_coef_channels; ch++) {
624             av_freep(&s->coeff[ch]);
625         }
626     }
627     av_freep(&s->coeff);
628
629     if (s->block) {
630         for (ch = 0; ch < s->nb_channels; ch++) {
631             av_freep(&s->block[ch]);
632         }
633     }
634     av_freep(&s->block);
635
636     if (s->rdft) {
637         for (ch = 0; ch < s->nb_channels; ch++) {
638             av_rdft_end(s->rdft[ch]);
639         }
640     }
641     av_freep(&s->rdft);
642
643     if (s->irdft) {
644         for (ch = 0; ch < s->nb_channels; ch++) {
645             av_rdft_end(s->irdft[ch]);
646         }
647     }
648     av_freep(&s->irdft);
649
650     av_frame_free(&s->in[1]);
651     av_frame_free(&s->buffer);
652
653     av_freep(&s->fdsp);
654
655     for (int i = 0; i < ctx->nb_outputs; i++)
656         av_freep(&ctx->output_pads[i].name);
657     av_frame_free(&s->video);
658 }
659
660 static int config_video(AVFilterLink *outlink)
661 {
662     AVFilterContext *ctx = outlink->src;
663     AudioFIRContext *s = ctx->priv;
664
665     outlink->sample_aspect_ratio = (AVRational){1,1};
666     outlink->w = s->w;
667     outlink->h = s->h;
668     outlink->frame_rate = s->frame_rate;
669     outlink->time_base = av_inv_q(outlink->frame_rate);
670
671     av_frame_free(&s->video);
672     s->video = ff_get_video_buffer(outlink, outlink->w, outlink->h);
673     if (!s->video)
674         return AVERROR(ENOMEM);
675
676     return 0;
677 }
678
679 static av_cold int init(AVFilterContext *ctx)
680 {
681     AudioFIRContext *s = ctx->priv;
682     AVFilterPad pad, vpad;
683     int ret;
684
685     pad = (AVFilterPad){
686         .name          = av_strdup("default"),
687         .type          = AVMEDIA_TYPE_AUDIO,
688         .config_props  = config_output,
689     };
690
691     if (!pad.name)
692         return AVERROR(ENOMEM);
693
694     if (s->response) {
695         vpad = (AVFilterPad){
696             .name         = av_strdup("filter_response"),
697             .type         = AVMEDIA_TYPE_VIDEO,
698             .config_props = config_video,
699         };
700         if (!vpad.name)
701             return AVERROR(ENOMEM);
702     }
703
704     ret = ff_insert_outpad(ctx, 0, &pad);
705     if (ret < 0) {
706         av_freep(&pad.name);
707         return ret;
708     }
709
710     if (s->response) {
711         ret = ff_insert_outpad(ctx, 1, &vpad);
712         if (ret < 0) {
713             av_freep(&vpad.name);
714             return ret;
715         }
716     }
717
718     s->fcmul_add = fcmul_add_c;
719
720     s->fdsp = avpriv_float_dsp_alloc(0);
721     if (!s->fdsp)
722         return AVERROR(ENOMEM);
723
724     if (ARCH_X86)
725         ff_afir_init_x86(s);
726
727     return 0;
728 }
729
730 static const AVFilterPad afir_inputs[] = {
731     {
732         .name           = "main",
733         .type           = AVMEDIA_TYPE_AUDIO,
734     },{
735         .name           = "ir",
736         .type           = AVMEDIA_TYPE_AUDIO,
737     },
738     { NULL }
739 };
740
741 #define AF AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
742 #define VF AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
743 #define OFFSET(x) offsetof(AudioFIRContext, x)
744
745 static const AVOption afir_options[] = {
746     { "dry",    "set dry gain",      OFFSET(dry_gain),   AV_OPT_TYPE_FLOAT, {.dbl=1},    0, 10, AF },
747     { "wet",    "set wet gain",      OFFSET(wet_gain),   AV_OPT_TYPE_FLOAT, {.dbl=1},    0, 10, AF },
748     { "length", "set IR length",     OFFSET(length),     AV_OPT_TYPE_FLOAT, {.dbl=1},    0,  1, AF },
749     { "gtype",  "set IR auto gain type",OFFSET(gtype),   AV_OPT_TYPE_INT,   {.i64=0},   -1,  2, AF, "gtype" },
750     {  "none",  "without auto gain", 0,                  AV_OPT_TYPE_CONST, {.i64=-1},   0,  0, AF, "gtype" },
751     {  "peak",  "peak gain",         0,                  AV_OPT_TYPE_CONST, {.i64=0},    0,  0, AF, "gtype" },
752     {  "dc",    "DC gain",           0,                  AV_OPT_TYPE_CONST, {.i64=1},    0,  0, AF, "gtype" },
753     {  "gn",    "gain to noise",     0,                  AV_OPT_TYPE_CONST, {.i64=2},    0,  0, AF, "gtype" },
754     { "irgain", "set IR gain",       OFFSET(ir_gain),    AV_OPT_TYPE_FLOAT, {.dbl=1},    0,  1, AF },
755     { "irfmt",  "set IR format",     OFFSET(ir_format),  AV_OPT_TYPE_INT,   {.i64=1},    0,  1, AF, "irfmt" },
756     {  "mono",  "single channel",    0,                  AV_OPT_TYPE_CONST, {.i64=0},    0,  0, AF, "irfmt" },
757     {  "input", "same as input",     0,                  AV_OPT_TYPE_CONST, {.i64=1},    0,  0, AF, "irfmt" },
758     { "maxir",  "set max IR length", OFFSET(max_ir_len), AV_OPT_TYPE_FLOAT, {.dbl=30}, 0.1, 60, AF },
759     { "response", "show IR frequency response", OFFSET(response), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, VF },
760     { "channel", "set IR channel to display frequency response", OFFSET(ir_channel), AV_OPT_TYPE_INT, {.i64=0}, 0, 1024, VF },
761     { "size",   "set video size",    OFFSET(w),          AV_OPT_TYPE_IMAGE_SIZE, {.str = "hd720"}, 0, 0, VF },
762     { "rate",   "set video rate",    OFFSET(frame_rate), AV_OPT_TYPE_VIDEO_RATE, {.str = "25"}, 0, INT32_MAX, VF },
763     { "minp",   "set min partition size", OFFSET(minp),  AV_OPT_TYPE_INT,   {.i64=16},    16, 65536, AF },
764     { "maxp",   "set max partition size", OFFSET(maxp),  AV_OPT_TYPE_INT,   {.i64=65536}, 16, 65536, AF },
765     { NULL }
766 };
767
768 AVFILTER_DEFINE_CLASS(afir);
769
770 AVFilter ff_af_afir = {
771     .name          = "afir",
772     .description   = NULL_IF_CONFIG_SMALL("Apply Finite Impulse Response filter with supplied coefficients in 2nd stream."),
773     .priv_size     = sizeof(AudioFIRContext),
774     .priv_class    = &afir_class,
775     .query_formats = query_formats,
776     .init          = init,
777     .activate      = activate,
778     .uninit        = uninit,
779     .inputs        = afir_inputs,
780     .flags         = AVFILTER_FLAG_DYNAMIC_OUTPUTS |
781                      AVFILTER_FLAG_SLICE_THREADS,
782 };