]> git.sesse.net Git - ffmpeg/blob - libavfilter/vaf_spectrumsynth.c
Merge commit '5b6f42da98c26a8aee8d2c2edfcbd0633ad1c607'
[ffmpeg] / libavfilter / vaf_spectrumsynth.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
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.
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 /**
22  * @file
23  * SpectrumSynth filter
24  * @todo support float pixel format
25  */
26
27 #include "libavcodec/avfft.h"
28 #include "libavutil/avassert.h"
29 #include "libavutil/channel_layout.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/parseutils.h"
32 #include "avfilter.h"
33 #include "formats.h"
34 #include "audio.h"
35 #include "video.h"
36 #include "internal.h"
37 #include "window_func.h"
38
39 enum MagnitudeScale { LINEAR, LOG, NB_SCALES };
40 enum SlideMode      { REPLACE, SCROLL, FULLFRAME, RSCROLL, NB_SLIDES };
41 enum Orientation    { VERTICAL, HORIZONTAL, NB_ORIENTATIONS };
42
43 typedef struct SpectrumSynthContext {
44     const AVClass *class;
45     int sample_rate;
46     int channels;
47     int scale;
48     int sliding;
49     int win_func;
50     float overlap;
51     int orientation;
52
53     AVFrame *magnitude, *phase;
54     FFTContext *fft;            ///< Fast Fourier Transform context
55     int fft_bits;               ///< number of bits (FFT window size = 1<<fft_bits)
56     FFTComplex **fft_data;      ///< bins holder for each (displayed) channels
57     int win_size;
58     int size;
59     int nb_freq;
60     int hop_size;
61     int start, end;
62     int xpos;
63     int xend;
64     int64_t pts;
65     float factor;
66     AVFrame *buffer;
67     float *window_func_lut;     ///< Window function LUT
68 } SpectrumSynthContext;
69
70 #define OFFSET(x) offsetof(SpectrumSynthContext, x)
71 #define A AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_AUDIO_PARAM
72 #define V AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
73
74 static const AVOption spectrumsynth_options[] = {
75     { "sample_rate", "set sample rate",  OFFSET(sample_rate), AV_OPT_TYPE_INT, {.i64 = 44100}, 15,  INT_MAX, A },
76     { "channels",    "set channels",     OFFSET(channels), AV_OPT_TYPE_INT, {.i64 = 1}, 1, 8, A },
77     { "scale",       "set input amplitude scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64 = LOG}, 0, NB_SCALES-1, V, "scale" },
78         { "lin",  "linear",      0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, V, "scale" },
79         { "log",  "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG},    0, 0, V, "scale" },
80     { "slide", "set input sliding mode", OFFSET(sliding), AV_OPT_TYPE_INT, {.i64 = FULLFRAME}, 0, NB_SLIDES-1, V, "slide" },
81         { "replace",   "consume old columns with new",   0, AV_OPT_TYPE_CONST, {.i64=REPLACE},   0, 0, V, "slide" },
82         { "scroll",    "consume only most right column", 0, AV_OPT_TYPE_CONST, {.i64=SCROLL},    0, 0, V, "slide" },
83         { "fullframe", "consume full frames",            0, AV_OPT_TYPE_CONST, {.i64=FULLFRAME}, 0, 0, V, "slide" },
84         { "rscroll",   "consume only most left column",  0, AV_OPT_TYPE_CONST, {.i64=RSCROLL},   0, 0, V, "slide" },
85     { "win_func", "set window function", OFFSET(win_func), AV_OPT_TYPE_INT, {.i64 = 0}, 0, NB_WFUNC-1, A, "win_func" },
86         { "rect",     "Rectangular",      0, AV_OPT_TYPE_CONST, {.i64=WFUNC_RECT},     0, 0, A, "win_func" },
87         { "bartlett", "Bartlett",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BARTLETT}, 0, 0, A, "win_func" },
88         { "hann",     "Hann",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, A, "win_func" },
89         { "hanning",  "Hanning",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, A, "win_func" },
90         { "hamming",  "Hamming",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HAMMING},  0, 0, A, "win_func" },
91         { "sine",     "Sine",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_SINE},     0, 0, A, "win_func" },
92     { "overlap", "set window overlap",  OFFSET(overlap), AV_OPT_TYPE_FLOAT, {.dbl=1}, 0,  1, A },
93     { "orientation", "set orientation", OFFSET(orientation), AV_OPT_TYPE_INT, {.i64=VERTICAL}, 0, NB_ORIENTATIONS-1, V, "orientation" },
94         { "vertical",   NULL, 0, AV_OPT_TYPE_CONST, {.i64=VERTICAL},   0, 0, V, "orientation" },
95         { "horizontal", NULL, 0, AV_OPT_TYPE_CONST, {.i64=HORIZONTAL}, 0, 0, V, "orientation" },
96     { NULL }
97 };
98
99 AVFILTER_DEFINE_CLASS(spectrumsynth);
100
101 static int query_formats(AVFilterContext *ctx)
102 {
103     SpectrumSynthContext *s = ctx->priv;
104     AVFilterFormats *formats = NULL;
105     AVFilterChannelLayouts *layout = NULL;
106     AVFilterLink *magnitude = ctx->inputs[0];
107     AVFilterLink *phase = ctx->inputs[1];
108     AVFilterLink *outlink = ctx->outputs[0];
109     static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE };
110     static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY16,
111                                                    AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUVJ444P,
112                                                    AV_PIX_FMT_YUV444P16, AV_PIX_FMT_NONE };
113     int ret, sample_rates[] = { 48000, -1 };
114
115     formats = ff_make_format_list(sample_fmts);
116     if ((ret = ff_formats_ref         (formats, &outlink->in_formats        )) < 0 ||
117         (ret = ff_add_channel_layout  (&layout, FF_COUNT2LAYOUT(s->channels))) < 0 ||
118         (ret = ff_channel_layouts_ref (layout , &outlink->in_channel_layouts)) < 0)
119         return ret;
120
121     sample_rates[0] = s->sample_rate;
122     formats = ff_make_format_list(sample_rates);
123     if (!formats)
124         return AVERROR(ENOMEM);
125     if ((ret = ff_formats_ref(formats, &outlink->in_samplerates)) < 0)
126         return ret;
127
128     formats = ff_make_format_list(pix_fmts);
129     if (!formats)
130         return AVERROR(ENOMEM);
131     if ((ret = ff_formats_ref(formats, &magnitude->out_formats)) < 0)
132         return ret;
133
134     formats = ff_make_format_list(pix_fmts);
135     if (!formats)
136         return AVERROR(ENOMEM);
137     if ((ret = ff_formats_ref(formats, &phase->out_formats)) < 0)
138         return ret;
139
140     return 0;
141 }
142
143 static int config_output(AVFilterLink *outlink)
144 {
145     AVFilterContext *ctx = outlink->src;
146     SpectrumSynthContext *s = ctx->priv;
147     int width = ctx->inputs[0]->w;
148     int height = ctx->inputs[0]->h;
149     AVRational time_base  = ctx->inputs[0]->time_base;
150     AVRational frame_rate = ctx->inputs[0]->frame_rate;
151     int i, ch, fft_bits;
152     float factor, overlap;
153
154     outlink->sample_rate = s->sample_rate;
155     outlink->time_base = (AVRational){1, s->sample_rate};
156
157     if (width  != ctx->inputs[1]->w ||
158         height != ctx->inputs[1]->h) {
159         av_log(ctx, AV_LOG_ERROR,
160                "Magnitude and Phase sizes differ (%dx%d vs %dx%d).\n",
161                width, height,
162                ctx->inputs[1]->w, ctx->inputs[1]->h);
163         return AVERROR_INVALIDDATA;
164     } else if (av_cmp_q(time_base, ctx->inputs[1]->time_base) != 0) {
165         av_log(ctx, AV_LOG_ERROR,
166                "Magnitude and Phase time bases differ (%d/%d vs %d/%d).\n",
167                time_base.num, time_base.den,
168                ctx->inputs[1]->time_base.num,
169                ctx->inputs[1]->time_base.den);
170         return AVERROR_INVALIDDATA;
171     } else if (av_cmp_q(frame_rate, ctx->inputs[1]->frame_rate) != 0) {
172         av_log(ctx, AV_LOG_ERROR,
173                "Magnitude and Phase framerates differ (%d/%d vs %d/%d).\n",
174                frame_rate.num, frame_rate.den,
175                ctx->inputs[1]->frame_rate.num,
176                ctx->inputs[1]->frame_rate.den);
177         return AVERROR_INVALIDDATA;
178     }
179
180     s->size = s->orientation == VERTICAL ? height / s->channels : width / s->channels;
181     s->xend = s->orientation == VERTICAL ? width : height;
182
183     for (fft_bits = 1; 1 << fft_bits < 2 * s->size; fft_bits++);
184
185     s->win_size = 1 << fft_bits;
186     s->nb_freq = 1 << (fft_bits - 1);
187
188     s->fft = av_fft_init(fft_bits, 1);
189     if (!s->fft) {
190         av_log(ctx, AV_LOG_ERROR, "Unable to create FFT context. "
191                "The window size might be too high.\n");
192         return AVERROR(EINVAL);
193     }
194     s->fft_data = av_calloc(s->channels, sizeof(*s->fft_data));
195     if (!s->fft_data)
196         return AVERROR(ENOMEM);
197     for (ch = 0; ch < s->channels; ch++) {
198         s->fft_data[ch] = av_calloc(s->win_size, sizeof(**s->fft_data));
199         if (!s->fft_data[ch])
200             return AVERROR(ENOMEM);
201     }
202
203     s->buffer = ff_get_audio_buffer(outlink, s->win_size * 2);
204     if (!s->buffer)
205         return AVERROR(ENOMEM);
206
207     /* pre-calc windowing function */
208     s->window_func_lut = av_realloc_f(s->window_func_lut, s->win_size,
209                                       sizeof(*s->window_func_lut));
210     if (!s->window_func_lut)
211         return AVERROR(ENOMEM);
212     ff_generate_window_func(s->window_func_lut, s->win_size, s->win_func, &overlap);
213     if (s->overlap == 1)
214         s->overlap = overlap;
215     s->hop_size = (1 - s->overlap) * s->win_size;
216     for (factor = 0, i = 0; i < s->win_size; i++) {
217         factor += s->window_func_lut[i] * s->window_func_lut[i];
218     }
219     s->factor = (factor / s->win_size) / FFMAX(1 / (1 - s->overlap) - 1, 1);
220
221     return 0;
222 }
223
224 static int request_frame(AVFilterLink *outlink)
225 {
226     AVFilterContext *ctx = outlink->src;
227     SpectrumSynthContext *s = ctx->priv;
228     int ret;
229
230     if (!s->magnitude) {
231         ret = ff_request_frame(ctx->inputs[0]);
232         if (ret < 0)
233             return ret;
234     }
235     if (!s->phase) {
236         ret = ff_request_frame(ctx->inputs[1]);
237         if (ret < 0)
238             return ret;
239     }
240     return 0;
241 }
242
243 static void read16_fft_bin(SpectrumSynthContext *s,
244                            int x, int y, int f, int ch)
245 {
246     const int m_linesize = s->magnitude->linesize[0];
247     const int p_linesize = s->phase->linesize[0];
248     const uint16_t *m = (uint16_t *)(s->magnitude->data[0] + y * m_linesize);
249     const uint16_t *p = (uint16_t *)(s->phase->data[0] + y * p_linesize);
250     float magnitude, phase;
251
252     switch (s->scale) {
253     case LINEAR:
254         magnitude = m[x] / (double)UINT16_MAX;
255         break;
256     case LOG:
257         magnitude = ff_exp10(((m[x] / (double)UINT16_MAX) - 1.) * 6.);
258         break;
259     }
260     phase = ((p[x] / (double)UINT16_MAX) * 2. - 1.) * M_PI;
261
262     s->fft_data[ch][f].re = magnitude * cos(phase);
263     s->fft_data[ch][f].im = magnitude * sin(phase);
264 }
265
266 static void read8_fft_bin(SpectrumSynthContext *s,
267                           int x, int y, int f, int ch)
268 {
269     const int m_linesize = s->magnitude->linesize[0];
270     const int p_linesize = s->phase->linesize[0];
271     const uint8_t *m = (uint8_t *)(s->magnitude->data[0] + y * m_linesize);
272     const uint8_t *p = (uint8_t *)(s->phase->data[0] + y * p_linesize);
273     float magnitude, phase;
274
275     switch (s->scale) {
276     case LINEAR:
277         magnitude = m[x] / (double)UINT8_MAX;
278         break;
279     case LOG:
280         magnitude = ff_exp10(((m[x] / (double)UINT8_MAX) - 1.) * 6.);
281         break;
282     }
283     phase = ((p[x] / (double)UINT8_MAX) * 2. - 1.) * M_PI;
284
285     s->fft_data[ch][f].re = magnitude * cos(phase);
286     s->fft_data[ch][f].im = magnitude * sin(phase);
287 }
288
289 static void read_fft_data(AVFilterContext *ctx, int x, int h, int ch)
290 {
291     SpectrumSynthContext *s = ctx->priv;
292     AVFilterLink *inlink = ctx->inputs[0];
293     int start = h * (s->channels - ch) - 1;
294     int end = h * (s->channels - ch - 1);
295     int y, f;
296
297     switch (s->orientation) {
298     case VERTICAL:
299         switch (inlink->format) {
300         case AV_PIX_FMT_YUV444P16:
301         case AV_PIX_FMT_GRAY16:
302             for (y = start, f = 0; y >= end; y--, f++) {
303                 read16_fft_bin(s, x, y, f, ch);
304             }
305             break;
306         case AV_PIX_FMT_YUVJ444P:
307         case AV_PIX_FMT_YUV444P:
308         case AV_PIX_FMT_GRAY8:
309             for (y = start, f = 0; y >= end; y--, f++) {
310                 read8_fft_bin(s, x, y, f, ch);
311             }
312             break;
313         }
314         break;
315     case HORIZONTAL:
316         switch (inlink->format) {
317         case AV_PIX_FMT_YUV444P16:
318         case AV_PIX_FMT_GRAY16:
319             for (y = end, f = 0; y <= start; y++, f++) {
320                 read16_fft_bin(s, y, x, f, ch);
321             }
322             break;
323         case AV_PIX_FMT_YUVJ444P:
324         case AV_PIX_FMT_YUV444P:
325         case AV_PIX_FMT_GRAY8:
326             for (y = end, f = 0; y <= start; y++, f++) {
327                 read8_fft_bin(s, y, x, f, ch);
328             }
329             break;
330         }
331         break;
332     }
333 }
334
335 static void synth_window(AVFilterContext *ctx, int x)
336 {
337     SpectrumSynthContext *s = ctx->priv;
338     const int h = s->size;
339     int nb = s->win_size;
340     int y, f, ch;
341
342     for (ch = 0; ch < s->channels; ch++) {
343         read_fft_data(ctx, x, h, ch);
344
345         for (y = h; y <= s->nb_freq; y++) {
346             s->fft_data[ch][y].re = 0;
347             s->fft_data[ch][y].im = 0;
348         }
349
350         for (y = s->nb_freq + 1, f = s->nb_freq - 1; y < nb; y++, f--) {
351             s->fft_data[ch][y].re =  s->fft_data[ch][f].re;
352             s->fft_data[ch][y].im = -s->fft_data[ch][f].im;
353         }
354
355         av_fft_permute(s->fft, s->fft_data[ch]);
356         av_fft_calc(s->fft, s->fft_data[ch]);
357     }
358 }
359
360 static int try_push_frame(AVFilterContext *ctx, int x)
361 {
362     SpectrumSynthContext *s = ctx->priv;
363     AVFilterLink *outlink = ctx->outputs[0];
364     const float factor = s->factor;
365     int ch, n, i, ret;
366     int start, end;
367     AVFrame *out;
368
369     synth_window(ctx, x);
370
371     for (ch = 0; ch < s->channels; ch++) {
372         float *buf = (float *)s->buffer->extended_data[ch];
373         int j, k;
374
375         start = s->start;
376         end = s->end;
377         k = end;
378         for (i = 0, j = start; j < k && i < s->win_size; i++, j++) {
379             buf[j] += s->fft_data[ch][i].re;
380         }
381
382         for (; i < s->win_size; i++, j++) {
383             buf[j] = s->fft_data[ch][i].re;
384         }
385
386         start += s->hop_size;
387         end = j;
388
389         if (start >= s->win_size) {
390             start -= s->win_size;
391             end -= s->win_size;
392
393             if (ch == s->channels - 1) {
394                 float *dst;
395                 int c;
396
397                 out = ff_get_audio_buffer(outlink, s->win_size);
398                 if (!out) {
399                     av_frame_free(&s->magnitude);
400                     av_frame_free(&s->phase);
401                     return AVERROR(ENOMEM);
402                 }
403
404                 out->pts = s->pts;
405                 s->pts += s->win_size;
406                 for (c = 0; c < s->channels; c++) {
407                     dst = (float *)out->extended_data[c];
408                     buf = (float *)s->buffer->extended_data[c];
409
410                     for (n = 0; n < s->win_size; n++) {
411                         dst[n] = buf[n] * factor;
412                     }
413                     memmove(buf, buf + s->win_size, s->win_size * 4);
414                 }
415
416                 ret = ff_filter_frame(outlink, out);
417             }
418         }
419     }
420
421     s->start = start;
422     s->end = end;
423
424     return 0;
425 }
426
427 static int try_push_frames(AVFilterContext *ctx)
428 {
429     SpectrumSynthContext *s = ctx->priv;
430     int ret, x;
431
432     if (!(s->magnitude && s->phase))
433         return 0;
434
435     switch (s->sliding) {
436     case REPLACE:
437         ret = try_push_frame(ctx, s->xpos);
438         s->xpos++;
439         if (s->xpos >= s->xend)
440             s->xpos = 0;
441         break;
442     case SCROLL:
443         s->xpos = s->xend - 1;
444         ret = try_push_frame(ctx, s->xpos);
445     case RSCROLL:
446         s->xpos = 0;
447         ret = try_push_frame(ctx, s->xpos);
448         break;
449         break;
450     case FULLFRAME:
451         for (x = 0; x < s->xend; x++) {
452             ret = try_push_frame(ctx, x);
453             if (ret < 0)
454                 break;
455         }
456         break;
457     }
458
459     av_frame_free(&s->magnitude);
460     av_frame_free(&s->phase);
461     return ret;
462 }
463
464 static int filter_frame_magnitude(AVFilterLink *inlink, AVFrame *magnitude)
465 {
466     AVFilterContext *ctx = inlink->dst;
467     SpectrumSynthContext *s = ctx->priv;
468
469     s->magnitude = magnitude;
470     return try_push_frames(ctx);
471 }
472
473 static int filter_frame_phase(AVFilterLink *inlink, AVFrame *phase)
474 {
475     AVFilterContext *ctx = inlink->dst;
476     SpectrumSynthContext *s = ctx->priv;
477
478     s->phase = phase;
479     return try_push_frames(ctx);
480 }
481
482 static av_cold void uninit(AVFilterContext *ctx)
483 {
484     SpectrumSynthContext *s = ctx->priv;
485     int i;
486
487     av_frame_free(&s->magnitude);
488     av_frame_free(&s->phase);
489     av_frame_free(&s->buffer);
490     av_fft_end(s->fft);
491     if (s->fft_data) {
492         for (i = 0; i < s->channels; i++)
493             av_freep(&s->fft_data[i]);
494     }
495     av_freep(&s->fft_data);
496     av_freep(&s->window_func_lut);
497 }
498
499 static const AVFilterPad spectrumsynth_inputs[] = {
500     {
501         .name         = "magnitude",
502         .type         = AVMEDIA_TYPE_VIDEO,
503         .filter_frame = filter_frame_magnitude,
504         .needs_fifo   = 1,
505     },
506     {
507         .name         = "phase",
508         .type         = AVMEDIA_TYPE_VIDEO,
509         .filter_frame = filter_frame_phase,
510         .needs_fifo   = 1,
511     },
512     { NULL }
513 };
514
515 static const AVFilterPad spectrumsynth_outputs[] = {
516     {
517         .name          = "default",
518         .type          = AVMEDIA_TYPE_AUDIO,
519         .config_props  = config_output,
520         .request_frame = request_frame,
521     },
522     { NULL }
523 };
524
525 AVFilter ff_vaf_spectrumsynth = {
526     .name          = "spectrumsynth",
527     .description   = NULL_IF_CONFIG_SMALL("Convert input spectrum videos to audio output."),
528     .uninit        = uninit,
529     .query_formats = query_formats,
530     .priv_size     = sizeof(SpectrumSynthContext),
531     .inputs        = spectrumsynth_inputs,
532     .outputs       = spectrumsynth_outputs,
533     .priv_class    = &spectrumsynth_class,
534 };