]> git.sesse.net Git - ffmpeg/blob - libavfilter/avf_showspectrum.c
Merge commit 'a43905f4ae261bdde87c300901d867b31961f57b'
[ffmpeg] / libavfilter / avf_showspectrum.c
1 /*
2  * Copyright (c) 2012-2013 Clément Bœsch
3  * Copyright (c) 2013 Rudolf Polzer <divverent@xonotic.org>
4  * Copyright (c) 2015 Paul B Mahol
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * audio to spectrum (video) transmedia filter, based on ffplay rdft showmode
26  * (by Michael Niedermayer) and lavfi/avf_showwaves (by Stefano Sabatini).
27  */
28
29 #include <math.h>
30
31 #include "libavcodec/avfft.h"
32 #include "libavutil/audio_fifo.h"
33 #include "libavutil/avassert.h"
34 #include "libavutil/channel_layout.h"
35 #include "libavutil/opt.h"
36 #include "audio.h"
37 #include "video.h"
38 #include "avfilter.h"
39 #include "internal.h"
40 #include "window_func.h"
41
42 enum DisplayMode  { COMBINED, SEPARATE, NB_MODES };
43 enum DisplayScale { LINEAR, SQRT, CBRT, LOG, FOURTHRT, FIFTHRT, NB_SCALES };
44 enum ColorMode    { CHANNEL, INTENSITY, RAINBOW, MORELAND, NEBULAE, FIRE, FIERY, NB_CLMODES };
45 enum SlideMode    { REPLACE, SCROLL, FULLFRAME, RSCROLL, NB_SLIDES };
46 enum Orientation  { VERTICAL, HORIZONTAL, NB_ORIENTATIONS };
47
48 typedef struct {
49     const AVClass *class;
50     int w, h;
51     AVFrame *outpicref;
52     int nb_display_channels;
53     int orientation;
54     int channel_width;
55     int channel_height;
56     int sliding;                ///< 1 if sliding mode, 0 otherwise
57     int mode;                   ///< channel display mode
58     int color_mode;             ///< display color scheme
59     int scale;
60     float saturation;           ///< color saturation multiplier
61     int xpos;                   ///< x position (current column)
62     FFTContext *fft;            ///< Fast Fourier Transform context
63     int fft_bits;               ///< number of bits (FFT window size = 1<<fft_bits)
64     FFTComplex **fft_data;      ///< bins holder for each (displayed) channels
65     float *window_func_lut;     ///< Window function LUT
66     float **magnitudes;
67     int win_func;
68     int win_size;
69     double win_scale;
70     float overlap;
71     int skip_samples;
72     float *combine_buffer;      ///< color combining buffer (3 * h items)
73     AVAudioFifo *fifo;
74     int64_t pts;
75     int single_pic;
76 } ShowSpectrumContext;
77
78 #define OFFSET(x) offsetof(ShowSpectrumContext, x)
79 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
80
81 static const AVOption showspectrum_options[] = {
82     { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
83     { "s",    "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
84     { "slide", "set sliding mode", OFFSET(sliding), AV_OPT_TYPE_INT, {.i64 = 0}, 0, NB_SLIDES-1, FLAGS, "slide" },
85         { "replace", "replace old columns with new", 0, AV_OPT_TYPE_CONST, {.i64=REPLACE}, 0, 0, FLAGS, "slide" },
86         { "scroll", "scroll from right to left", 0, AV_OPT_TYPE_CONST, {.i64=SCROLL}, 0, 0, FLAGS, "slide" },
87         { "rscroll", "scroll from left to right", 0, AV_OPT_TYPE_CONST, {.i64=RSCROLL}, 0, 0, FLAGS, "slide" },
88         { "fullframe", "return full frames", 0, AV_OPT_TYPE_CONST, {.i64=FULLFRAME}, 0, 0, FLAGS, "slide" },
89     { "mode", "set channel display mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=COMBINED}, COMBINED, NB_MODES-1, FLAGS, "mode" },
90         { "combined", "combined mode", 0, AV_OPT_TYPE_CONST, {.i64=COMBINED}, 0, 0, FLAGS, "mode" },
91         { "separate", "separate mode", 0, AV_OPT_TYPE_CONST, {.i64=SEPARATE}, 0, 0, FLAGS, "mode" },
92     { "color", "set channel coloring", OFFSET(color_mode), AV_OPT_TYPE_INT, {.i64=CHANNEL}, CHANNEL, NB_CLMODES-1, FLAGS, "color" },
93         { "channel",   "separate color for each channel", 0, AV_OPT_TYPE_CONST, {.i64=CHANNEL},   0, 0, FLAGS, "color" },
94         { "intensity", "intensity based coloring",        0, AV_OPT_TYPE_CONST, {.i64=INTENSITY}, 0, 0, FLAGS, "color" },
95         { "rainbow",   "rainbow based coloring",          0, AV_OPT_TYPE_CONST, {.i64=RAINBOW},   0, 0, FLAGS, "color" },
96         { "moreland",  "moreland based coloring",         0, AV_OPT_TYPE_CONST, {.i64=MORELAND},  0, 0, FLAGS, "color" },
97         { "nebulae",   "nebulae based coloring",          0, AV_OPT_TYPE_CONST, {.i64=NEBULAE},   0, 0, FLAGS, "color" },
98         { "fire",      "fire based coloring",             0, AV_OPT_TYPE_CONST, {.i64=FIRE},      0, 0, FLAGS, "color" },
99         { "fiery",     "fiery based coloring",            0, AV_OPT_TYPE_CONST, {.i64=FIERY},     0, 0, FLAGS, "color" },
100     { "scale", "set display scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64=SQRT}, LINEAR, NB_SCALES-1, FLAGS, "scale" },
101         { "sqrt", "square root", 0, AV_OPT_TYPE_CONST, {.i64=SQRT},   0, 0, FLAGS, "scale" },
102         { "cbrt", "cubic root",  0, AV_OPT_TYPE_CONST, {.i64=CBRT},   0, 0, FLAGS, "scale" },
103         { "4thrt","4th root",    0, AV_OPT_TYPE_CONST, {.i64=FOURTHRT}, 0, 0, FLAGS, "scale" },
104         { "5thrt","5th root",    0, AV_OPT_TYPE_CONST, {.i64=FIFTHRT},  0, 0, FLAGS, "scale" },
105         { "log",  "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG},    0, 0, FLAGS, "scale" },
106         { "lin",  "linear",      0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, FLAGS, "scale" },
107     { "saturation", "color saturation multiplier", OFFSET(saturation), AV_OPT_TYPE_FLOAT, {.dbl = 1}, -10, 10, FLAGS },
108     { "win_func", "set window function", OFFSET(win_func), AV_OPT_TYPE_INT, {.i64 = WFUNC_HANNING}, 0, NB_WFUNC-1, FLAGS, "win_func" },
109         { "rect",     "Rectangular",      0, AV_OPT_TYPE_CONST, {.i64=WFUNC_RECT},     0, 0, FLAGS, "win_func" },
110         { "bartlett", "Bartlett",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BARTLETT}, 0, 0, FLAGS, "win_func" },
111         { "hann",     "Hann",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, FLAGS, "win_func" },
112         { "hanning",  "Hanning",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, FLAGS, "win_func" },
113         { "hamming",  "Hamming",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HAMMING},  0, 0, FLAGS, "win_func" },
114         { "blackman", "Blackman",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BLACKMAN}, 0, 0, FLAGS, "win_func" },
115         { "welch",    "Welch",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_WELCH},    0, 0, FLAGS, "win_func" },
116         { "flattop",  "Flat-top",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_FLATTOP},  0, 0, FLAGS, "win_func" },
117         { "bharris",  "Blackman-Harris",  0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BHARRIS},  0, 0, FLAGS, "win_func" },
118         { "bnuttall", "Blackman-Nuttall", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BNUTTALL}, 0, 0, FLAGS, "win_func" },
119         { "bhann",    "Bartlett-Hann",    0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BHANN},    0, 0, FLAGS, "win_func" },
120         { "sine",     "Sine",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_SINE},     0, 0, FLAGS, "win_func" },
121         { "nuttall",  "Nuttall",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_NUTTALL},  0, 0, FLAGS, "win_func" },
122         { "lanczos",  "Lanczos",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_LANCZOS},  0, 0, FLAGS, "win_func" },
123         { "gauss",    "Gauss",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_GAUSS},    0, 0, FLAGS, "win_func" },
124     { "orientation", "set orientation", OFFSET(orientation), AV_OPT_TYPE_INT, {.i64=VERTICAL}, 0, NB_ORIENTATIONS-1, FLAGS, "orientation" },
125         { "vertical",   NULL, 0, AV_OPT_TYPE_CONST, {.i64=VERTICAL},   0, 0, FLAGS, "orientation" },
126         { "horizontal", NULL, 0, AV_OPT_TYPE_CONST, {.i64=HORIZONTAL}, 0, 0, FLAGS, "orientation" },
127     { "overlap", "set window overlap", OFFSET(overlap), AV_OPT_TYPE_FLOAT, {.dbl = 0}, 0, 1, FLAGS },
128     { NULL }
129 };
130
131 AVFILTER_DEFINE_CLASS(showspectrum);
132
133 static const struct ColorTable {
134     float a, y, u, v;
135 } color_table[][8] = {
136     [INTENSITY] = {
137     {    0,                  0,                  0,                   0 },
138     { 0.13, .03587126228984074,  .1573300977624594, -.02548747583751842 },
139     { 0.30, .18572281794568020,  .1772436246393981,  .17475554840414750 },
140     { 0.60, .28184980583656130, -.1593064119945782,  .47132074554608920 },
141     { 0.73, .65830621175547810, -.3716070802232764,  .24352759331252930 },
142     { 0.78, .76318535758242900, -.4307467689263783,  .16866496622310430 },
143     { 0.91, .95336363636363640, -.2045454545454546,  .03313636363636363 },
144     {    1,                  1,                  0,                   0 }},
145     [RAINBOW] = {
146     {    0,                  0,                  0,                   0 },
147     { 0.13,            44/256.,     (189-128)/256.,      (138-128)/256. },
148     { 0.25,            29/256.,     (186-128)/256.,      (119-128)/256. },
149     { 0.38,           119/256.,     (194-128)/256.,       (53-128)/256. },
150     { 0.60,           111/256.,      (73-128)/256.,       (59-128)/256. },
151     { 0.73,           205/256.,      (19-128)/256.,      (149-128)/256. },
152     { 0.86,           135/256.,      (83-128)/256.,      (200-128)/256. },
153     {    1,            73/256.,      (95-128)/256.,      (225-128)/256. }},
154     [MORELAND] = {
155     {    0,            44/256.,     (181-128)/256.,      (112-128)/256. },
156     { 0.13,           126/256.,     (177-128)/256.,      (106-128)/256. },
157     { 0.25,           164/256.,     (163-128)/256.,      (109-128)/256. },
158     { 0.38,           200/256.,     (140-128)/256.,      (120-128)/256. },
159     { 0.60,           201/256.,     (117-128)/256.,      (141-128)/256. },
160     { 0.73,           177/256.,     (103-128)/256.,      (165-128)/256. },
161     { 0.86,           136/256.,     (100-128)/256.,      (183-128)/256. },
162     {    1,            68/256.,     (117-128)/256.,      (203-128)/256. }},
163     [NEBULAE] = {
164     {    0,            10/256.,     (134-128)/256.,      (132-128)/256. },
165     { 0.23,            21/256.,     (137-128)/256.,      (130-128)/256. },
166     { 0.45,            35/256.,     (134-128)/256.,      (134-128)/256. },
167     { 0.57,            51/256.,     (130-128)/256.,      (139-128)/256. },
168     { 0.67,           104/256.,     (116-128)/256.,      (162-128)/256. },
169     { 0.77,           120/256.,     (105-128)/256.,      (188-128)/256. },
170     { 0.87,           140/256.,     (105-128)/256.,      (188-128)/256. },
171     {    1,                  1,                  0,                   0 }},
172     [FIRE] = {
173     {    0,                  0,                  0,                   0 },
174     { 0.23,            44/256.,     (132-128)/256.,      (127-128)/256. },
175     { 0.45,            62/256.,     (116-128)/256.,      (140-128)/256. },
176     { 0.57,            75/256.,     (105-128)/256.,      (152-128)/256. },
177     { 0.67,            95/256.,      (91-128)/256.,      (166-128)/256. },
178     { 0.77,           126/256.,      (74-128)/256.,      (172-128)/256. },
179     { 0.87,           164/256.,      (73-128)/256.,      (162-128)/256. },
180     {    1,                  1,                  0,                   0 }},
181     [FIERY] = {
182     {    0,                  0,                  0,                   0 },
183     { 0.23,            36/256.,     (116-128)/256.,      (163-128)/256. },
184     { 0.45,            52/256.,     (102-128)/256.,      (200-128)/256. },
185     { 0.57,           116/256.,      (84-128)/256.,      (196-128)/256. },
186     { 0.67,           157/256.,      (67-128)/256.,      (181-128)/256. },
187     { 0.77,           193/256.,      (40-128)/256.,      (155-128)/256. },
188     { 0.87,           221/256.,     (101-128)/256.,      (134-128)/256. },
189     {    1,                  1,                  0,                   0 }},
190 };
191
192 static av_cold void uninit(AVFilterContext *ctx)
193 {
194     ShowSpectrumContext *s = ctx->priv;
195     int i;
196
197     av_freep(&s->combine_buffer);
198     av_fft_end(s->fft);
199     if (s->fft_data) {
200         for (i = 0; i < s->nb_display_channels; i++)
201             av_freep(&s->fft_data[i]);
202     }
203     av_freep(&s->fft_data);
204     av_freep(&s->window_func_lut);
205     if (s->magnitudes) {
206         for (i = 0; i < s->nb_display_channels; i++)
207             av_freep(&s->magnitudes[i]);
208     }
209     av_freep(&s->magnitudes);
210     av_frame_free(&s->outpicref);
211     av_audio_fifo_free(s->fifo);
212 }
213
214 static int query_formats(AVFilterContext *ctx)
215 {
216     AVFilterFormats *formats = NULL;
217     AVFilterChannelLayouts *layouts = NULL;
218     AVFilterLink *inlink = ctx->inputs[0];
219     AVFilterLink *outlink = ctx->outputs[0];
220     static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE };
221     static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_NONE };
222     int ret;
223
224     /* set input audio formats */
225     formats = ff_make_format_list(sample_fmts);
226     if ((ret = ff_formats_ref(formats, &inlink->out_formats)) < 0)
227         return ret;
228
229     layouts = ff_all_channel_layouts();
230     if ((ret = ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts)) < 0)
231         return ret;
232
233     formats = ff_all_samplerates();
234     if ((ret = ff_formats_ref(formats, &inlink->out_samplerates)) < 0)
235         return ret;
236
237     /* set output video format */
238     formats = ff_make_format_list(pix_fmts);
239     if ((ret = ff_formats_ref(formats, &outlink->in_formats)) < 0)
240         return ret;
241
242     return 0;
243 }
244
245 static int config_output(AVFilterLink *outlink)
246 {
247     AVFilterContext *ctx = outlink->src;
248     AVFilterLink *inlink = ctx->inputs[0];
249     ShowSpectrumContext *s = ctx->priv;
250     int i, fft_bits, h, w;
251     float overlap;
252
253     if (!strcmp(ctx->filter->name, "showspectrumpic"))
254         s->single_pic = 1;
255
256     outlink->w = s->w;
257     outlink->h = s->h;
258
259     h = (s->mode == COMBINED || s->orientation == HORIZONTAL) ? outlink->h : outlink->h / inlink->channels;
260     w = (s->mode == COMBINED || s->orientation == VERTICAL)   ? outlink->w : outlink->w / inlink->channels;
261     s->channel_height = h;
262     s->channel_width  = w;
263
264     if (s->orientation == VERTICAL) {
265         /* FFT window size (precision) according to the requested output frame height */
266         for (fft_bits = 1; 1 << fft_bits < 2 * h; fft_bits++);
267     } else {
268         /* FFT window size (precision) according to the requested output frame width */
269         for (fft_bits = 1; 1 << fft_bits < 2 * w; fft_bits++);
270     }
271     s->win_size = 1 << fft_bits;
272
273     /* (re-)configuration if the video output changed (or first init) */
274     if (fft_bits != s->fft_bits) {
275         AVFrame *outpicref;
276
277         av_fft_end(s->fft);
278         s->fft = av_fft_init(fft_bits, 0);
279         if (!s->fft) {
280             av_log(ctx, AV_LOG_ERROR, "Unable to create FFT context. "
281                    "The window size might be too high.\n");
282             return AVERROR(EINVAL);
283         }
284         s->fft_bits = fft_bits;
285
286         /* FFT buffers: x2 for each (display) channel buffer.
287          * Note: we use free and malloc instead of a realloc-like function to
288          * make sure the buffer is aligned in memory for the FFT functions. */
289         for (i = 0; i < s->nb_display_channels; i++)
290             av_freep(&s->fft_data[i]);
291         av_freep(&s->fft_data);
292         s->nb_display_channels = inlink->channels;
293
294         s->magnitudes = av_calloc(s->nb_display_channels, sizeof(*s->magnitudes));
295         if (!s->magnitudes)
296             return AVERROR(ENOMEM);
297         for (i = 0; i < s->nb_display_channels; i++) {
298             s->magnitudes[i] = av_calloc(s->orientation == VERTICAL ? s->h : s->w, sizeof(**s->magnitudes));
299             if (!s->magnitudes[i])
300                 return AVERROR(ENOMEM);
301         }
302
303         s->fft_data = av_calloc(s->nb_display_channels, sizeof(*s->fft_data));
304         if (!s->fft_data)
305             return AVERROR(ENOMEM);
306         for (i = 0; i < s->nb_display_channels; i++) {
307             s->fft_data[i] = av_calloc(s->win_size, sizeof(**s->fft_data));
308             if (!s->fft_data[i])
309                 return AVERROR(ENOMEM);
310         }
311
312         /* pre-calc windowing function */
313         s->window_func_lut =
314             av_realloc_f(s->window_func_lut, s->win_size,
315                          sizeof(*s->window_func_lut));
316         if (!s->window_func_lut)
317             return AVERROR(ENOMEM);
318         ff_generate_window_func(s->window_func_lut, s->win_size, s->win_func, &overlap);
319         if (s->overlap == 1)
320             s->overlap = overlap;
321         s->skip_samples = (1. - s->overlap) * s->win_size;
322         if (s->skip_samples < 1) {
323             av_log(ctx, AV_LOG_ERROR, "overlap %f too big\n", s->overlap);
324             return AVERROR(EINVAL);
325         }
326
327         for (s->win_scale = 0, i = 0; i < s->win_size; i++) {
328             s->win_scale += s->window_func_lut[i] * s->window_func_lut[i];
329         }
330         s->win_scale = 1. / sqrt(s->win_scale);
331
332         /* prepare the initial picref buffer (black frame) */
333         av_frame_free(&s->outpicref);
334         s->outpicref = outpicref =
335             ff_get_video_buffer(outlink, outlink->w, outlink->h);
336         if (!outpicref)
337             return AVERROR(ENOMEM);
338         outlink->sample_aspect_ratio = (AVRational){1,1};
339         for (i = 0; i < outlink->h; i++) {
340             memset(outpicref->data[0] + i * outpicref->linesize[0],   0, outlink->w);
341             memset(outpicref->data[1] + i * outpicref->linesize[1], 128, outlink->w);
342             memset(outpicref->data[2] + i * outpicref->linesize[2], 128, outlink->w);
343         }
344     }
345
346     if ((s->orientation == VERTICAL   && s->xpos >= outlink->w) ||
347         (s->orientation == HORIZONTAL && s->xpos >= outlink->h))
348         s->xpos = 0;
349
350     outlink->frame_rate = av_make_q(inlink->sample_rate, s->win_size * (1.-s->overlap));
351     if (s->orientation == VERTICAL && s->sliding == FULLFRAME)
352         outlink->frame_rate.den *= outlink->w;
353     if (s->orientation == HORIZONTAL && s->sliding == FULLFRAME)
354         outlink->frame_rate.den *= outlink->h;
355
356     if (s->orientation == VERTICAL) {
357         s->combine_buffer =
358             av_realloc_f(s->combine_buffer, outlink->h * 3,
359                          sizeof(*s->combine_buffer));
360     } else {
361         s->combine_buffer =
362             av_realloc_f(s->combine_buffer, outlink->w * 3,
363                          sizeof(*s->combine_buffer));
364     }
365
366     av_log(ctx, AV_LOG_VERBOSE, "s:%dx%d FFT window size:%d\n",
367            s->w, s->h, s->win_size);
368
369     av_audio_fifo_free(s->fifo);
370     s->fifo = av_audio_fifo_alloc(inlink->format, inlink->channels, s->win_size);
371     if (!s->fifo)
372         return AVERROR(ENOMEM);
373     return 0;
374 }
375
376 static void run_fft(ShowSpectrumContext *s, AVFrame *fin)
377 {
378     int ch, n;
379
380     /* fill FFT input with the number of samples available */
381     for (ch = 0; ch < s->nb_display_channels; ch++) {
382         const float *p = (float *)fin->extended_data[ch];
383
384         for (n = 0; n < s->win_size; n++) {
385             s->fft_data[ch][n].re = p[n] * s->window_func_lut[n];
386             s->fft_data[ch][n].im = 0;
387         }
388     }
389
390     /* run FFT on each samples set */
391     for (ch = 0; ch < s->nb_display_channels; ch++) {
392         av_fft_permute(s->fft, s->fft_data[ch]);
393         av_fft_calc(s->fft, s->fft_data[ch]);
394     }
395 }
396
397 #define RE(y, ch) s->fft_data[ch][y].re
398 #define IM(y, ch) s->fft_data[ch][y].im
399 #define MAGNITUDE(y, ch) hypot(RE(y, ch), IM(y, ch))
400
401 static void calc_magnitudes(ShowSpectrumContext *s)
402 {
403     int ch, y, h = s->orientation == VERTICAL ? s->h : s->w;
404
405     for (ch = 0; ch < s->nb_display_channels; ch++) {
406         float *magnitudes = s->magnitudes[ch];
407
408         for (y = 0; y < h; y++)
409             magnitudes[y] = MAGNITUDE(y, ch);
410     }
411 }
412
413 static void acalc_magnitudes(ShowSpectrumContext *s)
414 {
415     int ch, y, h = s->orientation == VERTICAL ? s->h : s->w;
416
417     for (ch = 0; ch < s->nb_display_channels; ch++) {
418         float *magnitudes = s->magnitudes[ch];
419
420         for (y = 0; y < h; y++)
421             magnitudes[y] += MAGNITUDE(y, ch);
422     }
423 }
424
425 static void scale_magnitudes(ShowSpectrumContext *s, float scale)
426 {
427     int ch, y, h = s->orientation == VERTICAL ? s->h : s->w;
428
429     for (ch = 0; ch < s->nb_display_channels; ch++) {
430         float *magnitudes = s->magnitudes[ch];
431
432         for (y = 0; y < h; y++)
433             magnitudes[y] *= scale;
434     }
435 }
436
437 static void pick_color(ShowSpectrumContext *s,
438                        float yf, float uf, float vf,
439                        float a, float *out)
440 {
441     if (s->color_mode > CHANNEL) {
442         const int cm = s->color_mode;
443         float y, u, v;
444         int i;
445
446         for (i = 1; i < FF_ARRAY_ELEMS(color_table[cm]) - 1; i++)
447             if (color_table[cm][i].a >= a)
448                 break;
449         // i now is the first item >= the color
450         // now we know to interpolate between item i - 1 and i
451         if (a <= color_table[cm][i - 1].a) {
452             y = color_table[cm][i - 1].y;
453             u = color_table[cm][i - 1].u;
454             v = color_table[cm][i - 1].v;
455         } else if (a >= color_table[cm][i].a) {
456             y = color_table[cm][i].y;
457             u = color_table[cm][i].u;
458             v = color_table[cm][i].v;
459         } else {
460             float start = color_table[cm][i - 1].a;
461             float end = color_table[cm][i].a;
462             float lerpfrac = (a - start) / (end - start);
463             y = color_table[cm][i - 1].y * (1.0f - lerpfrac)
464               + color_table[cm][i].y * lerpfrac;
465             u = color_table[cm][i - 1].u * (1.0f - lerpfrac)
466               + color_table[cm][i].u * lerpfrac;
467             v = color_table[cm][i - 1].v * (1.0f - lerpfrac)
468               + color_table[cm][i].v * lerpfrac;
469         }
470
471         out[0] += y * yf;
472         out[1] += u * uf;
473         out[2] += v * vf;
474     } else {
475         out[0] += a * yf;
476         out[1] += a * uf;
477         out[2] += a * vf;
478     }
479 }
480
481 static void clear_combine_buffer(ShowSpectrumContext *s, int size)
482 {
483     int y;
484
485     for (y = 0; y < size; y++) {
486         s->combine_buffer[3 * y    ] = 0;
487         s->combine_buffer[3 * y + 1] = 127.5;
488         s->combine_buffer[3 * y + 2] = 127.5;
489     }
490 }
491
492 static int plot_spectrum_column(AVFilterLink *inlink, AVFrame *insamples)
493 {
494     int ret;
495     AVFilterContext *ctx = inlink->dst;
496     AVFilterLink *outlink = ctx->outputs[0];
497     ShowSpectrumContext *s = ctx->priv;
498     AVFrame *outpicref = s->outpicref;
499     const double w = s->win_scale;
500     int h = s->orientation == VERTICAL ? s->channel_height : s->channel_width;
501
502     int ch, plane, x, y;
503
504     /* fill a new spectrum column */
505     /* initialize buffer for combining to black */
506     clear_combine_buffer(s, s->orientation == VERTICAL ? outlink->h : outlink->w);
507
508     for (ch = 0; ch < s->nb_display_channels; ch++) {
509         float *magnitudes = s->magnitudes[ch];
510         float yf, uf, vf;
511
512         /* decide color range */
513         switch (s->mode) {
514         case COMBINED:
515             // reduce range by channel count
516             yf = 256.0f / s->nb_display_channels;
517             switch (s->color_mode) {
518             case RAINBOW:
519             case MORELAND:
520             case NEBULAE:
521             case FIRE:
522             case FIERY:
523             case INTENSITY:
524                 uf = yf;
525                 vf = yf;
526                 break;
527             case CHANNEL:
528                 /* adjust saturation for mixed UV coloring */
529                 /* this factor is correct for infinite channels, an approximation otherwise */
530                 uf = yf * M_PI;
531                 vf = yf * M_PI;
532                 break;
533             default:
534                 av_assert0(0);
535             }
536             break;
537         case SEPARATE:
538             // full range
539             yf = 256.0f;
540             uf = 256.0f;
541             vf = 256.0f;
542             break;
543         default:
544             av_assert0(0);
545         }
546
547         if (s->color_mode == CHANNEL) {
548             if (s->nb_display_channels > 1) {
549                 uf *= 0.5 * sin((2 * M_PI * ch) / s->nb_display_channels);
550                 vf *= 0.5 * cos((2 * M_PI * ch) / s->nb_display_channels);
551             } else {
552                 uf = 0.0f;
553                 vf = 0.0f;
554             }
555         }
556         uf *= s->saturation;
557         vf *= s->saturation;
558
559         /* draw the channel */
560         for (y = 0; y < h; y++) {
561             int row = (s->mode == COMBINED) ? y : ch * h + y;
562             float *out = &s->combine_buffer[3 * row];
563
564             /* get magnitude */
565             float a = w * magnitudes[y];
566
567             /* apply scale */
568             switch (s->scale) {
569             case LINEAR:
570                 break;
571             case SQRT:
572                 a = sqrt(a);
573                 break;
574             case CBRT:
575                 a = cbrt(a);
576                 break;
577             case FOURTHRT:
578                 a = pow(a, 0.25);
579                 break;
580             case FIFTHRT:
581                 a = pow(a, 0.20);
582                 break;
583             case LOG:
584                 a = 1 + log10(FFMAX(FFMIN(1, a * w), 1e-6)) / 6; // zero = -120dBFS
585                 break;
586             default:
587                 av_assert0(0);
588             }
589
590             pick_color(s, yf, uf, vf, a, out);
591         }
592     }
593
594     av_frame_make_writable(s->outpicref);
595     /* copy to output */
596     if (s->orientation == VERTICAL) {
597         if (s->sliding == SCROLL) {
598             for (plane = 0; plane < 3; plane++) {
599                 for (y = 0; y < outlink->h; y++) {
600                     uint8_t *p = outpicref->data[plane] +
601                                  y * outpicref->linesize[plane];
602                     memmove(p, p + 1, outlink->w - 1);
603                 }
604             }
605             s->xpos = outlink->w - 1;
606         } else if (s->sliding == RSCROLL) {
607             for (plane = 0; plane < 3; plane++) {
608                 for (y = 0; y < outlink->h; y++) {
609                     uint8_t *p = outpicref->data[plane] +
610                                  y * outpicref->linesize[plane];
611                     memmove(p + 1, p, outlink->w - 1);
612                 }
613             }
614             s->xpos = 0;
615         }
616         for (plane = 0; plane < 3; plane++) {
617             uint8_t *p = outpicref->data[plane] +
618                          (outlink->h - 1) * outpicref->linesize[plane] +
619                          s->xpos;
620             for (y = 0; y < outlink->h; y++) {
621                 *p = lrint(FFMAX(0, FFMIN(s->combine_buffer[3 * y + plane], 255)));
622                 p -= outpicref->linesize[plane];
623             }
624         }
625     } else {
626         if (s->sliding == SCROLL) {
627             for (plane = 0; plane < 3; plane++) {
628                 for (y = 1; y < outlink->h; y++) {
629                     memmove(outpicref->data[plane] + (y-1) * outpicref->linesize[plane],
630                             outpicref->data[plane] + (y  ) * outpicref->linesize[plane],
631                             outlink->w);
632                 }
633             }
634             s->xpos = outlink->h - 1;
635         } else if (s->sliding == RSCROLL) {
636             for (plane = 0; plane < 3; plane++) {
637                 for (y = outlink->h - 1; y >= 1; y--) {
638                     memmove(outpicref->data[plane] + (y  ) * outpicref->linesize[plane],
639                             outpicref->data[plane] + (y-1) * outpicref->linesize[plane],
640                             outlink->w);
641                 }
642             }
643             s->xpos = 0;
644         }
645         for (plane = 0; plane < 3; plane++) {
646             uint8_t *p = outpicref->data[plane] +
647                          s->xpos * outpicref->linesize[plane];
648             for (x = 0; x < outlink->w; x++) {
649                 *p = lrint(FFMAX(0, FFMIN(s->combine_buffer[3 * x + plane], 255)));
650                 p++;
651             }
652         }
653     }
654
655     if (s->sliding != FULLFRAME || s->xpos == 0)
656         outpicref->pts = insamples->pts;
657
658     s->xpos++;
659     if (s->orientation == VERTICAL && s->xpos >= outlink->w)
660         s->xpos = 0;
661     if (s->orientation == HORIZONTAL && s->xpos >= outlink->h)
662         s->xpos = 0;
663     if (!s->single_pic && (s->sliding != FULLFRAME || s->xpos == 0)) {
664         ret = ff_filter_frame(outlink, av_frame_clone(s->outpicref));
665         if (ret < 0)
666             return ret;
667     }
668
669     return s->win_size;
670 }
671
672 #if CONFIG_SHOWSPECTRUM_FILTER
673
674 static int request_frame(AVFilterLink *outlink)
675 {
676     ShowSpectrumContext *s = outlink->src->priv;
677     AVFilterLink *inlink = outlink->src->inputs[0];
678     unsigned i;
679     int ret;
680
681     ret = ff_request_frame(inlink);
682     if (ret == AVERROR_EOF && s->sliding == FULLFRAME && s->xpos > 0 &&
683         s->outpicref) {
684         if (s->orientation == VERTICAL) {
685             for (i = 0; i < outlink->h; i++) {
686                 memset(s->outpicref->data[0] + i * s->outpicref->linesize[0] + s->xpos,   0, outlink->w - s->xpos);
687                 memset(s->outpicref->data[1] + i * s->outpicref->linesize[1] + s->xpos, 128, outlink->w - s->xpos);
688                 memset(s->outpicref->data[2] + i * s->outpicref->linesize[2] + s->xpos, 128, outlink->w - s->xpos);
689             }
690         } else {
691             for (i = s->xpos; i < outlink->h; i++) {
692                 memset(s->outpicref->data[0] + i * s->outpicref->linesize[0],   0, outlink->w);
693                 memset(s->outpicref->data[1] + i * s->outpicref->linesize[1], 128, outlink->w);
694                 memset(s->outpicref->data[2] + i * s->outpicref->linesize[2], 128, outlink->w);
695             }
696         }
697         ret = ff_filter_frame(outlink, s->outpicref);
698         s->outpicref = NULL;
699     }
700
701     return ret;
702 }
703
704 static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
705 {
706     AVFilterContext *ctx = inlink->dst;
707     ShowSpectrumContext *s = ctx->priv;
708     AVFrame *fin = NULL;
709     int ret = 0;
710
711     av_audio_fifo_write(s->fifo, (void **)insamples->extended_data, insamples->nb_samples);
712     av_frame_free(&insamples);
713     while (av_audio_fifo_size(s->fifo) >= s->win_size) {
714         fin = ff_get_audio_buffer(inlink, s->win_size);
715         if (!fin) {
716             ret = AVERROR(ENOMEM);
717             goto fail;
718         }
719
720         fin->pts = s->pts;
721         s->pts += s->skip_samples;
722         ret = av_audio_fifo_peek(s->fifo, (void **)fin->extended_data, s->win_size);
723         if (ret < 0)
724             goto fail;
725
726         av_assert0(fin->nb_samples == s->win_size);
727
728         run_fft(s, fin);
729         calc_magnitudes(s);
730
731         ret = plot_spectrum_column(inlink, fin);
732         av_frame_free(&fin);
733         av_audio_fifo_drain(s->fifo, s->skip_samples);
734         if (ret < 0)
735             goto fail;
736     }
737
738 fail:
739     av_frame_free(&fin);
740     return ret;
741 }
742
743 static const AVFilterPad showspectrum_inputs[] = {
744     {
745         .name         = "default",
746         .type         = AVMEDIA_TYPE_AUDIO,
747         .filter_frame = filter_frame,
748     },
749     { NULL }
750 };
751
752 static const AVFilterPad showspectrum_outputs[] = {
753     {
754         .name          = "default",
755         .type          = AVMEDIA_TYPE_VIDEO,
756         .config_props  = config_output,
757         .request_frame = request_frame,
758     },
759     { NULL }
760 };
761
762 AVFilter ff_avf_showspectrum = {
763     .name          = "showspectrum",
764     .description   = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output."),
765     .uninit        = uninit,
766     .query_formats = query_formats,
767     .priv_size     = sizeof(ShowSpectrumContext),
768     .inputs        = showspectrum_inputs,
769     .outputs       = showspectrum_outputs,
770     .priv_class    = &showspectrum_class,
771 };
772 #endif // CONFIG_SHOWSPECTRUM_FILTER
773
774 #if CONFIG_SHOWSPECTRUMPIC_FILTER
775
776 static const AVOption showspectrumpic_options[] = {
777     { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "4096x2048"}, 0, 0, FLAGS },
778     { "s",    "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "4096x2048"}, 0, 0, FLAGS },
779     { "mode", "set channel display mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=COMBINED}, 0, NB_MODES-1, FLAGS, "mode" },
780         { "combined", "combined mode", 0, AV_OPT_TYPE_CONST, {.i64=COMBINED}, 0, 0, FLAGS, "mode" },
781         { "separate", "separate mode", 0, AV_OPT_TYPE_CONST, {.i64=SEPARATE}, 0, 0, FLAGS, "mode" },
782     { "color", "set channel coloring", OFFSET(color_mode), AV_OPT_TYPE_INT, {.i64=INTENSITY}, 0, NB_CLMODES-1, FLAGS, "color" },
783         { "channel",   "separate color for each channel", 0, AV_OPT_TYPE_CONST, {.i64=CHANNEL},   0, 0, FLAGS, "color" },
784         { "intensity", "intensity based coloring",        0, AV_OPT_TYPE_CONST, {.i64=INTENSITY}, 0, 0, FLAGS, "color" },
785         { "rainbow",   "rainbow based coloring",          0, AV_OPT_TYPE_CONST, {.i64=RAINBOW},   0, 0, FLAGS, "color" },
786         { "moreland",  "moreland based coloring",         0, AV_OPT_TYPE_CONST, {.i64=MORELAND},  0, 0, FLAGS, "color" },
787         { "nebulae",   "nebulae based coloring",          0, AV_OPT_TYPE_CONST, {.i64=NEBULAE},   0, 0, FLAGS, "color" },
788         { "fire",      "fire based coloring",             0, AV_OPT_TYPE_CONST, {.i64=FIRE},      0, 0, FLAGS, "color" },
789         { "fiery",     "fiery based coloring",            0, AV_OPT_TYPE_CONST, {.i64=FIERY},     0, 0, FLAGS, "color" },
790     { "scale", "set display scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64=LOG}, 0, NB_SCALES-1, FLAGS, "scale" },
791         { "sqrt", "square root", 0, AV_OPT_TYPE_CONST, {.i64=SQRT},   0, 0, FLAGS, "scale" },
792         { "cbrt", "cubic root",  0, AV_OPT_TYPE_CONST, {.i64=CBRT},   0, 0, FLAGS, "scale" },
793         { "4thrt","4th root",    0, AV_OPT_TYPE_CONST, {.i64=FOURTHRT}, 0, 0, FLAGS, "scale" },
794         { "5thrt","5th root",    0, AV_OPT_TYPE_CONST, {.i64=FIFTHRT},  0, 0, FLAGS, "scale" },
795         { "log",  "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG},    0, 0, FLAGS, "scale" },
796         { "lin",  "linear",      0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, FLAGS, "scale" },
797     { "saturation", "color saturation multiplier", OFFSET(saturation), AV_OPT_TYPE_FLOAT, {.dbl = 1}, -10, 10, FLAGS },
798     { "win_func", "set window function", OFFSET(win_func), AV_OPT_TYPE_INT, {.i64 = WFUNC_HANNING}, 0, NB_WFUNC-1, FLAGS, "win_func" },
799         { "rect",     "Rectangular",      0, AV_OPT_TYPE_CONST, {.i64=WFUNC_RECT},     0, 0, FLAGS, "win_func" },
800         { "bartlett", "Bartlett",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BARTLETT}, 0, 0, FLAGS, "win_func" },
801         { "hann",     "Hann",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, FLAGS, "win_func" },
802         { "hanning",  "Hanning",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, FLAGS, "win_func" },
803         { "hamming",  "Hamming",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HAMMING},  0, 0, FLAGS, "win_func" },
804         { "blackman", "Blackman",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BLACKMAN}, 0, 0, FLAGS, "win_func" },
805         { "welch",    "Welch",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_WELCH},    0, 0, FLAGS, "win_func" },
806         { "flattop",  "Flat-top",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_FLATTOP},  0, 0, FLAGS, "win_func" },
807         { "bharris",  "Blackman-Harris",  0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BHARRIS},  0, 0, FLAGS, "win_func" },
808         { "bnuttall", "Blackman-Nuttall", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BNUTTALL}, 0, 0, FLAGS, "win_func" },
809         { "bhann",    "Bartlett-Hann",    0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BHANN},    0, 0, FLAGS, "win_func" },
810         { "sine",     "Sine",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_SINE},     0, 0, FLAGS, "win_func" },
811         { "nuttall",  "Nuttall",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_NUTTALL},  0, 0, FLAGS, "win_func" },
812         { "lanczos",  "Lanczos",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_LANCZOS},  0, 0, FLAGS, "win_func" },
813         { "gauss",    "Gauss",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_GAUSS},    0, 0, FLAGS, "win_func" },
814     { "orientation", "set orientation", OFFSET(orientation), AV_OPT_TYPE_INT, {.i64=VERTICAL}, 0, NB_ORIENTATIONS-1, FLAGS, "orientation" },
815         { "vertical",   NULL, 0, AV_OPT_TYPE_CONST, {.i64=VERTICAL},   0, 0, FLAGS, "orientation" },
816         { "horizontal", NULL, 0, AV_OPT_TYPE_CONST, {.i64=HORIZONTAL}, 0, 0, FLAGS, "orientation" },
817     { NULL }
818 };
819
820 AVFILTER_DEFINE_CLASS(showspectrumpic);
821
822 static int showspectrumpic_request_frame(AVFilterLink *outlink)
823 {
824     ShowSpectrumContext *s = outlink->src->priv;
825     AVFilterLink *inlink = outlink->src->inputs[0];
826     int ret;
827
828     ret = ff_request_frame(inlink);
829     if (ret == AVERROR_EOF && s->outpicref) {
830         int samples = av_audio_fifo_size(s->fifo);
831         int consumed = 0;
832         int x = 0, sz = s->orientation == VERTICAL ? s->w : s->h;
833         int ch, spf, spb;
834         AVFrame *fin;
835
836         spf = s->win_size * (samples / ((s->win_size * sz) * ceil(samples / (float)(s->win_size * sz))));
837         spb = (samples / (spf * sz)) * spf;
838
839         fin = ff_get_audio_buffer(inlink, s->win_size);
840         if (!fin)
841             return AVERROR(ENOMEM);
842
843         while (x < sz) {
844             ret = av_audio_fifo_peek(s->fifo, (void **)fin->extended_data, s->win_size);
845             if (ret < 0) {
846                 av_frame_free(&fin);
847                 return ret;
848             }
849
850             av_audio_fifo_drain(s->fifo, spf);
851
852             if (ret < s->win_size) {
853                 for (ch = 0; ch < s->nb_display_channels; ch++) {
854                     memset(fin->extended_data[ch] + ret * sizeof(float), 0,
855                            (s->win_size - ret) * sizeof(float));
856                 }
857             }
858
859             run_fft(s, fin);
860             acalc_magnitudes(s);
861
862             consumed += spf;
863             if (consumed >= spb) {
864                 int h = s->orientation == VERTICAL ? s->h : s->w;
865
866                 scale_magnitudes(s, 1. / (consumed / spf));
867                 plot_spectrum_column(inlink, fin);
868                 consumed = 0;
869                 x++;
870                 for (ch = 0; ch < s->nb_display_channels; ch++)
871                     memset(s->magnitudes[ch], 0, h * sizeof(float));
872             }
873         }
874
875         av_frame_free(&fin);
876         s->outpicref->pts = 0;
877         ret = ff_filter_frame(outlink, s->outpicref);
878         s->outpicref = NULL;
879     }
880
881     return ret;
882 }
883
884 static int showspectrumpic_filter_frame(AVFilterLink *inlink, AVFrame *insamples)
885 {
886     AVFilterContext *ctx = inlink->dst;
887     ShowSpectrumContext *s = ctx->priv;
888     int ret;
889
890     ret = av_audio_fifo_write(s->fifo, (void **)insamples->extended_data, insamples->nb_samples);
891     av_frame_free(&insamples);
892     return ret;
893 }
894
895 static const AVFilterPad showspectrumpic_inputs[] = {
896     {
897         .name         = "default",
898         .type         = AVMEDIA_TYPE_AUDIO,
899         .filter_frame = showspectrumpic_filter_frame,
900     },
901     { NULL }
902 };
903
904 static const AVFilterPad showspectrumpic_outputs[] = {
905     {
906         .name          = "default",
907         .type          = AVMEDIA_TYPE_VIDEO,
908         .config_props  = config_output,
909         .request_frame = showspectrumpic_request_frame,
910     },
911     { NULL }
912 };
913
914 AVFilter ff_avf_showspectrumpic = {
915     .name          = "showspectrumpic",
916     .description   = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output single picture."),
917     .uninit        = uninit,
918     .query_formats = query_formats,
919     .priv_size     = sizeof(ShowSpectrumContext),
920     .inputs        = showspectrumpic_inputs,
921     .outputs       = showspectrumpic_outputs,
922     .priv_class    = &showspectrumpic_class,
923 };
924
925 #endif // CONFIG_SHOWSPECTRUMPIC_FILTER