• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/avstring.h"
22 #include "libavfilter/internal.h"
23 #include "libavutil/common.h"
24 #include "libavutil/cpu.h"
25 #include "libavutil/opt.h"
26 #include "libavutil/eval.h"
27 #include "libavutil/tx.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 
38     AVTXContext **fft, **ifft;
39     av_tx_fn  tx_fn, itx_fn;
40     AVComplexFloat **fft_in;
41     AVComplexFloat **fft_out;
42     AVComplexFloat **fft_temp;
43     int nb_exprs;
44     int channels;
45     int window_size;
46     AVExpr **real;
47     AVExpr **imag;
48     int hop_size;
49     float overlap;
50     AVFrame *window;
51     AVFrame *buffer;
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_OPTION("win_func", OFFSET(win_func), A, WFUNC_HANNING),
67     { "overlap", "set window overlap", OFFSET(overlap), AV_OPT_TYPE_FLOAT, {.dbl=0.75}, 0,  1, A },
68     { NULL },
69 };
70 
71 AVFILTER_DEFINE_CLASS(afftfilt);
72 
getreal(void * priv,double x,double ch)73 static inline double getreal(void *priv, double x, double ch)
74 {
75     AFFTFiltContext *s = priv;
76     int ich, ix;
77 
78     ich = av_clip(ch, 0, s->nb_exprs - 1);
79     ix = av_clip(x, 0, s->window_size / 2);
80 
81     return s->fft_out[ich][ix].re;
82 }
83 
getimag(void * priv,double x,double ch)84 static inline double getimag(void *priv, double x, double ch)
85 {
86     AFFTFiltContext *s = priv;
87     int ich, ix;
88 
89     ich = av_clip(ch, 0, s->nb_exprs - 1);
90     ix = av_clip(x, 0, s->window_size / 2);
91 
92     return s->fft_out[ich][ix].im;
93 }
94 
realf(void * priv,double x,double ch)95 static double realf(void *priv, double x, double ch) { return getreal(priv, x, ch); }
imagf(void * priv,double x,double ch)96 static double imagf(void *priv, double x, double ch) { return getimag(priv, x, ch); }
97 
98 static const char *const func2_names[]    = { "real", "imag", NULL };
99 static double (*const func2[])(void *, double, double) = {  realf,  imagf, NULL };
100 
config_input(AVFilterLink * inlink)101 static int config_input(AVFilterLink *inlink)
102 {
103     AVFilterContext *ctx = inlink->dst;
104     AFFTFiltContext *s = ctx->priv;
105     char *saveptr = NULL;
106     int ret = 0, ch;
107     float overlap, scale = 1.f;
108     char *args;
109     const char *last_expr = "1";
110     int buf_size;
111 
112     s->channels = inlink->ch_layout.nb_channels;
113     s->fft  = av_calloc(s->channels, sizeof(*s->fft));
114     s->ifft = av_calloc(s->channels, sizeof(*s->ifft));
115     if (!s->fft || !s->ifft)
116         return AVERROR(ENOMEM);
117 
118     for (int ch = 0; ch < s->channels; ch++) {
119         ret = av_tx_init(&s->fft[ch], &s->tx_fn, AV_TX_FLOAT_FFT, 0, s->fft_size, &scale, 0);
120         if (ret < 0)
121             return ret;
122     }
123 
124     for (int ch = 0; ch < s->channels; ch++) {
125         ret = av_tx_init(&s->ifft[ch], &s->itx_fn, AV_TX_FLOAT_FFT, 1, s->fft_size, &scale, 0);
126         if (ret < 0)
127             return ret;
128     }
129 
130     s->window_size = s->fft_size;
131     buf_size = FFALIGN(s->window_size, av_cpu_max_align());
132 
133     s->fft_in = av_calloc(inlink->ch_layout.nb_channels, sizeof(*s->fft_in));
134     if (!s->fft_in)
135         return AVERROR(ENOMEM);
136 
137     s->fft_out = av_calloc(inlink->ch_layout.nb_channels, sizeof(*s->fft_out));
138     if (!s->fft_out)
139         return AVERROR(ENOMEM);
140 
141     s->fft_temp = av_calloc(inlink->ch_layout.nb_channels, sizeof(*s->fft_temp));
142     if (!s->fft_temp)
143         return AVERROR(ENOMEM);
144 
145     for (ch = 0; ch < inlink->ch_layout.nb_channels; ch++) {
146         s->fft_in[ch] = av_calloc(buf_size, sizeof(**s->fft_in));
147         if (!s->fft_in[ch])
148             return AVERROR(ENOMEM);
149 
150         s->fft_out[ch] = av_calloc(buf_size, sizeof(**s->fft_out));
151         if (!s->fft_out[ch])
152             return AVERROR(ENOMEM);
153 
154         s->fft_temp[ch] = av_calloc(buf_size, sizeof(**s->fft_temp));
155         if (!s->fft_temp[ch])
156             return AVERROR(ENOMEM);
157     }
158 
159     s->real = av_calloc(inlink->ch_layout.nb_channels, sizeof(*s->real));
160     if (!s->real)
161         return AVERROR(ENOMEM);
162 
163     s->imag = av_calloc(inlink->ch_layout.nb_channels, sizeof(*s->imag));
164     if (!s->imag)
165         return AVERROR(ENOMEM);
166 
167     args = av_strdup(s->real_str);
168     if (!args)
169         return AVERROR(ENOMEM);
170 
171     for (ch = 0; ch < inlink->ch_layout.nb_channels; ch++) {
172         char *arg = av_strtok(ch == 0 ? args : NULL, "|", &saveptr);
173 
174         ret = av_expr_parse(&s->real[ch], arg ? arg : last_expr, var_names,
175                             NULL, NULL, func2_names, func2, 0, ctx);
176         if (ret < 0)
177             goto fail;
178         if (arg)
179             last_expr = arg;
180         s->nb_exprs++;
181     }
182 
183     av_freep(&args);
184 
185     args = av_strdup(s->img_str ? s->img_str : s->real_str);
186     if (!args)
187         return AVERROR(ENOMEM);
188 
189     saveptr = NULL;
190     last_expr = "1";
191     for (ch = 0; ch < inlink->ch_layout.nb_channels; ch++) {
192         char *arg = av_strtok(ch == 0 ? args : NULL, "|", &saveptr);
193 
194         ret = av_expr_parse(&s->imag[ch], arg ? arg : last_expr, var_names,
195                             NULL, NULL, func2_names, func2, 0, ctx);
196         if (ret < 0)
197             goto fail;
198         if (arg)
199             last_expr = arg;
200     }
201 
202     av_freep(&args);
203 
204     s->window_func_lut = av_realloc_f(s->window_func_lut, s->window_size,
205                                       sizeof(*s->window_func_lut));
206     if (!s->window_func_lut)
207         return AVERROR(ENOMEM);
208     generate_window_func(s->window_func_lut, s->window_size, s->win_func, &overlap);
209     for (int i = 0; i < s->window_size; i++)
210         s->window_func_lut[i] = sqrtf(s->window_func_lut[i] / s->window_size);
211     if (s->overlap == 1)
212         s->overlap = overlap;
213 
214     s->hop_size = s->window_size * (1 - s->overlap);
215     if (s->hop_size <= 0)
216         return AVERROR(EINVAL);
217 
218     s->window = ff_get_audio_buffer(inlink, s->window_size * 2);
219     if (!s->window)
220         return AVERROR(ENOMEM);
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 
tx_channel(AVFilterContext * ctx,void * arg,int jobnr,int nb_jobs)232 static int tx_channel(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
233 {
234     AFFTFiltContext *s = ctx->priv;
235     const int channels = s->channels;
236     const int start = (channels * jobnr) / nb_jobs;
237     const int end = (channels * (jobnr+1)) / nb_jobs;
238 
239     for (int ch = start; ch < end; ch++) {
240         AVComplexFloat *fft_in = s->fft_in[ch];
241         AVComplexFloat *fft_out = s->fft_out[ch];
242 
243         s->tx_fn(s->fft[ch], fft_out, fft_in, sizeof(float));
244     }
245 
246     return 0;
247 }
248 
filter_channel(AVFilterContext * ctx,void * arg,int jobnr,int nb_jobs)249 static int filter_channel(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
250 {
251     AFFTFiltContext *s = ctx->priv;
252     const int window_size = s->window_size;
253     const float *window_lut = s->window_func_lut;
254     const float f = sqrtf(1.f - s->overlap);
255     const int channels = s->channels;
256     const int start = (channels * jobnr) / nb_jobs;
257     const int end = (channels * (jobnr+1)) / nb_jobs;
258     double values[VAR_VARS_NB];
259 
260     memcpy(values, arg, sizeof(values));
261 
262     for (int ch = start; ch < end; ch++) {
263         AVComplexFloat *fft_out = s->fft_out[ch];
264         AVComplexFloat *fft_temp = s->fft_temp[ch];
265         float *buf = (float *)s->buffer->extended_data[ch];
266 
267         values[VAR_CHANNEL] = ch;
268 
269         if (ctx->is_disabled) {
270             for (int n = 0; n < window_size; n++) {
271                 fft_temp[n].re = fft_out[n].re;
272                 fft_temp[n].im = fft_out[n].im;
273             }
274         } else {
275             for (int n = 0; n <= window_size / 2; n++) {
276                 float fr, fi;
277 
278                 values[VAR_BIN] = n;
279                 values[VAR_REAL] = fft_out[n].re;
280                 values[VAR_IMAG] = fft_out[n].im;
281 
282                 fr = av_expr_eval(s->real[ch], values, s);
283                 fi = av_expr_eval(s->imag[ch], values, s);
284 
285                 fft_temp[n].re = fr;
286                 fft_temp[n].im = fi;
287             }
288 
289             for (int n = window_size / 2 + 1, x = window_size / 2 - 1; n < window_size; n++, x--) {
290                 fft_temp[n].re =  fft_temp[x].re;
291                 fft_temp[n].im = -fft_temp[x].im;
292             }
293         }
294 
295         s->itx_fn(s->ifft[ch], fft_out, fft_temp, sizeof(float));
296 
297         memmove(buf, buf + s->hop_size, window_size * sizeof(float));
298         for (int i = 0; i < window_size; i++)
299             buf[i] += fft_out[i].re * window_lut[i] * f;
300     }
301 
302     return 0;
303 }
304 
filter_frame(AVFilterLink * inlink,AVFrame * in)305 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
306 {
307     AVFilterContext *ctx = inlink->dst;
308     AVFilterLink *outlink = ctx->outputs[0];
309     AFFTFiltContext *s = ctx->priv;
310     const int window_size = s->window_size;
311     const float *window_lut = s->window_func_lut;
312     double values[VAR_VARS_NB];
313     int ch, n, ret;
314     AVFrame *out;
315 
316     for (ch = 0; ch < inlink->ch_layout.nb_channels; ch++) {
317         const int offset = s->window_size - s->hop_size;
318         float *src = (float *)s->window->extended_data[ch];
319         AVComplexFloat *fft_in = s->fft_in[ch];
320 
321         memmove(src, &src[s->hop_size], offset * sizeof(float));
322         memcpy(&src[offset], in->extended_data[ch], in->nb_samples * sizeof(float));
323         memset(&src[offset + in->nb_samples], 0, (s->hop_size - in->nb_samples) * sizeof(float));
324 
325         for (n = 0; n < window_size; n++) {
326             fft_in[n].re = src[n] * window_lut[n];
327             fft_in[n].im = 0;
328         }
329     }
330 
331     values[VAR_PTS]         = in->pts;
332     values[VAR_SAMPLE_RATE] = inlink->sample_rate;
333     values[VAR_NBBINS]      = window_size / 2;
334     values[VAR_CHANNELS]    = inlink->ch_layout.nb_channels;
335 
336     ff_filter_execute(ctx, tx_channel, NULL, NULL,
337                       FFMIN(s->channels, ff_filter_get_nb_threads(ctx)));
338 
339     ff_filter_execute(ctx, filter_channel, values, NULL,
340                       FFMIN(s->channels, ff_filter_get_nb_threads(ctx)));
341 
342     out = ff_get_audio_buffer(outlink, s->hop_size);
343     if (!out) {
344         ret = AVERROR(ENOMEM);
345         goto fail;
346     }
347 
348     out->pts = in->pts;
349     out->nb_samples = in->nb_samples;
350 
351     for (ch = 0; ch < inlink->ch_layout.nb_channels; ch++) {
352         float *dst = (float *)out->extended_data[ch];
353         float *buf = (float *)s->buffer->extended_data[ch];
354 
355         memcpy(dst, buf, s->hop_size * sizeof(float));
356     }
357 
358     ret = ff_filter_frame(outlink, out);
359     if (ret < 0)
360         goto fail;
361 
362 fail:
363     av_frame_free(&in);
364     return ret < 0 ? ret : 0;
365 }
366 
activate(AVFilterContext * ctx)367 static int activate(AVFilterContext *ctx)
368 {
369     AVFilterLink *inlink = ctx->inputs[0];
370     AVFilterLink *outlink = ctx->outputs[0];
371     AFFTFiltContext *s = ctx->priv;
372     AVFrame *in = NULL;
373     int ret = 0, status;
374     int64_t pts;
375 
376     FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink);
377 
378     ret = ff_inlink_consume_samples(inlink, s->hop_size, s->hop_size, &in);
379     if (ret < 0)
380         return ret;
381 
382     if (ret > 0)
383         ret = filter_frame(inlink, in);
384     if (ret < 0)
385         return ret;
386 
387     if (ff_inlink_acknowledge_status(inlink, &status, &pts)) {
388         ff_outlink_set_status(outlink, status, pts);
389         return 0;
390     }
391 
392     FF_FILTER_FORWARD_WANTED(outlink, inlink);
393 
394     return FFERROR_NOT_READY;
395 }
396 
uninit(AVFilterContext * ctx)397 static av_cold void uninit(AVFilterContext *ctx)
398 {
399     AFFTFiltContext *s = ctx->priv;
400     int i;
401 
402 
403     for (i = 0; i < s->channels; i++) {
404         if (s->ifft)
405             av_tx_uninit(&s->ifft[i]);
406         if (s->fft)
407             av_tx_uninit(&s->fft[i]);
408         if (s->fft_in)
409             av_freep(&s->fft_in[i]);
410         if (s->fft_out)
411             av_freep(&s->fft_out[i]);
412         if (s->fft_temp)
413             av_freep(&s->fft_temp[i]);
414     }
415 
416     av_freep(&s->fft);
417     av_freep(&s->ifft);
418     av_freep(&s->fft_in);
419     av_freep(&s->fft_out);
420     av_freep(&s->fft_temp);
421 
422     for (i = 0; i < s->nb_exprs; i++) {
423         av_expr_free(s->real[i]);
424         av_expr_free(s->imag[i]);
425     }
426 
427     av_freep(&s->real);
428     av_freep(&s->imag);
429     av_frame_free(&s->buffer);
430     av_frame_free(&s->window);
431     av_freep(&s->window_func_lut);
432 }
433 
434 static const AVFilterPad inputs[] = {
435     {
436         .name         = "default",
437         .type         = AVMEDIA_TYPE_AUDIO,
438         .config_props = config_input,
439     },
440 };
441 
442 static const AVFilterPad outputs[] = {
443     {
444         .name = "default",
445         .type = AVMEDIA_TYPE_AUDIO,
446     },
447 };
448 
449 const AVFilter ff_af_afftfilt = {
450     .name            = "afftfilt",
451     .description     = NULL_IF_CONFIG_SMALL("Apply arbitrary expressions to samples in frequency domain."),
452     .priv_size       = sizeof(AFFTFiltContext),
453     .priv_class      = &afftfilt_class,
454     FILTER_INPUTS(inputs),
455     FILTER_OUTPUTS(outputs),
456     FILTER_SINGLE_SAMPLEFMT(AV_SAMPLE_FMT_FLTP),
457     .activate        = activate,
458     .uninit          = uninit,
459     .flags           = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL |
460                        AVFILTER_FLAG_SLICE_THREADS,
461 };
462