]> git.sesse.net Git - ffmpeg/blob - libavfilter/af_afftfilt.c
avfilter/af_afftfilt: calculate all channels FFT values upfront
[ffmpeg] / libavfilter / af_afftfilt.c
1 /*
2  * Copyright (c) 2016 Paul B Mahol
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU Lesser General Public License as published
8  * by the Free Software Foundation; either version 2.1 of the License,
9  * 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 "libavutil/audio_fifo.h"
22 #include "libavutil/avstring.h"
23 #include "libavfilter/internal.h"
24 #include "libavutil/common.h"
25 #include "libavutil/opt.h"
26 #include "libavcodec/avfft.h"
27 #include "libavutil/eval.h"
28 #include "audio.h"
29 #include "window_func.h"
30
31 typedef struct AFFTFiltContext {
32     const AVClass *class;
33     char *real_str;
34     char *img_str;
35     int fft_bits;
36
37     FFTContext *fft, *ifft;
38     FFTComplex **fft_data;
39     FFTComplex **fft_temp;
40     int nb_exprs;
41     int window_size;
42     AVExpr **real;
43     AVExpr **imag;
44     AVAudioFifo *fifo;
45     int64_t pts;
46     int hop_size;
47     float overlap;
48     AVFrame *buffer;
49     int start, end;
50     int win_func;
51     float win_scale;
52     float *window_func_lut;
53 } AFFTFiltContext;
54
55 static const char *const var_names[] = {            "sr",     "b",       "nb",        "ch",        "chs",   "pts",     "re",     "im", NULL };
56 enum                                   { VAR_SAMPLE_RATE, VAR_BIN, VAR_NBBINS, VAR_CHANNEL, VAR_CHANNELS, VAR_PTS, VAR_REAL, VAR_IMAG, VAR_VARS_NB };
57
58 #define OFFSET(x) offsetof(AFFTFiltContext, x)
59 #define A AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
60
61 static const AVOption afftfilt_options[] = {
62     { "real", "set channels real expressions",       OFFSET(real_str), AV_OPT_TYPE_STRING, {.str = "re" }, 0, 0, A },
63     { "imag", "set channels imaginary expressions",  OFFSET(img_str),  AV_OPT_TYPE_STRING, {.str = "im" }, 0, 0, A },
64     { "win_size", "set window size", OFFSET(fft_bits), AV_OPT_TYPE_INT, {.i64=12}, 4, 17, A, "fft" },
65         { "w16",    0, 0, AV_OPT_TYPE_CONST, {.i64=4},  0, 0, A, "fft" },
66         { "w32",    0, 0, AV_OPT_TYPE_CONST, {.i64=5},  0, 0, A, "fft" },
67         { "w64",    0, 0, AV_OPT_TYPE_CONST, {.i64=6},  0, 0, A, "fft" },
68         { "w128",   0, 0, AV_OPT_TYPE_CONST, {.i64=7},  0, 0, A, "fft" },
69         { "w256",   0, 0, AV_OPT_TYPE_CONST, {.i64=8},  0, 0, A, "fft" },
70         { "w512",   0, 0, AV_OPT_TYPE_CONST, {.i64=9},  0, 0, A, "fft" },
71         { "w1024",  0, 0, AV_OPT_TYPE_CONST, {.i64=10}, 0, 0, A, "fft" },
72         { "w2048",  0, 0, AV_OPT_TYPE_CONST, {.i64=11}, 0, 0, A, "fft" },
73         { "w4096",  0, 0, AV_OPT_TYPE_CONST, {.i64=12}, 0, 0, A, "fft" },
74         { "w8192",  0, 0, AV_OPT_TYPE_CONST, {.i64=13}, 0, 0, A, "fft" },
75         { "w16384", 0, 0, AV_OPT_TYPE_CONST, {.i64=14}, 0, 0, A, "fft" },
76         { "w32768", 0, 0, AV_OPT_TYPE_CONST, {.i64=15}, 0, 0, A, "fft" },
77         { "w65536", 0, 0, AV_OPT_TYPE_CONST, {.i64=16}, 0, 0, A, "fft" },
78         { "w131072",0, 0, AV_OPT_TYPE_CONST, {.i64=17}, 0, 0, A, "fft" },
79     { "win_func", "set window function", OFFSET(win_func), AV_OPT_TYPE_INT, {.i64 = WFUNC_HANNING}, 0, NB_WFUNC-1, A, "win_func" },
80         { "rect",     "Rectangular",      0, AV_OPT_TYPE_CONST, {.i64=WFUNC_RECT},     0, 0, A, "win_func" },
81         { "bartlett", "Bartlett",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BARTLETT}, 0, 0, A, "win_func" },
82         { "hann",     "Hann",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, A, "win_func" },
83         { "hanning",  "Hanning",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, A, "win_func" },
84         { "hamming",  "Hamming",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HAMMING},  0, 0, A, "win_func" },
85         { "blackman", "Blackman",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BLACKMAN}, 0, 0, A, "win_func" },
86         { "welch",    "Welch",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_WELCH},    0, 0, A, "win_func" },
87         { "flattop",  "Flat-top",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_FLATTOP},  0, 0, A, "win_func" },
88         { "bharris",  "Blackman-Harris",  0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BHARRIS},  0, 0, A, "win_func" },
89         { "bnuttall", "Blackman-Nuttall", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BNUTTALL}, 0, 0, A, "win_func" },
90         { "bhann",    "Bartlett-Hann",    0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BHANN},    0, 0, A, "win_func" },
91         { "sine",     "Sine",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_SINE},     0, 0, A, "win_func" },
92         { "nuttall",  "Nuttall",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_NUTTALL},  0, 0, A, "win_func" },
93         { "lanczos",  "Lanczos",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_LANCZOS},  0, 0, A, "win_func" },
94         { "gauss",    "Gauss",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_GAUSS},    0, 0, A, "win_func" },
95         { "tukey",    "Tukey",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_TUKEY},    0, 0, A, "win_func" },
96         { "dolph",    "Dolph-Chebyshev",  0, AV_OPT_TYPE_CONST, {.i64=WFUNC_DOLPH},    0, 0, A, "win_func" },
97         { "cauchy",   "Cauchy",           0, AV_OPT_TYPE_CONST, {.i64=WFUNC_CAUCHY},   0, 0, A, "win_func" },
98         { "parzen",   "Parzen",           0, AV_OPT_TYPE_CONST, {.i64=WFUNC_PARZEN},   0, 0, A, "win_func" },
99         { "poisson",  "Poisson",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_POISSON},  0, 0, A, "win_func" },
100         { "bohman",   "Bohman",           0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BOHMAN},   0, 0, A, "win_func" },
101     { "overlap", "set window overlap", OFFSET(overlap), AV_OPT_TYPE_FLOAT, {.dbl=0.75}, 0,  1, A },
102     { NULL },
103 };
104
105 AVFILTER_DEFINE_CLASS(afftfilt);
106
107 static inline double getreal(void *priv, double x, double ch)
108 {
109     AFFTFiltContext *s = priv;
110     int ich, ix;
111
112     ich = av_clip(ch, 0, s->nb_exprs - 1);
113     ix = av_clip(x, 0, s->window_size / 2);
114
115     return s->fft_data[ich][ix].re;
116 }
117
118 static inline double getimag(void *priv, double x, double ch)
119 {
120     AFFTFiltContext *s = priv;
121     int ich, ix;
122
123     ich = av_clip(ch, 0, s->nb_exprs - 1);
124     ix = av_clip(x, 0, s->window_size / 2);
125
126     return s->fft_data[ich][ix].im;
127 }
128
129 static double realf(void *priv, double x, double ch) { return getreal(priv, x, ch); }
130 static double imagf(void *priv, double x, double ch) { return getimag(priv, x, ch); }
131
132 static const char *const func2_names[]    = { "real", "imag", NULL };
133 double (*func2[])(void *, double, double) = {  realf,  imagf, NULL };
134
135 static int config_input(AVFilterLink *inlink)
136 {
137     AVFilterContext *ctx = inlink->dst;
138     AFFTFiltContext *s = ctx->priv;
139     char *saveptr = NULL;
140     int ret = 0, ch, i;
141     float overlap;
142     char *args;
143     const char *last_expr = "1";
144
145     s->fft  = av_fft_init(s->fft_bits, 0);
146     s->ifft = av_fft_init(s->fft_bits, 1);
147     if (!s->fft || !s->ifft)
148         return AVERROR(ENOMEM);
149
150     s->window_size = 1 << s->fft_bits;
151
152     s->fft_data = av_calloc(inlink->channels, sizeof(*s->fft_data));
153     if (!s->fft_data)
154         return AVERROR(ENOMEM);
155
156     s->fft_temp = av_calloc(inlink->channels, sizeof(*s->fft_temp));
157     if (!s->fft_temp)
158         return AVERROR(ENOMEM);
159
160     for (ch = 0; ch < inlink->channels; ch++) {
161         s->fft_data[ch] = av_calloc(s->window_size, sizeof(**s->fft_data));
162         if (!s->fft_data[ch])
163             return AVERROR(ENOMEM);
164     }
165
166     for (ch = 0; ch < inlink->channels; ch++) {
167         s->fft_temp[ch] = av_calloc(s->window_size, sizeof(**s->fft_temp));
168         if (!s->fft_temp[ch])
169             return AVERROR(ENOMEM);
170     }
171
172     s->real = av_calloc(inlink->channels, sizeof(*s->real));
173     if (!s->real)
174         return AVERROR(ENOMEM);
175
176     s->imag = av_calloc(inlink->channels, sizeof(*s->imag));
177     if (!s->imag)
178         return AVERROR(ENOMEM);
179
180     args = av_strdup(s->real_str);
181     if (!args)
182         return AVERROR(ENOMEM);
183
184     for (ch = 0; ch < inlink->channels; ch++) {
185         char *arg = av_strtok(ch == 0 ? args : NULL, "|", &saveptr);
186
187         ret = av_expr_parse(&s->real[ch], arg ? arg : last_expr, var_names,
188                             NULL, NULL, func2_names, func2, 0, ctx);
189         if (ret < 0)
190             break;
191         if (arg)
192             last_expr = arg;
193         s->nb_exprs++;
194     }
195
196     av_free(args);
197
198     args = av_strdup(s->img_str ? s->img_str : s->real_str);
199     if (!args)
200         return AVERROR(ENOMEM);
201
202     for (ch = 0; ch < inlink->channels; ch++) {
203         char *arg = av_strtok(ch == 0 ? args : NULL, "|", &saveptr);
204
205         ret = av_expr_parse(&s->imag[ch], arg ? arg : last_expr, var_names,
206                             NULL, NULL, func2_names, func2, 0, ctx);
207         if (ret < 0)
208             break;
209         if (arg)
210             last_expr = arg;
211     }
212
213     av_free(args);
214
215     s->fifo = av_audio_fifo_alloc(inlink->format, inlink->channels, s->window_size);
216     if (!s->fifo)
217         return AVERROR(ENOMEM);
218
219     s->window_func_lut = av_realloc_f(s->window_func_lut, s->window_size,
220                                       sizeof(*s->window_func_lut));
221     if (!s->window_func_lut)
222         return AVERROR(ENOMEM);
223     generate_window_func(s->window_func_lut, s->window_size, s->win_func, &overlap);
224     if (s->overlap == 1)
225         s->overlap = overlap;
226
227     for (s->win_scale = 0, i = 0; i < s->window_size; i++) {
228         s->win_scale += s->window_func_lut[i] * s->window_func_lut[i];
229     }
230
231     s->hop_size = s->window_size * (1 - s->overlap);
232     if (s->hop_size <= 0)
233         return AVERROR(EINVAL);
234
235     s->buffer = ff_get_audio_buffer(inlink, s->window_size * 2);
236     if (!s->buffer)
237         return AVERROR(ENOMEM);
238
239     return ret;
240 }
241
242 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
243 {
244     AVFilterContext *ctx = inlink->dst;
245     AVFilterLink *outlink = ctx->outputs[0];
246     AFFTFiltContext *s = ctx->priv;
247     const int window_size = s->window_size;
248     const float f = 1. / s->win_scale;
249     double values[VAR_VARS_NB];
250     AVFrame *out, *in = NULL;
251     int ch, n, ret, i, j, k;
252     int start = s->start, end = s->end;
253
254     ret = av_audio_fifo_write(s->fifo, (void **)frame->extended_data, frame->nb_samples);
255     av_frame_free(&frame);
256     if (ret < 0)
257         return ret;
258
259     while (av_audio_fifo_size(s->fifo) >= window_size) {
260         if (!in) {
261             in = ff_get_audio_buffer(outlink, window_size);
262             if (!in)
263                 return AVERROR(ENOMEM);
264         }
265
266         ret = av_audio_fifo_peek(s->fifo, (void **)in->extended_data, window_size);
267         if (ret < 0)
268             break;
269
270         for (ch = 0; ch < inlink->channels; ch++) {
271             const float *src = (float *)in->extended_data[ch];
272             FFTComplex *fft_data = s->fft_data[ch];
273
274             for (n = 0; n < in->nb_samples; n++) {
275                 fft_data[n].re = src[n] * s->window_func_lut[n];
276                 fft_data[n].im = 0;
277             }
278
279             for (; n < window_size; n++) {
280                 fft_data[n].re = 0;
281                 fft_data[n].im = 0;
282             }
283         }
284
285         values[VAR_PTS]         = s->pts;
286         values[VAR_SAMPLE_RATE] = inlink->sample_rate;
287         values[VAR_NBBINS]      = window_size / 2;
288         values[VAR_CHANNELS]    = inlink->channels;
289
290         for (ch = 0; ch < inlink->channels; ch++) {
291             FFTComplex *fft_data = s->fft_data[ch];
292
293             av_fft_permute(s->fft, fft_data);
294             av_fft_calc(s->fft, fft_data);
295         }
296
297         for (ch = 0; ch < inlink->channels; ch++) {
298             FFTComplex *fft_data = s->fft_data[ch];
299             FFTComplex *fft_temp = s->fft_temp[ch];
300             float *buf = (float *)s->buffer->extended_data[ch];
301             int x;
302             values[VAR_CHANNEL] = ch;
303
304             for (n = 0; n <= window_size / 2; n++) {
305                 float fr, fi;
306
307                 values[VAR_BIN] = n;
308                 values[VAR_REAL] = fft_data[n].re;
309                 values[VAR_IMAG] = fft_data[n].im;
310
311                 fr = av_expr_eval(s->real[ch], values, s);
312                 fi = av_expr_eval(s->imag[ch], values, s);
313
314                 fft_temp[n].re = fr;
315                 fft_temp[n].im = fi;
316             }
317
318             for (n = window_size / 2 + 1, x = window_size / 2 - 1; n < window_size; n++, x--) {
319                 fft_temp[n].re =  fft_temp[x].re;
320                 fft_temp[n].im = -fft_temp[x].im;
321             }
322
323             av_fft_permute(s->ifft, fft_temp);
324             av_fft_calc(s->ifft, fft_temp);
325
326             start = s->start;
327             end = s->end;
328             k = end;
329             for (i = 0, j = start; j < k && i < window_size; i++, j++) {
330                 buf[j] += s->fft_temp[ch][i].re * f;
331             }
332
333             for (; i < window_size; i++, j++) {
334                 buf[j] = s->fft_temp[ch][i].re * f;
335             }
336
337             start += s->hop_size;
338             end = j;
339         }
340
341         s->start = start;
342         s->end = end;
343
344         if (start >= window_size) {
345             float *dst, *buf;
346
347             start -= window_size;
348             end   -= window_size;
349
350             s->start = start;
351             s->end = end;
352
353             out = ff_get_audio_buffer(outlink, window_size);
354             if (!out) {
355                 ret = AVERROR(ENOMEM);
356                 break;
357             }
358
359             out->pts = s->pts;
360             s->pts += window_size;
361
362             for (ch = 0; ch < inlink->channels; ch++) {
363                 dst = (float *)out->extended_data[ch];
364                 buf = (float *)s->buffer->extended_data[ch];
365
366                 for (n = 0; n < window_size; n++) {
367                     dst[n] = buf[n] * (1 - s->overlap);
368                 }
369                 memmove(buf, buf + window_size, window_size * 4);
370             }
371
372             ret = ff_filter_frame(outlink, out);
373             if (ret < 0)
374                 break;
375         }
376
377         av_audio_fifo_drain(s->fifo, s->hop_size);
378     }
379
380     av_frame_free(&in);
381     return ret < 0 ? ret : 0;
382 }
383
384 static int query_formats(AVFilterContext *ctx)
385 {
386     AVFilterFormats *formats;
387     AVFilterChannelLayouts *layouts;
388     static const enum AVSampleFormat sample_fmts[] = {
389         AV_SAMPLE_FMT_FLTP,
390         AV_SAMPLE_FMT_NONE
391     };
392     int ret;
393
394     layouts = ff_all_channel_counts();
395     if (!layouts)
396         return AVERROR(ENOMEM);
397     ret = ff_set_common_channel_layouts(ctx, layouts);
398     if (ret < 0)
399         return ret;
400
401     formats = ff_make_format_list(sample_fmts);
402     if (!formats)
403         return AVERROR(ENOMEM);
404     ret = ff_set_common_formats(ctx, formats);
405     if (ret < 0)
406         return ret;
407
408     formats = ff_all_samplerates();
409     if (!formats)
410         return AVERROR(ENOMEM);
411     return ff_set_common_samplerates(ctx, formats);
412 }
413
414 static av_cold void uninit(AVFilterContext *ctx)
415 {
416     AFFTFiltContext *s = ctx->priv;
417     int i;
418
419     av_fft_end(s->fft);
420     av_fft_end(s->ifft);
421
422     for (i = 0; i < s->nb_exprs; i++) {
423         if (s->fft_data)
424             av_freep(&s->fft_data[i]);
425         if (s->fft_temp)
426             av_freep(&s->fft_temp[i]);
427     }
428     av_freep(&s->fft_data);
429     av_freep(&s->fft_temp);
430
431     for (i = 0; i < s->nb_exprs; i++) {
432         av_expr_free(s->real[i]);
433         av_expr_free(s->imag[i]);
434     }
435
436     av_freep(&s->real);
437     av_freep(&s->imag);
438     av_frame_free(&s->buffer);
439     av_freep(&s->window_func_lut);
440
441     av_audio_fifo_free(s->fifo);
442 }
443
444 static const AVFilterPad inputs[] = {
445     {
446         .name         = "default",
447         .type         = AVMEDIA_TYPE_AUDIO,
448         .config_props = config_input,
449         .filter_frame = filter_frame,
450     },
451     { NULL }
452 };
453
454 static const AVFilterPad outputs[] = {
455     {
456         .name = "default",
457         .type = AVMEDIA_TYPE_AUDIO,
458     },
459     { NULL }
460 };
461
462 AVFilter ff_af_afftfilt = {
463     .name            = "afftfilt",
464     .description     = NULL_IF_CONFIG_SMALL("Apply arbitrary expressions to samples in frequency domain."),
465     .priv_size       = sizeof(AFFTFiltContext),
466     .priv_class      = &afftfilt_class,
467     .inputs          = inputs,
468     .outputs         = outputs,
469     .query_formats   = query_formats,
470     .uninit          = uninit,
471 };