Browse code

avfilter: add afftfilter

Signed-off-by: Paul B Mahol <onemda@gmail.com>

Paul B Mahol authored on 2016/01/16 23:09:25
Showing 7 changed files
... ...
@@ -56,6 +56,7 @@ version <next>:
56 56
 - ahistogram filter
57 57
 - only seek with the right mouse button in ffplay
58 58
 - toggle full screen when double-clicking with the left mouse button in ffplay
59
+- afftfilt filter
59 60
 
60 61
 
61 62
 version 2.8:
... ...
@@ -2841,6 +2841,8 @@ unix_protocol_deps="sys_un_h"
2841 2841
 unix_protocol_select="network"
2842 2842
 
2843 2843
 # filters
2844
+afftfilt_filter_deps="avcodec"
2845
+afftfilt_filter_select="fft"
2844 2846
 amovie_filter_deps="avcodec avformat"
2845 2847
 aresample_filter_deps="swresample"
2846 2848
 ass_filter_deps="libass"
... ...
@@ -6065,6 +6067,7 @@ done
6065 6065
 enabled zlib && add_cppflags -DZLIB_CONST
6066 6066
 
6067 6067
 # conditional library dependencies, in linking order
6068
+enabled afftfilt_filter     && prepend avfilter_deps "avcodec"
6068 6069
 enabled amovie_filter       && prepend avfilter_deps "avformat avcodec"
6069 6070
 enabled aresample_filter    && prepend avfilter_deps "swresample"
6070 6071
 enabled asyncts_filter      && prepend avfilter_deps "avresample"
... ...
@@ -733,6 +733,83 @@ afade=t=out:st=875:d=25
733 733
 @end example
734 734
 @end itemize
735 735
 
736
+@section afftfilt
737
+Apply arbitrary expressions to samples in frequency domain.
738
+
739
+@table @option
740
+@item real
741
+Set frequency domain real expression for each separate channel separated
742
+by '|'. Default is "1".
743
+If the number of input channels is greater than the number of
744
+expressions, the last specified expression is used for the remaining
745
+output channels.
746
+
747
+@item imag
748
+Set frequency domain imaginary expression for each separate channel
749
+separated by '|'. If not set, @var{real} option is used.
750
+
751
+Each expression in @var{real} and @var{imag} can contain the following
752
+constants:
753
+
754
+@table @option
755
+@item sr
756
+sample rate
757
+
758
+@item b
759
+current frequency bin number
760
+
761
+@item nb
762
+number of available bins
763
+
764
+@item ch
765
+channel number of the current expression
766
+
767
+@item chs
768
+number of channels
769
+
770
+@item pts
771
+current frame pts
772
+@end table
773
+
774
+@item win_size
775
+Set window size.
776
+
777
+It accepts the following values:
778
+@table @samp
779
+@item w16
780
+@item w32
781
+@item w64
782
+@item w128
783
+@item w256
784
+@item w512
785
+@item w1024
786
+@item w2048
787
+@item w4096
788
+@item w8192
789
+@item w16384
790
+@item w32768
791
+@item w65536
792
+@end table
793
+Default is @code{w4096}
794
+
795
+@item win_func
796
+Set window function. Default is @code{hann}.
797
+
798
+@item overlap
799
+Set window overlap. If set to 1, the recommended overlap for selected
800
+window function will be picked. Default is @code{0.75}.
801
+@end table
802
+
803
+@subsection Examples
804
+
805
+@itemize
806
+@item
807
+Increase first 50 bins by 0.1 and lower all other frequencies by factor of 10:
808
+@example
809
+afftfilt="1.1*between(b\,0\,49)+0.1*between(b\,50\,f)"
810
+@end example
811
+@end itemize
812
+
736 813
 @anchor{aformat}
737 814
 @section aformat
738 815
 
... ...
@@ -29,6 +29,7 @@ OBJS-$(CONFIG_ACROSSFADE_FILTER)             += af_afade.o
29 29
 OBJS-$(CONFIG_ADELAY_FILTER)                 += af_adelay.o
