2 * Copyright (c) 2016 Muhammad Faiz <mfcc64@gmail.com>
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
21 #include "libavutil/opt.h"
22 #include "libavutil/eval.h"
23 #include "libavutil/avassert.h"
24 #include "libavcodec/avfft.h"
29 #define RDFT_BITS_MIN 4
30 #define RDFT_BITS_MAX 16
34 WFUNC_RECTANGULAR = WFUNC_MIN,
43 WFUNC_MAX = WFUNC_BHARRIS
46 #define NB_GAIN_ENTRY_MAX 4096
60 RDFTContext *analysis_irdft;
63 int analysis_rdft_len;
67 float *kernel_tmp_buf;
70 OverlapIndex *conv_idx;
74 int frame_nsamples_max;
80 const char *gain_entry;
90 GainEntry gain_entry_tbl[NB_GAIN_ENTRY_MAX];
91 } FIREqualizerContext;
93 #define OFFSET(x) offsetof(FIREqualizerContext, x)
94 #define FLAGS AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
96 static const AVOption firequalizer_options[] = {
97 { "gain", "set gain curve", OFFSET(gain), AV_OPT_TYPE_STRING, { .str = "gain_interpolate(f)" }, 0, 0, FLAGS },
98 { "gain_entry", "set gain entry", OFFSET(gain_entry), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, FLAGS },
99 { "delay", "set delay", OFFSET(delay), AV_OPT_TYPE_DOUBLE, { .dbl = 0.01 }, 0.0, 1e10, FLAGS },
100 { "accuracy", "set accuracy", OFFSET(accuracy), AV_OPT_TYPE_DOUBLE, { .dbl = 5.0 }, 0.0, 1e10, FLAGS },
101 { "wfunc", "set window function", OFFSET(wfunc), AV_OPT_TYPE_INT, { .i64 = WFUNC_HANN }, WFUNC_MIN, WFUNC_MAX, FLAGS, "wfunc" },
102 { "rectangular", "rectangular window", 0, AV_OPT_TYPE_CONST, { .i64 = WFUNC_RECTANGULAR }, 0, 0, FLAGS, "wfunc" },
103 { "hann", "hann window", 0, AV_OPT_TYPE_CONST, { .i64 = WFUNC_HANN }, 0, 0, FLAGS, "wfunc" },
104 { "hamming", "hamming window", 0, AV_OPT_TYPE_CONST, { .i64 = WFUNC_HAMMING }, 0, 0, FLAGS, "wfunc" },
105 { "blackman", "blackman window", 0, AV_OPT_TYPE_CONST, { .i64 = WFUNC_BLACKMAN }, 0, 0, FLAGS, "wfunc" },
106 { "nuttall3", "3-term nuttall window", 0, AV_OPT_TYPE_CONST, { .i64 = WFUNC_NUTTALL3 }, 0, 0, FLAGS, "wfunc" },
107 { "mnuttall3", "minimum 3-term nuttall window", 0, AV_OPT_TYPE_CONST, { .i64 = WFUNC_MNUTTALL3 }, 0, 0, FLAGS, "wfunc" },
108 { "nuttall", "nuttall window", 0, AV_OPT_TYPE_CONST, { .i64 = WFUNC_NUTTALL }, 0, 0, FLAGS, "wfunc" },
109 { "bnuttall", "blackman-nuttall window", 0, AV_OPT_TYPE_CONST, { .i64 = WFUNC_BNUTTALL }, 0, 0, FLAGS, "wfunc" },
110 { "bharris", "blackman-harris window", 0, AV_OPT_TYPE_CONST, { .i64 = WFUNC_BHARRIS }, 0, 0, FLAGS, "wfunc" },
111 { "fixed", "set fixed frame samples", OFFSET(fixed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
112 { "multi", "set multi channels mode", OFFSET(multi), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
113 { "zero_phase", "set zero phase mode", OFFSET(zero_phase), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, FLAGS },
117 AVFILTER_DEFINE_CLASS(firequalizer);
119 static void common_uninit(FIREqualizerContext *s)
121 av_rdft_end(s->analysis_irdft);
122 av_rdft_end(s->rdft);
123 av_rdft_end(s->irdft);
124 s->analysis_irdft = s->rdft = s->irdft = NULL;
126 av_freep(&s->analysis_buf);
127 av_freep(&s->kernel_tmp_buf);
128 av_freep(&s->kernel_buf);
129 av_freep(&s->conv_buf);
130 av_freep(&s->conv_idx);
133 static av_cold void uninit(AVFilterContext *ctx)
135 FIREqualizerContext *s = ctx->priv;
138 av_freep(&s->gain_cmd);
139 av_freep(&s->gain_entry_cmd);
142 static int query_formats(AVFilterContext *ctx)
144 AVFilterChannelLayouts *layouts;
145 AVFilterFormats *formats;
146 static const enum AVSampleFormat sample_fmts[] = {
152 layouts = ff_all_channel_counts();
154 return AVERROR(ENOMEM);
155 ret = ff_set_common_channel_layouts(ctx, layouts);
159 formats = ff_make_format_list(sample_fmts);
161 return AVERROR(ENOMEM);
162 ret = ff_set_common_formats(ctx, formats);
166 formats = ff_all_samplerates();
168 return AVERROR(ENOMEM);
169 return ff_set_common_samplerates(ctx, formats);
172 static void fast_convolute(FIREqualizerContext *s, const float *kernel_buf, float *conv_buf,
173 OverlapIndex *idx, float *data, int nsamples)
175 if (nsamples <= s->nsamples_max) {
176 float *buf = conv_buf + idx->buf_idx * s->rdft_len;
177 float *obuf = conv_buf + !idx->buf_idx * s->rdft_len + idx->overlap_idx;
180 memcpy(buf, data, nsamples * sizeof(*data));
181 memset(buf + nsamples, 0, (s->rdft_len - nsamples) * sizeof(*data));
182 av_rdft_calc(s->rdft, buf);
184 buf[0] *= kernel_buf[0];
185 buf[1] *= kernel_buf[1];
186 for (k = 2; k < s->rdft_len; k += 2) {
188 re = buf[k] * kernel_buf[k] - buf[k+1] * kernel_buf[k+1];
189 im = buf[k] * kernel_buf[k+1] + buf[k+1] * kernel_buf[k];
194 av_rdft_calc(s->irdft, buf);
195 for (k = 0; k < s->rdft_len - idx->overlap_idx; k++)
197 memcpy(data, buf, nsamples * sizeof(*data));
198 idx->buf_idx = !idx->buf_idx;
199 idx->overlap_idx = nsamples;
201 while (nsamples > s->nsamples_max * 2) {
202 fast_convolute(s, kernel_buf, conv_buf, idx, data, s->nsamples_max);
203 data += s->nsamples_max;
204 nsamples -= s->nsamples_max;
206 fast_convolute(s, kernel_buf, conv_buf, idx, data, nsamples/2);
207 fast_convolute(s, kernel_buf, conv_buf, idx, data + nsamples/2, nsamples - nsamples/2);
211 static double entry_func(void *p, double freq, double gain)
213 AVFilterContext *ctx = p;
214 FIREqualizerContext *s = ctx->priv;
216 if (s->nb_gain_entry >= NB_GAIN_ENTRY_MAX) {
217 av_log(ctx, AV_LOG_ERROR, "entry table overflow.\n");
218 s->gain_entry_err = AVERROR(EINVAL);
223 av_log(ctx, AV_LOG_ERROR, "nan frequency (%g, %g).\n", freq, gain);
224 s->gain_entry_err = AVERROR(EINVAL);
228 if (s->nb_gain_entry > 0 && freq <= s->gain_entry_tbl[s->nb_gain_entry - 1].freq) {
229 av_log(ctx, AV_LOG_ERROR, "unsorted frequency (%g, %g).\n", freq, gain);
230 s->gain_entry_err = AVERROR(EINVAL);
234 s->gain_entry_tbl[s->nb_gain_entry].freq = freq;
235 s->gain_entry_tbl[s->nb_gain_entry].gain = gain;
240 static int gain_entry_compare(const void *key, const void *memb)
242 const double *freq = key;
243 const GainEntry *entry = memb;
245 if (*freq < entry[0].freq)
247 if (*freq > entry[1].freq)
252 static double gain_interpolate_func(void *p, double freq)
254 AVFilterContext *ctx = p;
255 FIREqualizerContext *s = ctx->priv;
262 if (!s->nb_gain_entry)
265 if (freq <= s->gain_entry_tbl[0].freq)
266 return s->gain_entry_tbl[0].gain;
268 if (freq >= s->gain_entry_tbl[s->nb_gain_entry-1].freq)
269 return s->gain_entry_tbl[s->nb_gain_entry-1].gain;
271 res = bsearch(&freq, &s->gain_entry_tbl, s->nb_gain_entry - 1, sizeof(*res), gain_entry_compare);
274 d = res[1].freq - res[0].freq;
275 d0 = freq - res[0].freq;
276 d1 = res[1].freq - freq;
279 return (d0 * res[1].gain + d1 * res[0].gain) / d;
287 static const char *const var_names[] = {
307 static int generate_kernel(AVFilterContext *ctx, const char *gain, const char *gain_entry)
309 FIREqualizerContext *s = ctx->priv;
310 AVFilterLink *inlink = ctx->inputs[0];
311 const char *gain_entry_func_names[] = { "entry", NULL };
312 const char *gain_func_names[] = { "gain_interpolate", NULL };
313 double (*gain_entry_funcs[])(void *, double, double) = { entry_func, NULL };
314 double (*gain_funcs[])(void *, double) = { gain_interpolate_func, NULL };
317 int ret, k, center, ch;
319 s->nb_gain_entry = 0;
320 s->gain_entry_err = 0;
323 ret = av_expr_parse_and_eval(&result, gain_entry, NULL, NULL, NULL, NULL,
324 gain_entry_func_names, gain_entry_funcs, ctx, 0, ctx);
327 if (s->gain_entry_err < 0)
328 return s->gain_entry_err;
331 av_log(ctx, AV_LOG_DEBUG, "nb_gain_entry = %d.\n", s->nb_gain_entry);
333 ret = av_expr_parse(&gain_expr, gain, var_names,
334 gain_func_names, gain_funcs, NULL, NULL, 0, ctx);
338 vars[VAR_CHS] = inlink->channels;
339 vars[VAR_CHLAYOUT] = inlink->channel_layout;
340 vars[VAR_SR] = inlink->sample_rate;
341 for (ch = 0; ch < inlink->channels; ch++) {
343 vars[VAR_CHID] = av_channel_layout_extract_channel(inlink->channel_layout, ch);
345 s->analysis_buf[0] = pow(10.0, 0.05 * av_expr_eval(gain_expr, vars, ctx));
346 vars[VAR_F] = 0.5 * inlink->sample_rate;
347 s->analysis_buf[1] = pow(10.0, 0.05 * av_expr_eval(gain_expr, vars, ctx));
349 for (k = 1; k < s->analysis_rdft_len/2; k++) {
350 vars[VAR_F] = k * ((double)inlink->sample_rate /(double)s->analysis_rdft_len);
351 s->analysis_buf[2*k] = pow(10.0, 0.05 * av_expr_eval(gain_expr, vars, ctx));
352 s->analysis_buf[2*k+1] = 0.0;
355 av_rdft_calc(s->analysis_irdft, s->analysis_buf);
356 center = s->fir_len / 2;
358 for (k = 0; k <= center; k++) {
359 double u = k * (M_PI/center);
362 case WFUNC_RECTANGULAR:
366 win = 0.5 + 0.5 * cos(u);
369 win = 0.53836 + 0.46164 * cos(u);
372 win = 0.48 + 0.5 * cos(u) + 0.02 * cos(2*u);
375 win = 0.40897 + 0.5 * cos(u) + 0.09103 * cos(2*u);
377 case WFUNC_MNUTTALL3:
378 win = 0.4243801 + 0.4973406 * cos(u) + 0.0782793 * cos(2*u);
381 win = 0.355768 + 0.487396 * cos(u) + 0.144232 * cos(2*u) + 0.012604 * cos(3*u);
384 win = 0.3635819 + 0.4891775 * cos(u) + 0.1365995 * cos(2*u) + 0.0106411 * cos(3*u);
387 win = 0.35875 + 0.48829 * cos(u) + 0.14128 * cos(2*u) + 0.01168 * cos(3*u);
392 s->analysis_buf[k] *= (2.0/s->analysis_rdft_len) * (2.0/s->rdft_len) * win;
395 for (k = 0; k < center - k; k++) {
396 float tmp = s->analysis_buf[k];
397 s->analysis_buf[k] = s->analysis_buf[center - k];
398 s->analysis_buf[center - k] = tmp;
401 for (k = 1; k <= center; k++)
402 s->analysis_buf[center + k] = s->analysis_buf[center - k];
404 memset(s->analysis_buf + s->fir_len, 0, (s->rdft_len - s->fir_len) * sizeof(*s->analysis_buf));
405 av_rdft_calc(s->rdft, s->analysis_buf);
407 for (k = 0; k < s->rdft_len; k++) {
408 if (isnan(s->analysis_buf[k]) || isinf(s->analysis_buf[k])) {
409 av_log(ctx, AV_LOG_ERROR, "filter kernel contains nan or infinity.\n");
410 av_expr_free(gain_expr);
411 return AVERROR(EINVAL);
415 memcpy(s->kernel_tmp_buf + ch * s->rdft_len, s->analysis_buf, s->rdft_len * sizeof(*s->analysis_buf));
420 memcpy(s->kernel_buf, s->kernel_tmp_buf, (s->multi ? inlink->channels : 1) * s->rdft_len * sizeof(*s->kernel_buf));
421 av_expr_free(gain_expr);
425 static int config_input(AVFilterLink *inlink)
427 AVFilterContext *ctx = inlink->dst;
428 FIREqualizerContext *s = ctx->priv;
434 s->frame_nsamples_max = 0;
436 s->fir_len = FFMAX(2 * (int)(inlink->sample_rate * s->delay) + 1, 3);
437 s->remaining = s->fir_len - 1;
439 for (rdft_bits = RDFT_BITS_MIN; rdft_bits <= RDFT_BITS_MAX; rdft_bits++) {
440 s->rdft_len = 1 << rdft_bits;
441 s->nsamples_max = s->rdft_len - s->fir_len + 1;
442 if (s->nsamples_max * 2 >= s->fir_len)
446 if (rdft_bits > RDFT_BITS_MAX) {
447 av_log(ctx, AV_LOG_ERROR, "too large delay, please decrease it.\n");
448 return AVERROR(EINVAL);
451 if (!(s->rdft = av_rdft_init(rdft_bits, DFT_R2C)) || !(s->irdft = av_rdft_init(rdft_bits, IDFT_C2R)))
452 return AVERROR(ENOMEM);
454 for ( ; rdft_bits <= RDFT_BITS_MAX; rdft_bits++) {
455 s->analysis_rdft_len = 1 << rdft_bits;
456 if (inlink->sample_rate <= s->accuracy * s->analysis_rdft_len)
460 if (rdft_bits > RDFT_BITS_MAX) {
461 av_log(ctx, AV_LOG_ERROR, "too small accuracy, please increase it.\n");
462 return AVERROR(EINVAL);
465 if (!(s->analysis_irdft = av_rdft_init(rdft_bits, IDFT_C2R)))
466 return AVERROR(ENOMEM);
468 s->analysis_buf = av_malloc_array(s->analysis_rdft_len, sizeof(*s->analysis_buf));
469 s->kernel_tmp_buf = av_malloc_array(s->rdft_len * (s->multi ? inlink->channels : 1), sizeof(*s->kernel_tmp_buf));
470 s->kernel_buf = av_malloc_array(s->rdft_len * (s->multi ? inlink->channels : 1), sizeof(*s->kernel_buf));
471 s->conv_buf = av_calloc(2 * s->rdft_len * inlink->channels, sizeof(*s->conv_buf));
472 s->conv_idx = av_calloc(inlink->channels, sizeof(*s->conv_idx));
473 if (!s->analysis_buf || !s->kernel_tmp_buf || !s->kernel_buf || !s->conv_buf || !s->conv_idx)
474 return AVERROR(ENOMEM);
476 av_log(ctx, AV_LOG_DEBUG, "sample_rate = %d, channels = %d, analysis_rdft_len = %d, rdft_len = %d, fir_len = %d, nsamples_max = %d.\n",
477 inlink->sample_rate, inlink->channels, s->analysis_rdft_len, s->rdft_len, s->fir_len, s->nsamples_max);
480 inlink->min_samples = inlink->max_samples = inlink->partial_buf_size = s->nsamples_max;
482 return generate_kernel(ctx, s->gain_cmd ? s->gain_cmd : s->gain,
483 s->gain_entry_cmd ? s->gain_entry_cmd : s->gain_entry);
486 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
488 AVFilterContext *ctx = inlink->dst;
489 FIREqualizerContext *s = ctx->priv;
492 for (ch = 0; ch < inlink->channels; ch++) {
493 fast_convolute(s, s->kernel_buf + (s->multi ? ch * s->rdft_len : 0),
494 s->conv_buf + 2 * ch * s->rdft_len, s->conv_idx + ch,
495 (float *) frame->extended_data[ch], frame->nb_samples);
498 s->next_pts = AV_NOPTS_VALUE;
499 if (frame->pts != AV_NOPTS_VALUE) {
500 s->next_pts = frame->pts + av_rescale_q(frame->nb_samples, av_make_q(1, inlink->sample_rate), inlink->time_base);
502 frame->pts -= av_rescale_q(s->fir_len/2, av_make_q(1, inlink->sample_rate), inlink->time_base);
504 s->frame_nsamples_max = FFMAX(s->frame_nsamples_max, frame->nb_samples);
505 return ff_filter_frame(ctx->outputs[0], frame);
508 static int request_frame(AVFilterLink *outlink)
510 AVFilterContext *ctx = outlink->src;
511 FIREqualizerContext *s= ctx->priv;
514 ret = ff_request_frame(ctx->inputs[0]);
515 if (ret == AVERROR_EOF && s->remaining > 0 && s->frame_nsamples_max > 0) {
516 AVFrame *frame = ff_get_audio_buffer(outlink, FFMIN(s->remaining, s->frame_nsamples_max));
519 return AVERROR(ENOMEM);
521 av_samples_set_silence(frame->extended_data, 0, frame->nb_samples, outlink->channels, frame->format);
522 frame->pts = s->next_pts;
523 s->remaining -= frame->nb_samples;
524 ret = filter_frame(ctx->inputs[0], frame);
530 static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
531 char *res, int res_len, int flags)
533 FIREqualizerContext *s = ctx->priv;
534 int ret = AVERROR(ENOSYS);
536 if (!strcmp(cmd, "gain")) {
539 gain_cmd = av_strdup(args);
541 return AVERROR(ENOMEM);
543 ret = generate_kernel(ctx, gain_cmd, s->gain_entry_cmd ? s->gain_entry_cmd : s->gain_entry);
545 av_freep(&s->gain_cmd);
546 s->gain_cmd = gain_cmd;
550 } else if (!strcmp(cmd, "gain_entry")) {
551 char *gain_entry_cmd;
553 gain_entry_cmd = av_strdup(args);
555 return AVERROR(ENOMEM);
557 ret = generate_kernel(ctx, s->gain_cmd ? s->gain_cmd : s->gain, gain_entry_cmd);
559 av_freep(&s->gain_entry_cmd);
560 s->gain_entry_cmd = gain_entry_cmd;
562 av_freep(&gain_entry_cmd);
569 static const AVFilterPad firequalizer_inputs[] = {
572 .config_props = config_input,
573 .filter_frame = filter_frame,
574 .type = AVMEDIA_TYPE_AUDIO,
580 static const AVFilterPad firequalizer_outputs[] = {
583 .request_frame = request_frame,
584 .type = AVMEDIA_TYPE_AUDIO,
589 AVFilter ff_af_firequalizer = {
590 .name = "firequalizer",
591 .description = NULL_IF_CONFIG_SMALL("Finite Impulse Response Equalizer."),
593 .query_formats = query_formats,
594 .process_command = process_command,
595 .priv_size = sizeof(FIREqualizerContext),
596 .inputs = firequalizer_inputs,
597 .outputs = firequalizer_outputs,
598 .priv_class = &firequalizer_class,