2 * Copyright (c) 2017 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 * An arbitrary audio FIR filter
28 #include "libavutil/audio_fifo.h"
29 #include "libavutil/common.h"
30 #include "libavutil/float_dsp.h"
31 #include "libavutil/intreadwrite.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/xga_font_data.h"
34 #include "libavcodec/avfft.h"
43 static void fcmul_add_c(float *sum, const float *t, const float *c, ptrdiff_t len)
47 for (n = 0; n < len; n++) {
48 const float cre = c[2 * n ];
49 const float cim = c[2 * n + 1];
50 const float tre = t[2 * n ];
51 const float tim = t[2 * n + 1];
53 sum[2 * n ] += tre * cre - tim * cim;
54 sum[2 * n + 1] += tre * cim + tim * cre;
57 sum[2 * n] += t[2 * n] * c[2 * n];
60 static int fir_channel(AVFilterContext *ctx, void *arg, int ch, int nb_jobs)
62 AudioFIRContext *s = ctx->priv;
63 const float *src = (const float *)s->in[0]->extended_data[ch];
64 int index1 = (s->index + 1) % 3;
65 int index2 = (s->index + 2) % 3;
66 float *sum = s->sum[ch];
72 memset(sum, 0, sizeof(*sum) * s->fft_length);
73 block = s->block[ch] + s->part_index * s->block_size;
74 memset(block, 0, sizeof(*block) * s->fft_length);
76 s->fdsp->vector_fmul_scalar(block + s->part_size, src, s->dry_gain, FFALIGN(s->nb_samples, 4));
79 av_rdft_calc(s->rdft[ch], block);
80 block[2 * s->part_size] = block[1];
85 for (i = 0; i < s->nb_partitions; i++) {
86 const int coffset = i * s->coeff_size;
87 const FFTComplex *coeff = s->coeff[ch * !s->one2many] + coffset;
89 block = s->block[ch] + j * s->block_size;
90 s->fcmul_add(sum, block, (const float *)coeff, s->part_size);
97 sum[1] = sum[2 * s->part_size];
98 av_rdft_calc(s->irdft[ch], sum);
100 dst = (float *)s->buffer->extended_data[ch] + index1 * s->part_size;
101 for (n = 0; n < s->part_size; n++) {
105 dst = (float *)s->buffer->extended_data[ch] + index2 * s->part_size;
107 memcpy(dst, sum + s->part_size, s->part_size * sizeof(*dst));
109 dst = (float *)s->buffer->extended_data[ch] + s->index * s->part_size;
112 float *ptr = (float *)out->extended_data[ch];
113 s->fdsp->vector_fmul_scalar(ptr, dst, s->wet_gain, FFALIGN(out->nb_samples, 4));
120 static int fir_frame(AudioFIRContext *s, AVFrame *in, AVFilterLink *outlink)
122 AVFilterContext *ctx = outlink->src;
126 s->nb_samples = in->nb_samples;
129 out = ff_get_audio_buffer(outlink, s->nb_samples);
131 return AVERROR(ENOMEM);
134 if (s->pts == AV_NOPTS_VALUE)
137 ctx->internal->execute(ctx, fir_channel, out, NULL, outlink->channels);
139 s->part_index = (s->part_index + 1) % s->nb_partitions;
143 if (s->pts != AV_NOPTS_VALUE)
144 s->pts += av_rescale_q(out->nb_samples, (AVRational){1, outlink->sample_rate}, outlink->time_base);
153 if (s->want_skip == 1) {
157 ret = ff_filter_frame(outlink, out);
163 static void drawtext(AVFrame *pic, int x, int y, const char *txt, uint32_t color)
169 font = avpriv_cga_font, font_height = 8;
171 for (i = 0; txt[i]; i++) {
174 uint8_t *p = pic->data[0] + y * pic->linesize[0] + (x + i * 8) * 4;
175 for (char_y = 0; char_y < font_height; char_y++) {
176 for (mask = 0x80; mask; mask >>= 1) {
177 if (font[txt[i] * font_height + char_y] & mask)
181 p += pic->linesize[0] - 8 * 4;
186 static void draw_line(AVFrame *out, int x0, int y0, int x1, int y1, uint32_t color)
188 int dx = FFABS(x1-x0);
189 int dy = FFABS(y1-y0), sy = y0 < y1 ? 1 : -1;
190 int err = (dx>dy ? dx : -dy) / 2, e2;
193 AV_WL32(out->data[0] + y0 * out->linesize[0] + x0 * 4, color);
195 if (x0 == x1 && y0 == y1)
212 static void draw_response(AVFilterContext *ctx, AVFrame *out)
214 AudioFIRContext *s = ctx->priv;
215 float *mag, *phase, min = FLT_MAX, max = FLT_MIN;
216 int prev_ymag = -1, prev_yphase = -1;
220 memset(out->data[0], 0, s->h * out->linesize[0]);
222 phase = av_malloc_array(s->w, sizeof(*phase));
223 mag = av_malloc_array(s->w, sizeof(*mag));
227 channel = av_clip(s->ir_channel, 0, s->in[1]->channels - 1);
228 for (i = 0; i < s->w; i++) {
229 const float *src = (const float *)s->in[1]->extended_data[channel];
230 double w = i * M_PI / (s->w - 1);
234 for (x = 0; x < s->nb_taps; x++) {
235 real += cos(-x * w) * src[x];
236 imag += sin(-x * w) * src[x];
239 mag[i] = hypot(real, imag);
240 phase[i] = atan2(imag, real);
241 min = fminf(min, mag[i]);
242 max = fmaxf(max, mag[i]);
245 for (i = 0; i < s->w; i++) {
246 int ymag = mag[i] / max * (s->h - 1);
247 int yphase = (0.5 * (1. + phase[i] / M_PI)) * (s->h - 1);
249 ymag = s->h - 1 - av_clip(ymag, 0, s->h - 1);
250 yphase = s->h - 1 - av_clip(yphase, 0, s->h - 1);
255 prev_yphase = yphase;
257 draw_line(out, i, ymag, FFMAX(i - 1, 0), prev_ymag, 0xFFFF00FF);
258 draw_line(out, i, yphase, FFMAX(i - 1, 0), prev_yphase, 0xFF00FF00);
261 prev_yphase = yphase;
264 if (s->w > 400 && s->h > 100) {
265 drawtext(out, 2, 2, "Max Magnitude:", 0xDDDDDDDD);
266 snprintf(text, sizeof(text), "%.2f", max);
267 drawtext(out, 15 * 8 + 2, 2, text, 0xDDDDDDDD);
269 drawtext(out, 2, 12, "Min Magnitude:", 0xDDDDDDDD);
270 snprintf(text, sizeof(text), "%.2f", min);
271 drawtext(out, 15 * 8 + 2, 12, text, 0xDDDDDDDD);
279 static int convert_coeffs(AVFilterContext *ctx)
281 AudioFIRContext *s = ctx->priv;
285 s->nb_taps = av_audio_fifo_size(s->fifo);
287 return AVERROR(EINVAL);
289 for (n = 4; (1 << n) < s->nb_taps; n++);
291 s->ir_length = 1 << n;
292 s->fft_length = (1 << (N + 1)) + 1;
293 s->part_size = 1 << (N - 1);
294 s->block_size = FFALIGN(s->fft_length, 32);
295 s->coeff_size = FFALIGN(s->part_size + 1, 32);
296 s->nb_partitions = (s->nb_taps + s->part_size - 1) / s->part_size;
297 s->nb_coeffs = s->ir_length + s->nb_partitions;
299 for (ch = 0; ch < ctx->inputs[0]->channels; ch++) {
300 s->sum[ch] = av_calloc(s->fft_length, sizeof(**s->sum));
302 return AVERROR(ENOMEM);
305 for (ch = 0; ch < ctx->inputs[1]->channels; ch++) {
306 s->coeff[ch] = av_calloc(s->nb_partitions * s->coeff_size, sizeof(**s->coeff));
308 return AVERROR(ENOMEM);
311 for (ch = 0; ch < ctx->inputs[0]->channels; ch++) {
312 s->block[ch] = av_calloc(s->nb_partitions * s->block_size, sizeof(**s->block));
314 return AVERROR(ENOMEM);
317 for (ch = 0; ch < ctx->inputs[0]->channels; ch++) {
318 s->rdft[ch] = av_rdft_init(N, DFT_R2C);
319 s->irdft[ch] = av_rdft_init(N, IDFT_C2R);
320 if (!s->rdft[ch] || !s->irdft[ch])
321 return AVERROR(ENOMEM);
324 s->in[1] = ff_get_audio_buffer(ctx->inputs[1], s->nb_taps);
326 return AVERROR(ENOMEM);
328 s->buffer = ff_get_audio_buffer(ctx->inputs[0], s->part_size * 3);
330 return AVERROR(ENOMEM);
332 av_audio_fifo_read(s->fifo, (void **)s->in[1]->extended_data, s->nb_taps);
335 draw_response(ctx, s->video);
342 for (ch = 0; ch < ctx->inputs[1]->channels; ch++) {
343 float *time = (float *)s->in[1]->extended_data[!s->one2many * ch];
345 for (i = 0; i < s->nb_taps; i++)
346 power += FFABS(time[i]);
348 s->gain = ctx->inputs[1]->channels / power;
351 for (ch = 0; ch < ctx->inputs[1]->channels; ch++) {
352 float *time = (float *)s->in[1]->extended_data[!s->one2many * ch];
354 for (i = 0; i < s->nb_taps; i++)
357 s->gain = ctx->inputs[1]->channels / power;
360 for (ch = 0; ch < ctx->inputs[1]->channels; ch++) {
361 float *time = (float *)s->in[1]->extended_data[!s->one2many * ch];
363 for (i = 0; i < s->nb_taps; i++)
364 power += time[i] * time[i];
366 s->gain = sqrtf(ch / power);
373 s->gain = FFMIN(s->gain * s->ir_gain, 1.f);
374 av_log(ctx, AV_LOG_DEBUG, "power %f, gain %f\n", power, s->gain);
375 for (ch = 0; ch < ctx->inputs[1]->channels; ch++) {
376 float *time = (float *)s->in[1]->extended_data[!s->one2many * ch];
378 s->fdsp->vector_fmul_scalar(time, time, s->gain, FFALIGN(s->nb_taps, 4));
381 for (ch = 0; ch < ctx->inputs[1]->channels; ch++) {
382 float *time = (float *)s->in[1]->extended_data[!s->one2many * ch];
383 float *block = s->block[ch];
384 FFTComplex *coeff = s->coeff[ch];
386 for (i = FFMAX(1, s->length * s->nb_taps); i < s->nb_taps; i++)
389 for (i = 0; i < s->nb_partitions; i++) {
390 const float scale = 1.f / s->part_size;
391 const int toffset = i * s->part_size;
392 const int coffset = i * s->coeff_size;
393 const int boffset = s->part_size;
394 const int remaining = s->nb_taps - (i * s->part_size);
395 const int size = remaining >= s->part_size ? s->part_size : remaining;
397 memset(block, 0, sizeof(*block) * s->fft_length);
398 memcpy(block + boffset, time + toffset, size * sizeof(*block));
400 av_rdft_calc(s->rdft[0], block);
402 coeff[coffset].re = block[0] * scale;
403 coeff[coffset].im = 0;
404 for (n = 1; n < s->part_size; n++) {
405 coeff[coffset + n].re = block[2 * n] * scale;
406 coeff[coffset + n].im = block[2 * n + 1] * scale;
408 coeff[coffset + s->part_size].re = block[1] * scale;
409 coeff[coffset + s->part_size].im = 0;
413 av_frame_free(&s->in[1]);
414 av_log(ctx, AV_LOG_DEBUG, "nb_taps: %d\n", s->nb_taps);
415 av_log(ctx, AV_LOG_DEBUG, "nb_partitions: %d\n", s->nb_partitions);
416 av_log(ctx, AV_LOG_DEBUG, "partition size: %d\n", s->part_size);
417 av_log(ctx, AV_LOG_DEBUG, "ir_length: %d\n", s->ir_length);
424 static int read_ir(AVFilterLink *link, AVFrame *frame)
426 AVFilterContext *ctx = link->dst;
427 AudioFIRContext *s = ctx->priv;
428 int nb_taps, max_nb_taps, ret;
430 ret = av_audio_fifo_write(s->fifo, (void **)frame->extended_data,
432 av_frame_free(&frame);
436 nb_taps = av_audio_fifo_size(s->fifo);
437 max_nb_taps = s->max_ir_len * ctx->outputs[0]->sample_rate;
438 if (nb_taps > max_nb_taps) {
439 av_log(ctx, AV_LOG_ERROR, "Too big number of coefficients: %d > %d.\n", nb_taps, max_nb_taps);
440 return AVERROR(EINVAL);
446 static int activate(AVFilterContext *ctx)
448 AudioFIRContext *s = ctx->priv;
449 AVFilterLink *outlink = ctx->outputs[0];
454 FF_FILTER_FORWARD_STATUS_BACK_ALL(ctx->outputs[0], ctx);
456 FF_FILTER_FORWARD_STATUS_BACK_ALL(ctx->outputs[1], ctx);
457 if (!s->eof_coeffs) {
460 if ((ret = ff_inlink_consume_frame(ctx->inputs[1], &ir)) > 0) {
461 ret = read_ir(ctx->inputs[1], ir);
468 if (ff_inlink_acknowledge_status(ctx->inputs[1], &status, &pts)) {
469 if (status == AVERROR_EOF) {
474 if (!s->eof_coeffs) {
475 if (ff_outlink_frame_wanted(ctx->outputs[0]))
476 ff_inlink_request_frame(ctx->inputs[1]);
481 if (!s->have_coeffs && s->eof_coeffs) {
482 ret = convert_coeffs(ctx);
487 if (s->need_padding) {
488 in = ff_get_audio_buffer(outlink, s->part_size);
490 return AVERROR(ENOMEM);
494 ret = ff_inlink_consume_samples(ctx->inputs[0], s->part_size, s->part_size, &in);
498 ret = fir_frame(s, in, outlink);
506 if (s->response && s->have_coeffs) {
507 if (ff_outlink_frame_wanted(ctx->outputs[1])) {
508 s->video->pts = s->pts;
509 ret = ff_filter_frame(ctx->outputs[1], av_frame_clone(s->video));
515 if (ff_inlink_acknowledge_status(ctx->inputs[0], &status, &pts)) {
516 if (status == AVERROR_EOF) {
517 ff_outlink_set_status(ctx->outputs[0], status, pts);
519 ff_outlink_set_status(ctx->outputs[1], status, pts);
524 if (ff_outlink_frame_wanted(ctx->outputs[0])) {
525 ff_inlink_request_frame(ctx->inputs[0]);
529 if (s->response && ff_outlink_frame_wanted(ctx->outputs[1])) {
530 ff_inlink_request_frame(ctx->inputs[0]);
537 static int query_formats(AVFilterContext *ctx)
539 AudioFIRContext *s = ctx->priv;
540 AVFilterFormats *formats;
541 AVFilterChannelLayouts *layouts;
542 static const enum AVSampleFormat sample_fmts[] = {
546 static const enum AVPixelFormat pix_fmts[] = {
553 AVFilterLink *videolink = ctx->outputs[1];
554 formats = ff_make_format_list(pix_fmts);
555 if ((ret = ff_formats_ref(formats, &videolink->in_formats)) < 0)
559 layouts = ff_all_channel_counts();
560 if ((ret = ff_channel_layouts_ref(layouts, &ctx->outputs[0]->in_channel_layouts)) < 0)
563 for (i = 0; i < 2; i++) {
564 layouts = ff_all_channel_counts();
565 if ((ret = ff_channel_layouts_ref(layouts, &ctx->inputs[i]->out_channel_layouts)) < 0)
569 formats = ff_make_format_list(sample_fmts);
570 if ((ret = ff_set_common_formats(ctx, formats)) < 0)
573 formats = ff_all_samplerates();
574 return ff_set_common_samplerates(ctx, formats);
577 static int config_output(AVFilterLink *outlink)
579 AVFilterContext *ctx = outlink->src;
580 AudioFIRContext *s = ctx->priv;
582 if (ctx->inputs[0]->channels != ctx->inputs[1]->channels &&
583 ctx->inputs[1]->channels != 1) {
584 av_log(ctx, AV_LOG_ERROR,
585 "Second input must have same number of channels as first input or "
586 "exactly 1 channel.\n");
587 return AVERROR(EINVAL);
590 s->one2many = ctx->inputs[1]->channels == 1;
591 outlink->sample_rate = ctx->inputs[0]->sample_rate;
592 outlink->time_base = ctx->inputs[0]->time_base;
593 outlink->channel_layout = ctx->inputs[0]->channel_layout;
594 outlink->channels = ctx->inputs[0]->channels;
596 s->fifo = av_audio_fifo_alloc(ctx->inputs[1]->format, ctx->inputs[1]->channels, 1024);
598 return AVERROR(ENOMEM);
600 s->sum = av_calloc(outlink->channels, sizeof(*s->sum));
601 s->coeff = av_calloc(ctx->inputs[1]->channels, sizeof(*s->coeff));
602 s->block = av_calloc(ctx->inputs[0]->channels, sizeof(*s->block));
603 s->rdft = av_calloc(outlink->channels, sizeof(*s->rdft));
604 s->irdft = av_calloc(outlink->channels, sizeof(*s->irdft));
605 if (!s->sum || !s->coeff || !s->block || !s->rdft || !s->irdft)
606 return AVERROR(ENOMEM);
608 s->nb_channels = outlink->channels;
609 s->nb_coef_channels = ctx->inputs[1]->channels;
612 s->pts = AV_NOPTS_VALUE;
617 static av_cold void uninit(AVFilterContext *ctx)
619 AudioFIRContext *s = ctx->priv;
623 for (ch = 0; ch < s->nb_channels; ch++) {
624 av_freep(&s->sum[ch]);
630 for (ch = 0; ch < s->nb_coef_channels; ch++) {
631 av_freep(&s->coeff[ch]);
637 for (ch = 0; ch < s->nb_channels; ch++) {
638 av_freep(&s->block[ch]);
644 for (ch = 0; ch < s->nb_channels; ch++) {
645 av_rdft_end(s->rdft[ch]);
651 for (ch = 0; ch < s->nb_channels; ch++) {
652 av_rdft_end(s->irdft[ch]);
657 av_frame_free(&s->in[1]);
658 av_frame_free(&s->buffer);
660 av_audio_fifo_free(s->fifo);
664 for (int i = 0; i < ctx->nb_outputs; i++)
665 av_freep(&ctx->output_pads[i].name);
666 av_frame_free(&s->video);
669 static int config_video(AVFilterLink *outlink)
671 AVFilterContext *ctx = outlink->src;
672 AudioFIRContext *s = ctx->priv;
674 outlink->sample_aspect_ratio = (AVRational){1,1};
678 av_frame_free(&s->video);
679 s->video = ff_get_video_buffer(outlink, outlink->w, outlink->h);
681 return AVERROR(ENOMEM);
686 static av_cold int init(AVFilterContext *ctx)
688 AudioFIRContext *s = ctx->priv;
689 AVFilterPad pad, vpad;
693 .name = av_strdup("default"),
694 .type = AVMEDIA_TYPE_AUDIO,
695 .config_props = config_output,
699 return AVERROR(ENOMEM);
702 vpad = (AVFilterPad){
703 .name = av_strdup("filter_response"),
704 .type = AVMEDIA_TYPE_VIDEO,
705 .config_props = config_video,
708 return AVERROR(ENOMEM);
711 ret = ff_insert_outpad(ctx, 0, &pad);
718 ret = ff_insert_outpad(ctx, 1, &vpad);
720 av_freep(&vpad.name);
725 s->fcmul_add = fcmul_add_c;
727 s->fdsp = avpriv_float_dsp_alloc(0);
729 return AVERROR(ENOMEM);
737 static const AVFilterPad afir_inputs[] = {
740 .type = AVMEDIA_TYPE_AUDIO,
743 .type = AVMEDIA_TYPE_AUDIO,
748 #define AF AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
749 #define VF AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
750 #define OFFSET(x) offsetof(AudioFIRContext, x)
752 static const AVOption afir_options[] = {
753 { "dry", "set dry gain", OFFSET(dry_gain), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 10, AF },
754 { "wet", "set wet gain", OFFSET(wet_gain), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 10, AF },
755 { "length", "set IR length", OFFSET(length), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 1, AF },
756 { "again", "enable auto gain", OFFSET(again), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1, AF },
757 { "gtype", "set auto gain type",OFFSET(gtype), AV_OPT_TYPE_INT, {.i64=0}, 0, 2, AF, "gtype" },
758 { "peak", "peak gain", 0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, AF, "gtype" },
759 { "dc", "DC gain", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, AF, "gtype" },
760 { "gn", "gain to noise", 0, AV_OPT_TYPE_CONST, {.i64=2}, 0, 0, AF, "gtype" },
761 { "irgain", "set IR gain", OFFSET(ir_gain), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0, 1, AF },
762 { "maxir", "set max IR length", OFFSET(max_ir_len), AV_OPT_TYPE_FLOAT, {.dbl=30}, 0.1, 60, AF },
763 { "response", "show IR frequency response", OFFSET(response), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, VF },
764 { "channel", "set IR channel to display frequency response", OFFSET(ir_channel), AV_OPT_TYPE_INT, {.i64=0}, 0, 1024, VF },
765 { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "hd720"}, 0, 0, VF },
769 AVFILTER_DEFINE_CLASS(afir);
771 AVFilter ff_af_afir = {
773 .description = NULL_IF_CONFIG_SMALL("Apply Finite Impulse Response filter with supplied coefficients in 2nd stream."),
774 .priv_size = sizeof(AudioFIRContext),
775 .priv_class = &afir_class,
776 .query_formats = query_formats,
778 .activate = activate,
780 .inputs = afir_inputs,
781 .flags = AVFILTER_FLAG_DYNAMIC_OUTPUTS |
782 AVFILTER_FLAG_SLICE_THREADS,