30 30
 OBJS-$(CONFIG_AECHO_FILTER)                  += af_aecho.o
31 31
 OBJS-$(CONFIG_AEMPHASIS_FILTER)              += af_aemphasis.o
32
+OBJS-$(CONFIG_AFFTFILT_FILTER)               += af_afftfilt.o window_func.o
32 33
 OBJS-$(CONFIG_ANEQUALIZER_FILTER)            += af_anequalizer.o
33 34
 OBJS-$(CONFIG_AEVAL_FILTER)                  += aeval.o
34 35
 OBJS-$(CONFIG_AFADE_FILTER)                  += af_afade.o
35 36
new file mode 100644
... ...
@@ -0,0 +1,401 @@
0
+/*
1
+ * Copyright (c) 2016 Paul B Mahol
2
+ *
3
+ * This file is part of FFmpeg.
4
+ *
5
+ * FFmpeg is free software; you can redistribute it and/or modify it
6
+ * under the terms of the GNU Lesser General Public License as published
7
+ * by the Free Software Foundation; either version 2.1 of the License,
8
+ * or (at your option) any later version.
9
+ *
10
+ * FFmpeg is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
+ * Lesser General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU Lesser General Public
16
+ * License along with FFmpeg; if not, write to the Free Software
17
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
+ */
19
+
20
+#include "libavutil/audio_fifo.h"
21
+#include "libavutil/avstring.h"
22
+#include "libavfilter/internal.h"
23
+#include "libavutil/common.h"
24
+#include "libavutil/opt.h"
25
+#include "libavcodec/avfft.h"
26
+#include "libavutil/eval.h"
27
+#include "audio.h"
28
+#include "window_func.h"
29
+
30
+typedef struct AFFTFiltContext {
31
+    const AVClass *class;
32
+    char *real_str;
33
+    char *img_str;
34
+    int fft_bits;
35
+
36
+    FFTContext *fft, *ifft;
37
+    FFTComplex **fft_data;
38
+    int nb_exprs;
39
+    int window_size;
40
+    AVExpr **real;
41
+    AVExpr **imag;
42
+    AVAudioFifo *fifo;
43
+    int64_t pts;
44
+    int hop_size;
45
+    float overlap;
46
+    AVFrame *buffer;
47
+    int start, end;
48
+    int win_func;
49
+    float win_scale;
50
+    float *window_func_lut;
51
+} AFFTFiltContext;
52
+
53
+static const char *const var_names[] = {            "sr",     "b",       "nb",        "ch",        "chs",   "pts",        NULL };
54
+enum                                   { VAR_SAMPLE_RATE, VAR_BIN, VAR_NBBINS, VAR_CHANNEL, VAR_CHANNELS, VAR_PTS, VAR_VARS_NB };
55
+
56
+#define OFFSET(x) offsetof(AFFTFiltContext, x)
57
+#define A AV_OPT_FLAG_AUDIO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
58
+
59
+static const AVOption afftfilt_options[] = {
60
+    { "real", "set channels real expressions",       OFFSET(real_str), AV_OPT_TYPE_STRING, {.str = "1" }, 0, 0, A },
61
+    { "imag",  "set channels imaginary expressions", OFFSET(img_str),  AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, A },
62
+    { "win_size", "set window size", OFFSET(fft_bits), AV_OPT_TYPE_INT, {.i64=12}, 4, 16, A, "fft" },
63
+        { "w16",    0, 0, AV_OPT_TYPE_CONST, {.i64=4},  0, 0, A, "fft" },
64
+        { "w32",    0, 0, AV_OPT_TYPE_CONST, {.i64=5},  0, 0, A, "fft" },
65
+        { "w64",    0, 0, AV_OPT_TYPE_CONST, {.i64=6},  0, 0, A, "fft" },
66
+        { "w128",   0, 0, AV_OPT_TYPE_CONST, {.i64=7},  0, 0, A, "fft" },
67
+        { "w256",   0, 0, AV_OPT_TYPE_CONST, {.i64=8},  0, 0, A, "fft" },
68
+        { "w512",   0, 0, AV_OPT_TYPE_CONST, {.i64=9},  0, 0, A, "fft" },
69
+        { "w1024",  0, 0, AV_OPT_TYPE_CONST, {.i64=10}, 0, 0, A, "fft" },
70
+        { "w2048",  0, 0, AV_OPT_TYPE_CONST, {.i64=11}, 0, 0, A, "fft" },
71
+        { "w4096",  0, 0, AV_OPT_TYPE_CONST, {.i64=12}, 0, 0, A, "fft" },
72
+        { "w8192",  0, 0, AV_OPT_TYPE_CONST, {.i64=13}, 0, 0, A, "fft" },
73
+        { "w16384", 0, 0, AV_OPT_TYPE_CONST, {.i64=14}, 0, 0, A, "fft" },
74
+        { "w32768", 0, 0, AV_OPT_TYPE_CONST, {.i64=15}, 0, 0, A, "fft" },
75
+        { "w65536", 0, 0, AV_OPT_TYPE_CONST, {.i64=16}, 0, 0, A, "fft" },
76
+    { "win_func", "set window function", OFFSET(win_func), AV_OPT_TYPE_INT, {.i64 = WFUNC_HANNING}, 0, NB_WFUNC-1, A, "win_func" },
77
+        { "rect",     "Rectangular",      0, AV_OPT_TYPE_CONST, {.i64=WFUNC_RECT},     0, 0, A, "win_func" },
78
+        { "bartlett", "Bartlett",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BARTLETT}, 0, 0, A, "win_func" },
79
+        { "hann",     "Hann",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, A, "win_func" },
80
+        { "hanning",  "Hanning",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, A, "win_func" },
81
+        { "hamming",  "Hamming",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HAMMING},  0, 0, A, "win_func" },
82
+        { "sine",     "Sine",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_SINE},     0, 0, A, "win_func" },
83
+    { "overlap", "set window overlap", OFFSET(overlap), AV_OPT_TYPE_FLOAT, {.dbl=0.75}, 0,  1, A },
84
+    { NULL },
85
+};
86
+
87
+AVFILTER_DEFINE_CLASS(afftfilt);
88
+
89
+static int config_input(AVFilterLink *inlink)
90
+{
91
+    AVFilterContext *ctx = inlink->dst;
92
+    AFFTFiltContext *s = ctx->priv;
93
+    char *saveptr = NULL;
94
+    int ret = 0, ch, i;
95
+    float overlap;
96
+    char *args, *last_expr = NULL;
97
+
98
+    s->fft  = av_fft_init(s->fft_bits, 0);
99
+    s->ifft = av_fft_init(s->fft_bits, 1);
100
+    if (!s->fft || !s->ifft)
101
+        return AVERROR(ENOMEM);
102
+
103
+    s->window_size = 1 << s->fft_bits;
104
+
105
+    s->fft_data = av_calloc(inlink->channels, sizeof(*s->fft_data));
106
+    if (!s->fft_data)
107
+        return AVERROR(ENOMEM);
108
+
109
+    for (ch = 0; ch < inlink->channels; ch++) {
110
+        s->fft_data[ch] = av_calloc(s->window_size, sizeof(**s->fft_data));
111
+        if (!s->fft_data[ch])
112
+            return AVERROR(ENOMEM);
113
+    }
114
+
115
+    s->real = av_calloc(inlink->channels, sizeof(*s->real));
116
+    if (!s->real)
117
+        return AVERROR(ENOMEM);
118
+
119
+    s->imag = av_calloc(inlink->channels, sizeof(*s->imag));
120
+    if (!s->imag)
121
+        return AVERROR(ENOMEM);
122
+
123
+    args = av_strdup(s->real_str);
124
+    if (!args)
125
+        return AVERROR(ENOMEM);
126
+
127
+    for (ch = 0; ch < inlink->channels; ch++) {
128
+        char *arg = av_strtok(ch == 0 ? args : NULL, "|", &saveptr);
129
+
130
+        ret = av_expr_parse(&s->real[ch], arg ? arg : last_expr, var_names,
131
+                            NULL, NULL, NULL, NULL, 0, ctx);
132
+        if (ret < 0)
133
+            break;
134
+        if (arg)
135
+            last_expr = arg;
136
+        s->nb_exprs++;
137
+    }
138
+
139
+    av_free(args);
140
+
141
+    args = av_strdup(s->img_str ? s->img_str : s->real_str);
142
+    if (!args)
143
+        return AVERROR(ENOMEM);
144
+
145
+    for (ch = 0; ch < inlink->channels; ch++) {
146
+        char *arg = av_strtok(ch == 0 ? args : NULL, "|", &saveptr);
147
+
148
+        ret = av_expr_parse(&s->imag[ch], arg ? arg : last_expr, var_names,
149
+                            NULL, NULL, NULL, NULL, 0, ctx);
150
+        if (ret < 0)
151
+            break;
152
+        if (arg)
153
+            last_expr = arg;
154
+    }
155
+
156
+    av_free(args);
157
+
158
+    s->fifo = av_audio_fifo_alloc(inlink->format, inlink->channels, s->window_size);
159
+    if (!s->fifo)
160
+        return AVERROR(ENOMEM);
161
+
162
+    s->window_func_lut = av_realloc_f(s->window_func_lut, s->window_size,
163
+                                      sizeof(*s->window_func_lut));
164
+    if (!s->window_func_lut)
165
+        return AVERROR(ENOMEM);
166
+    ff_generate_window_func(s->window_func_lut, s->window_size, s->win_func, &overlap);
167
+    if (s->overlap == 1)
168
+        s->overlap = overlap;
169
+
170
+    for (s->win_scale = 0, i = 0; i < s->window_size; i++) {
171
+        s->win_scale += s->window_func_lut[i] * s->window_func_lut[i];
172
+    }
173
+
174
+    s->hop_size = s->window_size * (1 - s->overlap);
175
+    if (s->hop_size <= 0)
176
+        return AVERROR(EINVAL);
177
+
178
+    s->buffer = ff_get_audio_buffer(inlink, s->window_size * 2);
179
+    if (!s->buffer)
180
+        return AVERROR(ENOMEM);
181
+
182
+    return ret;
183
+}
184
+
185
+static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
186
+{
187
+    AVFilterContext *ctx = inlink->dst;
188
+    AVFilterLink *outlink = ctx->outputs[0];
189
+    AFFTFiltContext *s = ctx->priv;
190
+    const int window_size = s->window_size;
191
+    const float f = 1. / s->win_scale;
192
+    double values[VAR_VARS_NB];
193
+    AVFrame *out, *in = NULL;
194
+    int ch, n, ret, i, j, k;
195
+    int start = s->start, end = s->end;
196
+
197
+    av_audio_fifo_write(s->fifo, (void **)frame->extended_data, frame->nb_samples);
198
+    av_frame_free(&frame);
199
+
200
+    while (av_audio_fifo_size(s->fifo) >= window_size) {
201
+        if (!in) {
202
+            in = ff_get_audio_buffer(outlink, window_size);
203
+            if (!in)
204
+                return AVERROR(ENOMEM);
205
+        }
206
+
207
+        ret = av_audio_fifo_peek(s->fifo, (void **)in->extended_data, window_size);
208
+        if (ret < 0)
209
+            break;
210
+
211
+        for (ch = 0; ch < inlink->channels; ch++) {
212
+            const float *src = (float *)in->extended_data[ch];
213
+            FFTComplex *fft_data = s->fft_data[ch];
214
+
215
+            for (n = 0; n < in->nb_samples; n++) {
216
+                fft_data[n].re = src[n] * s->window_func_lut[n];
217
+                fft_data[n].im = 0;
218
+            }
219
+
220
+            for (; n < window_size; n++) {
221
+                fft_data[n].re = 0;
222
+                fft_data[n].im = 0;
223
+            }
224
+        }
225
+
226
+        values[VAR_PTS]         = s->pts;
227
+        values[VAR_SAMPLE_RATE] = inlink->sample_rate;
228
+        values[VAR_NBBINS]      = window_size / 2;
229
+        values[VAR_CHANNELS]    = inlink->channels;
230
+
231
+        for (ch = 0; ch < inlink->channels; ch++) {
232
+            FFTComplex *fft_data = s->fft_data[ch];
233
+            float *buf = (float *)s->buffer->extended_data[ch];
234
+            int x;
235
+
236
+            values[VAR_CHANNEL] = ch;
237
+
238
+            av_fft_permute(s->fft, fft_data);
239
+            av_fft_calc(s->fft, fft_data);
240
+
241
+            for (n = 0; n < window_size / 2; n++) {
242
+                float fr, fi;
243
+
244
+                values[VAR_BIN] = n;
245
+
246
+                fr = av_expr_eval(s->real[ch], values, s);
247
+                fi = av_expr_eval(s->imag[ch], values, s);
248
+
249
+                fft_data[n].re *= fr;
250
+                fft_data[n].im *= fi;
251
+            }
252
+
253
+            for (n = window_size / 2 + 1, x = window_size / 2 - 1; n < window_size; n++, x--) {
254
+                fft_data[n].re =  fft_data[x].re;
255
+                fft_data[n].im = -fft_data[x].im;
256
+            }
257
+
258
+            av_fft_permute(s->ifft, fft_data);
259
+            av_fft_calc(s->ifft, fft_data);
260
+
261
+            start = s->start;
262
+            end = s->end;
263
+            k = end;
264
+            for (i = 0, j = start; j < k && i < window_size; i++, j++) {
265
+                buf[j] += s->fft_data[ch][i].re * f;
266
+            }
267
+
268
+            for (; i < window_size; i++, j++) {
269
+                buf[j] = s->fft_data[ch][i].re * f;
270
+            }
271
+
272
+            start += s->hop_size;
273
+            end = j;
274
+        }
275
+
276
+        s->start = start;
277
+        s->end = end;
278
+
279
+        if (start >= window_size) {
280
+            float *dst, *buf;
281
+
282
+            start -= window_size;
283
+            end   -= window_size;
284
+
285
+            s->start = start;
286
+            s->end = end;
287
+
288
+            out = ff_get_audio_buffer(outlink, window_size);
289
+            if (!out) {
290
+                ret = AVERROR(ENOMEM);
291
+                break;
292
+            }
293
+
294
+            out->pts = s->pts;
295
+            s->pts += window_size;
296
+
297
+            for (ch = 0; ch < inlink->channels; ch++) {
298
+                dst = (float *)out->extended_data[ch];
299
+                buf = (float *)s->buffer->extended_data[ch];
300
+
301
+                for (n = 0; n < window_size; n++) {
302
+                    dst[n] = buf[n] * (1 - s->overlap);
303
+                }
304
+                memmove(buf, buf + window_size, window_size * 4);
305
+            }
306
+
307
+            ret = ff_filter_frame(outlink, out);
308
+            if (ret < 0)
309
+                break;
310
+        }
311
+
312
+        av_audio_fifo_drain(s->fifo, s->hop_size);
313
+    }
314
+
315
+    av_frame_free(&in);
316
+    return ret;
317
+}
318
+
319
+static int query_formats(AVFilterContext *ctx)
320
+{
321
+    AVFilterFormats *formats;
322
+    AVFilterChannelLayouts *layouts;
323
+    static const enum AVSampleFormat sample_fmts[] = {
324
+        AV_SAMPLE_FMT_FLTP,
325
+        AV_SAMPLE_FMT_NONE
326
+    };
327
+    int ret;
328
+
329
+    layouts = ff_all_channel_counts();
330
+    if (!layouts)
331
+        return AVERROR(ENOMEM);
332
+    ret = ff_set_common_channel_layouts(ctx, layouts);
333
+    if (ret < 0)
334
+        return ret;
335
+
336
+    formats = ff_make_format_list(sample_fmts);
337
+    if (!formats)
338
+        return AVERROR(ENOMEM);
339
+    ret = ff_set_common_formats(ctx, formats);
340
+    if (ret < 0)
341
+        return ret;
342
+
343
+    formats = ff_all_samplerates();
344
+    if (!formats)
345
+        return AVERROR(ENOMEM);
346
+    return ff_set_common_samplerates(ctx, formats);
347
+}
348
+
349
+static av_cold void uninit(AVFilterContext *ctx)
350
+{
351
+    AFFTFiltContext *s = ctx->priv;
352
+    int i;
353
+
354
+    av_fft_end(s->fft);
355
+    av_fft_end(s->ifft);
356
+
357
+    for (i = 0; i < s->nb_exprs; i++) {
358
+        if (s->fft_data)
359
+            av_freep(&s->fft_data[i]);
360
+    }
361
+    av_freep(&s->fft_data);
362
+
363
+    for (i = 0; i < s->nb_exprs; i++) {
364
+        av_expr_free(s->real[i]);
365
+        av_expr_free(s->imag[i]);
366
+    }
367
+
368
+    av_freep(&s->real);
369
+    av_freep(&s->imag);
370
+    av_frame_free(&s->buffer);
371
+}
372
+
373
+static const AVFilterPad inputs[] = {
374
+    {
375
+        .name         = "default",
376
+        .type         = AVMEDIA_TYPE_AUDIO,
377
+        .config_props = config_input,
378
+        .filter_frame = filter_frame,
379
+    },
380
+    { NULL }
381
+};
382
+
383
+static const AVFilterPad outputs[] = {
384
+    {
385
+        .name = "default",
386
+        .type = AVMEDIA_TYPE_AUDIO,
387
+    },
388
+    { NULL }
389
+};
390
+
391
+AVFilter ff_af_afftfilt = {
392
+    .name            = "afftfilt",
393
+    .description     = NULL_IF_CONFIG_SMALL("Apply arbitrary expressions to samples in frequency domain."),
394
+    .priv_size       = sizeof(AFFTFiltContext),
395
+    .priv_class      = &afftfilt_class,
396
+    .inputs          = inputs,
397
+    .outputs         = outputs,
398
+    .query_formats   = query_formats,
399
+    .uninit          = uninit,
400
+};
... ...
@@ -52,6 +52,7 @@ void avfilter_register_all(void)
52 52
     REGISTER_FILTER(AEMPHASIS,      aemphasis,      af);
53 53
     REGISTER_FILTER(AEVAL,          aeval,          af);
54 54
     REGISTER_FILTER(AFADE,          afade,          af);
55
+    REGISTER_FILTER(AFFTFILT,       afftfilt,       af);
55 56
     REGISTER_FILTER(AFORMAT,        aformat,        af);
56 57
     REGISTER_FILTER(AGATE,          agate,          af);
57 58
     REGISTER_FILTER(AINTERLEAVE,    ainterleave,    af);
... ...
@@ -30,7 +30,7 @@
30 30
 #include "libavutil/version.h"
31 31
 
32 32
 #define LIBAVFILTER_VERSION_MAJOR   6
33
-#define LIBAVFILTER_VERSION_MINOR  25
33
+#define LIBAVFILTER_VERSION_MINOR  26
34 34
 #define LIBAVFILTER_VERSION_MICRO 100
35 35
 
36 36
 #define LIBAVFILTER_VERSION_INT AV_VERSION_INT(LIBAVFILTER_VERSION_MAJOR, \