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