]> git.sesse.net Git - ffmpeg/blob - libavfilter/avf_showspectrum.c
avfilter/avf_showspectrum: add cividis colormap
[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/avstring.h"
35 #include "libavutil/channel_layout.h"
36 #include "libavutil/opt.h"
37 #include "libavutil/parseutils.h"
38 #include "libavutil/xga_font_data.h"
39 #include "audio.h"
40 #include "video.h"
41 #include "avfilter.h"
42 #include "filters.h"
43 #include "internal.h"
44 #include "window_func.h"
45
46 enum DisplayMode  { COMBINED, SEPARATE, NB_MODES };
47 enum DataMode     { D_MAGNITUDE, D_PHASE, NB_DMODES };
48 enum DisplayScale { LINEAR, SQRT, CBRT, LOG, FOURTHRT, FIFTHRT, NB_SCALES };
49 enum ColorMode    { CHANNEL, INTENSITY, RAINBOW, MORELAND, NEBULAE, FIRE, FIERY, FRUIT, COOL, MAGMA, GREEN, VIRIDIS, PLASMA, CIVIDIS, NB_CLMODES };
50 enum SlideMode    { REPLACE, SCROLL, FULLFRAME, RSCROLL, NB_SLIDES };
51 enum Orientation  { VERTICAL, HORIZONTAL, NB_ORIENTATIONS };
52
53 typedef struct ShowSpectrumContext {
54     const AVClass *class;
55     int w, h;
56     char *rate_str;
57     AVRational auto_frame_rate;
58     AVRational frame_rate;
59     AVFrame *outpicref;
60     int nb_display_channels;
61     int orientation;
62     int channel_width;
63     int channel_height;
64     int sliding;                ///< 1 if sliding mode, 0 otherwise
65     int mode;                   ///< channel display mode
66     int color_mode;             ///< display color scheme
67     int scale;
68     float saturation;           ///< color saturation multiplier
69     float rotation;             ///< color rotation
70     int start, stop;            ///< zoom mode
71     int data;
72     int xpos;                   ///< x position (current column)
73     FFTContext **fft;           ///< Fast Fourier Transform context
74     FFTContext **ifft;          ///< Inverse Fast Fourier Transform context
75     int fft_bits;               ///< number of bits (FFT window size = 1<<fft_bits)
76     FFTComplex **fft_data;      ///< bins holder for each (displayed) channels
77     FFTComplex **fft_scratch;   ///< scratch buffers
78     float *window_func_lut;     ///< Window function LUT
79     float **magnitudes;
80     float **phases;
81     int win_func;
82     int win_size;
83     int buf_size;
84     double win_scale;
85     float overlap;
86     float gain;
87     int consumed;
88     int hop_size;
89     float *combine_buffer;      ///< color combining buffer (3 * h items)
90     float **color_buffer;       ///< color buffer (3 * h * ch items)
91     AVAudioFifo *fifo;
92     int64_t pts;
93     int64_t old_pts;
94     int old_len;
95     int single_pic;
96     int legend;
97     int start_x, start_y;
98 } ShowSpectrumContext;
99
100 #define OFFSET(x) offsetof(ShowSpectrumContext, x)
101 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
102
103 static const AVOption showspectrum_options[] = {
104     { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
105     { "s",    "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
106     { "slide", "set sliding mode", OFFSET(sliding), AV_OPT_TYPE_INT, {.i64 = 0}, 0, NB_SLIDES-1, FLAGS, "slide" },
107         { "replace", "replace old columns with new", 0, AV_OPT_TYPE_CONST, {.i64=REPLACE}, 0, 0, FLAGS, "slide" },
108         { "scroll", "scroll from right to left", 0, AV_OPT_TYPE_CONST, {.i64=SCROLL}, 0, 0, FLAGS, "slide" },
109         { "fullframe", "return full frames", 0, AV_OPT_TYPE_CONST, {.i64=FULLFRAME}, 0, 0, FLAGS, "slide" },
110         { "rscroll", "scroll from left to right", 0, AV_OPT_TYPE_CONST, {.i64=RSCROLL}, 0, 0, FLAGS, "slide" },
111     { "mode", "set channel display mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=COMBINED}, COMBINED, NB_MODES-1, FLAGS, "mode" },
112         { "combined", "combined mode", 0, AV_OPT_TYPE_CONST, {.i64=COMBINED}, 0, 0, FLAGS, "mode" },
113         { "separate", "separate mode", 0, AV_OPT_TYPE_CONST, {.i64=SEPARATE}, 0, 0, FLAGS, "mode" },
114     { "color", "set channel coloring", OFFSET(color_mode), AV_OPT_TYPE_INT, {.i64=CHANNEL}, CHANNEL, NB_CLMODES-1, FLAGS, "color" },
115         { "channel",   "separate color for each channel", 0, AV_OPT_TYPE_CONST, {.i64=CHANNEL},   0, 0, FLAGS, "color" },
116         { "intensity", "intensity based coloring",        0, AV_OPT_TYPE_CONST, {.i64=INTENSITY}, 0, 0, FLAGS, "color" },
117         { "rainbow",   "rainbow based coloring",          0, AV_OPT_TYPE_CONST, {.i64=RAINBOW},   0, 0, FLAGS, "color" },
118         { "moreland",  "moreland based coloring",         0, AV_OPT_TYPE_CONST, {.i64=MORELAND},  0, 0, FLAGS, "color" },
119         { "nebulae",   "nebulae based coloring",          0, AV_OPT_TYPE_CONST, {.i64=NEBULAE},   0, 0, FLAGS, "color" },
120         { "fire",      "fire based coloring",             0, AV_OPT_TYPE_CONST, {.i64=FIRE},      0, 0, FLAGS, "color" },
121         { "fiery",     "fiery based coloring",            0, AV_OPT_TYPE_CONST, {.i64=FIERY},     0, 0, FLAGS, "color" },
122         { "fruit",     "fruit based coloring",            0, AV_OPT_TYPE_CONST, {.i64=FRUIT},     0, 0, FLAGS, "color" },
123         { "cool",      "cool based coloring",             0, AV_OPT_TYPE_CONST, {.i64=COOL},      0, 0, FLAGS, "color" },
124         { "magma",     "magma based coloring",            0, AV_OPT_TYPE_CONST, {.i64=MAGMA},     0, 0, FLAGS, "color" },
125         { "green",     "green based coloring",            0, AV_OPT_TYPE_CONST, {.i64=GREEN},     0, 0, FLAGS, "color" },
126         { "viridis",   "viridis based coloring",          0, AV_OPT_TYPE_CONST, {.i64=VIRIDIS},   0, 0, FLAGS, "color" },
127         { "plasma",    "plasma based coloring",           0, AV_OPT_TYPE_CONST, {.i64=PLASMA},    0, 0, FLAGS, "color" },
128         { "cividis",   "cividis based coloring",          0, AV_OPT_TYPE_CONST, {.i64=CIVIDIS},   0, 0, FLAGS, "color" },
129     { "scale", "set display scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64=SQRT}, LINEAR, NB_SCALES-1, FLAGS, "scale" },
130         { "lin",  "linear",      0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, FLAGS, "scale" },
131         { "sqrt", "square root", 0, AV_OPT_TYPE_CONST, {.i64=SQRT},   0, 0, FLAGS, "scale" },
132         { "cbrt", "cubic root",  0, AV_OPT_TYPE_CONST, {.i64=CBRT},   0, 0, FLAGS, "scale" },
133         { "log",  "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG},    0, 0, FLAGS, "scale" },
134         { "4thrt","4th root",    0, AV_OPT_TYPE_CONST, {.i64=FOURTHRT}, 0, 0, FLAGS, "scale" },
135         { "5thrt","5th root",    0, AV_OPT_TYPE_CONST, {.i64=FIFTHRT},  0, 0, FLAGS, "scale" },
136     { "saturation", "color saturation multiplier", OFFSET(saturation), AV_OPT_TYPE_FLOAT, {.dbl = 1}, -10, 10, FLAGS },
137     { "win_func", "set window function", OFFSET(win_func), AV_OPT_TYPE_INT, {.i64 = WFUNC_HANNING}, 0, NB_WFUNC-1, FLAGS, "win_func" },
138         { "rect",     "Rectangular",      0, AV_OPT_TYPE_CONST, {.i64=WFUNC_RECT},     0, 0, FLAGS, "win_func" },
139         { "bartlett", "Bartlett",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BARTLETT}, 0, 0, FLAGS, "win_func" },
140         { "hann",     "Hann",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, FLAGS, "win_func" },
141         { "hanning",  "Hanning",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, FLAGS, "win_func" },
142         { "hamming",  "Hamming",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HAMMING},  0, 0, FLAGS, "win_func" },
143         { "blackman", "Blackman",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BLACKMAN}, 0, 0, FLAGS, "win_func" },
144         { "welch",    "Welch",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_WELCH},    0, 0, FLAGS, "win_func" },
145         { "flattop",  "Flat-top",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_FLATTOP},  0, 0, FLAGS, "win_func" },
146         { "bharris",  "Blackman-Harris",  0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BHARRIS},  0, 0, FLAGS, "win_func" },
147         { "bnuttall", "Blackman-Nuttall", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BNUTTALL}, 0, 0, FLAGS, "win_func" },
148         { "bhann",    "Bartlett-Hann",    0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BHANN},    0, 0, FLAGS, "win_func" },
149         { "sine",     "Sine",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_SINE},     0, 0, FLAGS, "win_func" },
150         { "nuttall",  "Nuttall",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_NUTTALL},  0, 0, FLAGS, "win_func" },
151         { "lanczos",  "Lanczos",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_LANCZOS},  0, 0, FLAGS, "win_func" },
152         { "gauss",    "Gauss",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_GAUSS},    0, 0, FLAGS, "win_func" },
153         { "tukey",    "Tukey",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_TUKEY},    0, 0, FLAGS, "win_func" },
154         { "dolph",    "Dolph-Chebyshev",  0, AV_OPT_TYPE_CONST, {.i64=WFUNC_DOLPH},    0, 0, FLAGS, "win_func" },
155         { "cauchy",   "Cauchy",           0, AV_OPT_TYPE_CONST, {.i64=WFUNC_CAUCHY},   0, 0, FLAGS, "win_func" },
156         { "parzen",   "Parzen",           0, AV_OPT_TYPE_CONST, {.i64=WFUNC_PARZEN},   0, 0, FLAGS, "win_func" },
157         { "poisson",  "Poisson",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_POISSON},  0, 0, FLAGS, "win_func" },
158         { "bohman",   "Bohman",           0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BOHMAN},   0, 0, FLAGS, "win_func" },
159     { "orientation", "set orientation", OFFSET(orientation), AV_OPT_TYPE_INT, {.i64=VERTICAL}, 0, NB_ORIENTATIONS-1, FLAGS, "orientation" },
160         { "vertical",   NULL, 0, AV_OPT_TYPE_CONST, {.i64=VERTICAL},   0, 0, FLAGS, "orientation" },
161         { "horizontal", NULL, 0, AV_OPT_TYPE_CONST, {.i64=HORIZONTAL}, 0, 0, FLAGS, "orientation" },
162     { "overlap", "set window overlap", OFFSET(overlap), AV_OPT_TYPE_FLOAT, {.dbl = 0}, 0, 1, FLAGS },
163     { "gain", "set scale gain", OFFSET(gain), AV_OPT_TYPE_FLOAT, {.dbl = 1}, 0, 128, FLAGS },
164     { "data", "set data mode", OFFSET(data), AV_OPT_TYPE_INT, {.i64 = 0}, 0, NB_DMODES-1, FLAGS, "data" },
165         { "magnitude", NULL, 0, AV_OPT_TYPE_CONST, {.i64=D_MAGNITUDE}, 0, 0, FLAGS, "data" },
166         { "phase",     NULL, 0, AV_OPT_TYPE_CONST, {.i64=D_PHASE},     0, 0, FLAGS, "data" },
167     { "rotation", "color rotation", OFFSET(rotation), AV_OPT_TYPE_FLOAT, {.dbl = 0}, -1, 1, FLAGS },
168     { "start", "start frequency", OFFSET(start), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT32_MAX, FLAGS },
169     { "stop",  "stop frequency",  OFFSET(stop),  AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT32_MAX, FLAGS },
170     { "fps",   "set video rate",  OFFSET(rate_str), AV_OPT_TYPE_STRING, {.str = "auto"}, 0, 0, FLAGS },
171     { "legend", "draw legend", OFFSET(legend), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, FLAGS },
172     { NULL }
173 };
174
175 AVFILTER_DEFINE_CLASS(showspectrum);
176
177 static const struct ColorTable {
178     float a, y, u, v;
179 } color_table[][8] = {
180     [INTENSITY] = {
181     {    0,                  0,                  0,                   0 },
182     { 0.13, .03587126228984074,  .1573300977624594, -.02548747583751842 },
183     { 0.30, .18572281794568020,  .1772436246393981,  .17475554840414750 },
184     { 0.60, .28184980583656130, -.1593064119945782,  .47132074554608920 },
185     { 0.73, .65830621175547810, -.3716070802232764,  .24352759331252930 },
186     { 0.78, .76318535758242900, -.4307467689263783,  .16866496622310430 },
187     { 0.91, .95336363636363640, -.2045454545454546,  .03313636363636363 },
188     {    1,                  1,                  0,                   0 }},
189     [RAINBOW] = {
190     {    0,                  0,                  0,                   0 },
191     { 0.13,            44/256.,     (189-128)/256.,      (138-128)/256. },
192     { 0.25,            29/256.,     (186-128)/256.,      (119-128)/256. },
193     { 0.38,           119/256.,     (194-128)/256.,       (53-128)/256. },
194     { 0.60,           111/256.,      (73-128)/256.,       (59-128)/256. },
195     { 0.73,           205/256.,      (19-128)/256.,      (149-128)/256. },
196     { 0.86,           135/256.,      (83-128)/256.,      (200-128)/256. },
197     {    1,            73/256.,      (95-128)/256.,      (225-128)/256. }},
198     [MORELAND] = {
199     {    0,            44/256.,     (181-128)/256.,      (112-128)/256. },
200     { 0.13,           126/256.,     (177-128)/256.,      (106-128)/256. },
201     { 0.25,           164/256.,     (163-128)/256.,      (109-128)/256. },
202     { 0.38,           200/256.,     (140-128)/256.,      (120-128)/256. },
203     { 0.60,           201/256.,     (117-128)/256.,      (141-128)/256. },
204     { 0.73,           177/256.,     (103-128)/256.,      (165-128)/256. },
205     { 0.86,           136/256.,     (100-128)/256.,      (183-128)/256. },
206     {    1,            68/256.,     (117-128)/256.,      (203-128)/256. }},
207     [NEBULAE] = {
208     {    0,            10/256.,     (134-128)/256.,      (132-128)/256. },
209     { 0.23,            21/256.,     (137-128)/256.,      (130-128)/256. },
210     { 0.45,            35/256.,     (134-128)/256.,      (134-128)/256. },
211     { 0.57,            51/256.,     (130-128)/256.,      (139-128)/256. },
212     { 0.67,           104/256.,     (116-128)/256.,      (162-128)/256. },
213     { 0.77,           120/256.,     (105-128)/256.,      (188-128)/256. },
214     { 0.87,           140/256.,     (105-128)/256.,      (188-128)/256. },
215     {    1,                  1,                  0,                   0 }},
216     [FIRE] = {
217     {    0,                  0,                  0,                   0 },
218     { 0.23,            44/256.,     (132-128)/256.,      (127-128)/256. },
219     { 0.45,            62/256.,     (116-128)/256.,      (140-128)/256. },
220     { 0.57,            75/256.,     (105-128)/256.,      (152-128)/256. },
221     { 0.67,            95/256.,      (91-128)/256.,      (166-128)/256. },
222     { 0.77,           126/256.,      (74-128)/256.,      (172-128)/256. },
223     { 0.87,           164/256.,      (73-128)/256.,      (162-128)/256. },
224     {    1,                  1,                  0,                   0 }},
225     [FIERY] = {
226     {    0,                  0,                  0,                   0 },
227     { 0.23,            36/256.,     (116-128)/256.,      (163-128)/256. },
228     { 0.45,            52/256.,     (102-128)/256.,      (200-128)/256. },
229     { 0.57,           116/256.,      (84-128)/256.,      (196-128)/256. },
230     { 0.67,           157/256.,      (67-128)/256.,      (181-128)/256. },
231     { 0.77,           193/256.,      (40-128)/256.,      (155-128)/256. },
232     { 0.87,           221/256.,     (101-128)/256.,      (134-128)/256. },
233     {    1,                  1,                  0,                   0 }},
234     [FRUIT] = {
235     {    0,                  0,                  0,                   0 },
236     { 0.20,            29/256.,     (136-128)/256.,      (119-128)/256. },
237     { 0.30,            60/256.,     (119-128)/256.,       (90-128)/256. },
238     { 0.40,            85/256.,      (91-128)/256.,       (85-128)/256. },
239     { 0.50,           116/256.,      (70-128)/256.,      (105-128)/256. },
240     { 0.60,           151/256.,      (50-128)/256.,      (146-128)/256. },
241     { 0.70,           191/256.,      (63-128)/256.,      (178-128)/256. },
242     {    1,            98/256.,      (80-128)/256.,      (221-128)/256. }},
243     [COOL] = {
244     {    0,                  0,                  0,                   0 },
245     {  .15,                  0,                 .5,                 -.5 },
246     {    1,                  1,                -.5,                  .5 }},
247     [MAGMA] = {
248     {    0,                  0,                  0,                   0 },
249     { 0.10,            23/256.,     (175-128)/256.,      (120-128)/256. },
250     { 0.23,            43/256.,     (158-128)/256.,      (144-128)/256. },
251     { 0.35,            85/256.,     (138-128)/256.,      (179-128)/256. },
252     { 0.48,            96/256.,     (128-128)/256.,      (189-128)/256. },
253     { 0.64,           128/256.,     (103-128)/256.,      (214-128)/256. },
254     { 0.92,           205/256.,      (80-128)/256.,      (152-128)/256. },
255     {    1,                  1,                  0,                   0 }},
256     [GREEN] = {
257     {    0,                  0,                  0,                   0 },
258     {  .75,                 .5,                  0,                 -.5 },
259     {    1,                  1,                  0,                   0 }},
260     [VIRIDIS] = {
261     {    0,                  0,                  0,                   0 },
262     { 0.10,          0x39/255.,   (0x9D -128)/255.,    (0x8F -128)/255. },
263     { 0.23,          0x5C/255.,   (0x9A -128)/255.,    (0x68 -128)/255. },
264     { 0.35,          0x69/255.,   (0x93 -128)/255.,    (0x57 -128)/255. },
265     { 0.48,          0x76/255.,   (0x88 -128)/255.,    (0x4B -128)/255. },
266     { 0.64,          0x8A/255.,   (0x72 -128)/255.,    (0x4F -128)/255. },
267     { 0.80,          0xA3/255.,   (0x50 -128)/255.,    (0x66 -128)/255. },
268     {    1,          0xCC/255.,   (0x2F -128)/255.,    (0x87 -128)/255. }},
269     [PLASMA] = {
270     {    0,                  0,                  0,                   0 },
271     { 0.10,          0x27/255.,   (0xC2 -128)/255.,    (0x82 -128)/255. },
272     { 0.58,          0x5B/255.,   (0x9A -128)/255.,    (0xAE -128)/255. },
273     { 0.70,          0x89/255.,   (0x44 -128)/255.,    (0xAB -128)/255. },
274     { 0.80,          0xB4/255.,   (0x2B -128)/255.,    (0x9E -128)/255. },
275     { 0.91,          0xD2/255.,   (0x38 -128)/255.,    (0x92 -128)/255. },
276     {    1,                  1,                  0,                  0. }},
277     [CIVIDIS] = {
278     {    0,                  0,                  0,                   0 },
279     { 0.20,          0x28/255.,   (0x98 -128)/255.,    (0x6F -128)/255. },
280     { 0.50,          0x48/255.,   (0x95 -128)/255.,    (0x74 -128)/255. },
281     { 0.63,          0x69/255.,   (0x84 -128)/255.,    (0x7F -128)/255. },
282     { 0.76,          0x89/255.,   (0x75 -128)/255.,    (0x84 -128)/255. },
283     { 0.90,          0xCE/255.,   (0x35 -128)/255.,    (0x95 -128)/255. },
284     {    1,                  1,                  0,                  0. }},
285 };
286
287 static av_cold void uninit(AVFilterContext *ctx)
288 {
289     ShowSpectrumContext *s = ctx->priv;
290     int i;
291
292     av_freep(&s->combine_buffer);
293     if (s->fft) {
294         for (i = 0; i < s->nb_display_channels; i++)
295             av_fft_end(s->fft[i]);
296     }
297     av_freep(&s->fft);
298     if (s->ifft) {
299         for (i = 0; i < s->nb_display_channels; i++)
300             av_fft_end(s->ifft[i]);
301     }
302     av_freep(&s->ifft);
303     if (s->fft_data) {
304         for (i = 0; i < s->nb_display_channels; i++)
305             av_freep(&s->fft_data[i]);
306     }
307     av_freep(&s->fft_data);
308     if (s->fft_scratch) {
309         for (i = 0; i < s->nb_display_channels; i++)
310             av_freep(&s->fft_scratch[i]);
311     }
312     av_freep(&s->fft_scratch);
313     if (s->color_buffer) {
314         for (i = 0; i < s->nb_display_channels; i++)
315             av_freep(&s->color_buffer[i]);
316     }
317     av_freep(&s->color_buffer);
318     av_freep(&s->window_func_lut);
319     if (s->magnitudes) {
320         for (i = 0; i < s->nb_display_channels; i++)
321             av_freep(&s->magnitudes[i]);
322     }
323     av_freep(&s->magnitudes);
324     av_frame_free(&s->outpicref);
325     av_audio_fifo_free(s->fifo);
326     if (s->phases) {
327         for (i = 0; i < s->nb_display_channels; i++)
328             av_freep(&s->phases[i]);
329     }
330     av_freep(&s->phases);
331 }
332
333 static int query_formats(AVFilterContext *ctx)
334 {
335     AVFilterFormats *formats = NULL;
336     AVFilterChannelLayouts *layouts = NULL;
337     AVFilterLink *inlink = ctx->inputs[0];
338     AVFilterLink *outlink = ctx->outputs[0];
339     static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE };
340     static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_NONE };
341     int ret;
342
343     /* set input audio formats */
344     formats = ff_make_format_list(sample_fmts);
345     if ((ret = ff_formats_ref(formats, &inlink->out_formats)) < 0)
346         return ret;
347
348     layouts = ff_all_channel_layouts();
349     if ((ret = ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts)) < 0)
350         return ret;
351
352     formats = ff_all_samplerates();
353     if ((ret = ff_formats_ref(formats, &inlink->out_samplerates)) < 0)
354         return ret;
355
356     /* set output video format */
357     formats = ff_make_format_list(pix_fmts);
358     if ((ret = ff_formats_ref(formats, &outlink->in_formats)) < 0)
359         return ret;
360
361     return 0;
362 }
363
364 static int run_channel_fft(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
365 {
366     ShowSpectrumContext *s = ctx->priv;
367     AVFilterLink *inlink = ctx->inputs[0];
368     const float *window_func_lut = s->window_func_lut;
369     AVFrame *fin = arg;
370     const int ch = jobnr;
371     int n;
372
373     /* fill FFT input with the number of samples available */
374     const float *p = (float *)fin->extended_data[ch];
375
376     for (n = 0; n < s->win_size; n++) {
377         s->fft_data[ch][n].re = p[n] * window_func_lut[n];
378         s->fft_data[ch][n].im = 0;
379     }
380
381     if (s->stop) {
382         double theta, phi, psi, a, b, S, c;
383         FFTComplex *g = s->fft_data[ch];
384         FFTComplex *h = s->fft_scratch[ch];
385         int L = s->buf_size;
386         int N = s->win_size;
387         int M = s->win_size / 2;
388
389         phi = 2.0 * M_PI * (s->stop - s->start) / (double)inlink->sample_rate / (M - 1);
390         theta = 2.0 * M_PI * s->start / (double)inlink->sample_rate;
391
392         for (int n = 0; n < M; n++) {
393             h[n].re = cos(n * n / 2.0 * phi);
394             h[n].im = sin(n * n / 2.0 * phi);
395         }
396
397         for (int n = M; n < L; n++) {
398             h[n].re = 0.0;
399             h[n].im = 0.0;
400         }
401
402         for (int n = L - N; n < L; n++) {
403             h[n].re = cos((L - n) * (L - n) / 2.0 * phi);
404             h[n].im = sin((L - n) * (L - n) / 2.0 * phi);
405         }
406
407         for (int n = 0; n < N; n++) {
408             g[n].re = s->fft_data[ch][n].re;
409             g[n].im = s->fft_data[ch][n].im;
410         }
411
412         for (int n = N; n < L; n++) {
413             g[n].re = 0.;
414             g[n].im = 0.;
415         }
416
417         for (int n = 0; n < N; n++) {
418             psi = n * theta + n * n / 2.0 * phi;
419             c =  cos(psi);
420             S = -sin(psi);
421             a = c * g[n].re - S * g[n].im;
422             b = S * g[n].re + c * g[n].im;
423             g[n].re = a;
424             g[n].im = b;
425         }
426
427         av_fft_permute(s->fft[ch], h);
428         av_fft_calc(s->fft[ch], h);
429
430         av_fft_permute(s->fft[ch], g);
431         av_fft_calc(s->fft[ch], g);
432
433         for (int n = 0; n < L; n++) {
434             c = g[n].re;
435             S = g[n].im;
436             a = c * h[n].re - S * h[n].im;
437             b = S * h[n].re + c * h[n].im;
438
439             g[n].re = a / L;
440             g[n].im = b / L;
441         }
442
443         av_fft_permute(s->ifft[ch], g);
444         av_fft_calc(s->ifft[ch], g);
445
446         for (int k = 0; k < M; k++) {
447             psi = k * k / 2.0 * phi;
448             c =  cos(psi);
449             S = -sin(psi);
450             a = c * g[k].re - S * g[k].im;
451             b = S * g[k].re + c * g[k].im;
452             s->fft_data[ch][k].re = a;
453             s->fft_data[ch][k].im = b;
454         }
455     } else {
456         /* run FFT on each samples set */
457         av_fft_permute(s->fft[ch], s->fft_data[ch]);
458         av_fft_calc(s->fft[ch], s->fft_data[ch]);
459     }
460
461     return 0;
462 }
463
464 static void drawtext(AVFrame *pic, int x, int y, const char *txt, int o)
465 {
466     const uint8_t *font;
467     int font_height;
468     int i;
469
470     font = avpriv_cga_font,   font_height =  8;
471
472     for (i = 0; txt[i]; i++) {
473         int char_y, mask;
474
475         if (o) {
476             for (char_y = font_height - 1; char_y >= 0; char_y--) {
477                 uint8_t *p = pic->data[0] + (y + i * 10) * pic->linesize[0] + x;
478                 for (mask = 0x80; mask; mask >>= 1) {
479                     if (font[txt[i] * font_height + font_height - 1 - char_y] & mask)
480                         p[char_y] = ~p[char_y];
481                     p += pic->linesize[0];
482                 }
483             }
484         } else {
485             uint8_t *p = pic->data[0] + y*pic->linesize[0] + (x + i*8);
486             for (char_y = 0; char_y < font_height; char_y++) {
487                 for (mask = 0x80; mask; mask >>= 1) {
488                     if (font[txt[i] * font_height + char_y] & mask)
489                         *p = ~(*p);
490                     p++;
491                 }
492                 p += pic->linesize[0] - 8;
493             }
494         }
495     }
496 }
497
498 static void color_range(ShowSpectrumContext *s, int ch,
499                         float *yf, float *uf, float *vf)
500 {
501     switch (s->mode) {
502     case COMBINED:
503         // reduce range by channel count
504         *yf = 256.0f / s->nb_display_channels;
505         switch (s->color_mode) {
506         case RAINBOW:
507         case MORELAND:
508         case NEBULAE:
509         case FIRE:
510         case FIERY:
511         case FRUIT:
512         case COOL:
513         case GREEN:
514         case VIRIDIS:
515         case PLASMA:
516         case CIVIDIS:
517         case MAGMA:
518         case INTENSITY:
519             *uf = *yf;
520             *vf = *yf;
521             break;
522         case CHANNEL:
523             /* adjust saturation for mixed UV coloring */
524             /* this factor is correct for infinite channels, an approximation otherwise */
525             *uf = *yf * M_PI;
526             *vf = *yf * M_PI;
527             break;
528         default:
529             av_assert0(0);
530         }
531         break;
532     case SEPARATE:
533         // full range
534         *yf = 256.0f;
535         *uf = 256.0f;
536         *vf = 256.0f;
537         break;
538     default:
539         av_assert0(0);
540     }
541
542     if (s->color_mode == CHANNEL) {
543         if (s->nb_display_channels > 1) {
544             *uf *= 0.5 * sin((2 * M_PI * ch) / s->nb_display_channels + M_PI * s->rotation);
545             *vf *= 0.5 * cos((2 * M_PI * ch) / s->nb_display_channels + M_PI * s->rotation);
546         } else {
547             *uf *= 0.5 * sin(M_PI * s->rotation);
548             *vf *= 0.5 * cos(M_PI * s->rotation + M_PI_2);
549         }
550     } else {
551         *uf += *uf * sin(M_PI * s->rotation);
552         *vf += *vf * cos(M_PI * s->rotation + M_PI_2);
553     }
554
555     *uf *= s->saturation;
556     *vf *= s->saturation;
557 }
558
559 static void pick_color(ShowSpectrumContext *s,
560                        float yf, float uf, float vf,
561                        float a, float *out)
562 {
563     if (s->color_mode > CHANNEL) {
564         const int cm = s->color_mode;
565         float y, u, v;
566         int i;
567
568         for (i = 1; i < FF_ARRAY_ELEMS(color_table[cm]) - 1; i++)
569             if (color_table[cm][i].a >= a)
570                 break;
571         // i now is the first item >= the color
572         // now we know to interpolate between item i - 1 and i
573         if (a <= color_table[cm][i - 1].a) {
574             y = color_table[cm][i - 1].y;
575             u = color_table[cm][i - 1].u;
576             v = color_table[cm][i - 1].v;
577         } else if (a >= color_table[cm][i].a) {
578             y = color_table[cm][i].y;
579             u = color_table[cm][i].u;
580             v = color_table[cm][i].v;
581         } else {
582             float start = color_table[cm][i - 1].a;
583             float end = color_table[cm][i].a;
584             float lerpfrac = (a - start) / (end - start);
585             y = color_table[cm][i - 1].y * (1.0f - lerpfrac)
586               + color_table[cm][i].y * lerpfrac;
587             u = color_table[cm][i - 1].u * (1.0f - lerpfrac)
588               + color_table[cm][i].u * lerpfrac;
589             v = color_table[cm][i - 1].v * (1.0f - lerpfrac)
590               + color_table[cm][i].v * lerpfrac;
591         }
592
593         out[0] = y * yf;
594         out[1] = u * uf;
595         out[2] = v * vf;
596     } else {
597         out[0] = a * yf;
598         out[1] = a * uf;
599         out[2] = a * vf;
600     }
601 }
602
603 static char *get_time(AVFilterContext *ctx, float seconds, int x)
604 {
605     char *units;
606
607     if (x == 0)
608         units = av_asprintf("0");
609     else if (log10(seconds) > 6)
610         units = av_asprintf("%.2fh", seconds / (60 * 60));
611     else if (log10(seconds) > 3)
612         units = av_asprintf("%.2fm", seconds / 60);
613     else
614         units = av_asprintf("%.2fs", seconds);
615     return units;
616 }
617
618 static int draw_legend(AVFilterContext *ctx, int samples)
619 {
620     ShowSpectrumContext *s = ctx->priv;
621     AVFilterLink *inlink = ctx->inputs[0];
622     AVFilterLink *outlink = ctx->outputs[0];
623     int ch, y, x = 0, sz = s->orientation == VERTICAL ? s->w : s->h;
624     int multi = (s->mode == SEPARATE && s->color_mode == CHANNEL);
625     float spp = samples / (float)sz;
626     char *text;
627     uint8_t *dst;
628     char chlayout_str[128];
629
630     av_get_channel_layout_string(chlayout_str, sizeof(chlayout_str), inlink->channels,
631                                  inlink->channel_layout);
632
633     text = av_asprintf("%d Hz | %s", inlink->sample_rate, chlayout_str);
634
635     drawtext(s->outpicref, 2, outlink->h - 10, "CREATED BY LIBAVFILTER", 0);
636     drawtext(s->outpicref, outlink->w - 2 - strlen(text) * 10, outlink->h - 10, text, 0);
637     if (s->stop) {
638         char *text = av_asprintf("Zoom: %d Hz - %d Hz", s->start, s->stop);
639         drawtext(s->outpicref, outlink->w - 2 - strlen(text) * 10, 3, text, 0);
640         av_freep(&text);
641     }
642
643     av_freep(&text);
644
645     dst = s->outpicref->data[0] + (s->start_y - 1) * s->outpicref->linesize[0] + s->start_x - 1;
646     for (x = 0; x < s->w + 1; x++)
647         dst[x] = 200;
648     dst = s->outpicref->data[0] + (s->start_y + s->h) * s->outpicref->linesize[0] + s->start_x - 1;
649     for (x = 0; x < s->w + 1; x++)
650         dst[x] = 200;
651     for (y = 0; y < s->h + 2; y++) {
652         dst = s->outpicref->data[0] + (y + s->start_y - 1) * s->outpicref->linesize[0];
653         dst[s->start_x - 1] = 200;
654         dst[s->start_x + s->w] = 200;
655     }
656     if (s->orientation == VERTICAL) {
657         int h = s->mode == SEPARATE ? s->h / s->nb_display_channels : s->h;
658         int hh = s->mode == SEPARATE ? -(s->h % s->nb_display_channels) + 1 : 1;
659         for (ch = 0; ch < (s->mode == SEPARATE ? s->nb_display_channels : 1); ch++) {
660             for (y = 0; y < h; y += 20) {
661                 dst = s->outpicref->data[0] + (s->start_y + h * (ch + 1) - y - hh) * s->outpicref->linesize[0];
662                 dst[s->start_x - 2] = 200;
663                 dst[s->start_x + s->w + 1] = 200;
664             }
665             for (y = 0; y < h; y += 40) {
666                 dst = s->outpicref->data[0] + (s->start_y + h * (ch + 1) - y - hh) * s->outpicref->linesize[0];
667                 dst[s->start_x - 3] = 200;
668                 dst[s->start_x + s->w + 2] = 200;
669             }
670             dst = s->outpicref->data[0] + (s->start_y - 2) * s->outpicref->linesize[0] + s->start_x;
671             for (x = 0; x < s->w; x+=40)
672                 dst[x] = 200;
673             dst = s->outpicref->data[0] + (s->start_y - 3) * s->outpicref->linesize[0] + s->start_x;
674             for (x = 0; x < s->w; x+=80)
675                 dst[x] = 200;
676             dst = s->outpicref->data[0] + (s->h + s->start_y + 1) * s->outpicref->linesize[0] + s->start_x;
677             for (x = 0; x < s->w; x+=40) {
678                 dst[x] = 200;
679             }
680             dst = s->outpicref->data[0] + (s->h + s->start_y + 2) * s->outpicref->linesize[0] + s->start_x;
681             for (x = 0; x < s->w; x+=80) {
682                 dst[x] = 200;
683             }
684             for (y = 0; y < h; y += 40) {
685                 float range = s->stop ? s->stop - s->start : inlink->sample_rate / 2;
686                 float hertz = s->start + y * range / (float)(1 << (int)ceil(log2(h)));
687                 char *units;
688
689                 if (hertz == 0)
690                     units = av_asprintf("DC");
691                 else
692                     units = av_asprintf("%.2f", hertz);
693                 if (!units)
694                     return AVERROR(ENOMEM);
695
696                 drawtext(s->outpicref, s->start_x - 8 * strlen(units) - 4, h * (ch + 1) + s->start_y - y - 4 - hh, units, 0);
697                 av_free(units);
698             }
699         }
700
701         for (x = 0; x < s->w && s->single_pic; x+=80) {
702             float seconds = x * spp / inlink->sample_rate;
703             char *units = get_time(ctx, seconds, x);
704
705             drawtext(s->outpicref, s->start_x + x - 4 * strlen(units), s->h + s->start_y + 6, units, 0);
706             drawtext(s->outpicref, s->start_x + x - 4 * strlen(units), s->start_y - 12, units, 0);
707             av_free(units);
708         }
709
710         drawtext(s->outpicref, outlink->w / 2 - 4 * 4, outlink->h - s->start_y / 2, "TIME", 0);
711         drawtext(s->outpicref, s->start_x / 7, outlink->h / 2 - 14 * 4, "FREQUENCY (Hz)", 1);
712     } else {
713         int w = s->mode == SEPARATE ? s->w / s->nb_display_channels : s->w;
714         for (y = 0; y < s->h; y += 20) {
715             dst = s->outpicref->data[0] + (s->start_y + y) * s->outpicref->linesize[0];
716             dst[s->start_x - 2] = 200;
717             dst[s->start_x + s->w + 1] = 200;
718         }
719         for (y = 0; y < s->h; y += 40) {
720             dst = s->outpicref->data[0] + (s->start_y + y) * s->outpicref->linesize[0];
721             dst[s->start_x - 3] = 200;
722             dst[s->start_x + s->w + 2] = 200;
723         }
724         for (ch = 0; ch < (s->mode == SEPARATE ? s->nb_display_channels : 1); ch++) {
725             dst = s->outpicref->data[0] + (s->start_y - 2) * s->outpicref->linesize[0] + s->start_x + w * ch;
726             for (x = 0; x < w; x+=40)
727                 dst[x] = 200;
728             dst = s->outpicref->data[0] + (s->start_y - 3) * s->outpicref->linesize[0] + s->start_x + w * ch;
729             for (x = 0; x < w; x+=80)
730                 dst[x] = 200;
731             dst = s->outpicref->data[0] + (s->h + s->start_y + 1) * s->outpicref->linesize[0] + s->start_x + w * ch;
732             for (x = 0; x < w; x+=40) {
733                 dst[x] = 200;
734             }
735             dst = s->outpicref->data[0] + (s->h + s->start_y + 2) * s->outpicref->linesize[0] + s->start_x + w * ch;
736             for (x = 0; x < w; x+=80) {
737                 dst[x] = 200;
738             }
739             for (x = 0; x < w - 79; x += 80) {
740                 float range = s->stop ? s->stop - s->start : inlink->sample_rate / 2;
741                 float hertz = s->start + x * range / (float)(1 << (int)ceil(log2(w)));
742                 char *units;
743
744                 if (hertz == 0)
745                     units = av_asprintf("DC");
746                 else
747                     units = av_asprintf("%.2f", hertz);
748                 if (!units)
749                     return AVERROR(ENOMEM);
750
751                 drawtext(s->outpicref, s->start_x - 4 * strlen(units) + x + w * ch, s->start_y - 12, units, 0);
752                 drawtext(s->outpicref, s->start_x - 4 * strlen(units) + x + w * ch, s->h + s->start_y + 6, units, 0);
753                 av_free(units);
754             }
755         }
756         for (y = 0; y < s->h && s->single_pic; y+=40) {
757             float seconds = y * spp / inlink->sample_rate;
758             char *units = get_time(ctx, seconds, x);
759
760             drawtext(s->outpicref, s->start_x - 8 * strlen(units) - 4, s->start_y + y - 4, units, 0);
761             av_free(units);
762         }
763         drawtext(s->outpicref, s->start_x / 7, outlink->h / 2 - 4 * 4, "TIME", 1);
764         drawtext(s->outpicref, outlink->w / 2 - 14 * 4, outlink->h - s->start_y / 2, "FREQUENCY (Hz)", 0);
765     }
766
767     for (ch = 0; ch < (multi ? s->nb_display_channels : 1); ch++) {
768         int h = multi ? s->h / s->nb_display_channels : s->h;
769
770         for (y = 0; y < h; y++) {
771             float out[3] = { 0., 127.5, 127.5};
772             int chn;
773
774             for (chn = 0; chn < (s->mode == SEPARATE ? 1 : s->nb_display_channels); chn++) {
775                 float yf, uf, vf;
776                 int channel = (multi) ? s->nb_display_channels - ch - 1 : chn;
777                 float lout[3];
778
779                 color_range(s, channel, &yf, &uf, &vf);
780                 pick_color(s, yf, uf, vf, y / (float)h, lout);
781                 out[0] += lout[0];
782                 out[1] += lout[1];
783                 out[2] += lout[2];
784             }
785             memset(s->outpicref->data[0]+(s->start_y + h * (ch + 1) - y - 1) * s->outpicref->linesize[0] + s->w + s->start_x + 20, av_clip_uint8(out[0]), 10);
786             memset(s->outpicref->data[1]+(s->start_y + h * (ch + 1) - y - 1) * s->outpicref->linesize[1] + s->w + s->start_x + 20, av_clip_uint8(out[1]), 10);
787             memset(s->outpicref->data[2]+(s->start_y + h * (ch + 1) - y - 1) * s->outpicref->linesize[2] + s->w + s->start_x + 20, av_clip_uint8(out[2]), 10);
788         }
789
790         for (y = 0; ch == 0 && y < h; y += h / 10) {
791             float value = 120.0 * log10(1. - y / (float)h);
792             char *text;
793
794             if (value < -120)
795                 break;
796             text = av_asprintf("%.0f dB", value);
797             if (!text)
798                 continue;
799             drawtext(s->outpicref, s->w + s->start_x + 35, s->start_y + y - 5, text, 0);
800             av_free(text);
801         }
802     }
803
804     return 0;
805 }
806
807 static int config_output(AVFilterLink *outlink)
808 {
809     AVFilterContext *ctx = outlink->src;
810     AVFilterLink *inlink = ctx->inputs[0];
811     ShowSpectrumContext *s = ctx->priv;
812     int i, fft_bits, h, w;
813     float overlap;
814
815     s->stop = FFMIN(s->stop, inlink->sample_rate / 2);
816     if (s->stop && s->stop <= s->start) {
817         av_log(ctx, AV_LOG_ERROR, "Stop frequency should be greater than start.\n");
818         return AVERROR(EINVAL);
819     }
820
821     if (!strcmp(ctx->filter->name, "showspectrumpic"))
822         s->single_pic = 1;
823
824     outlink->w = s->w;
825     outlink->h = s->h;
826     outlink->sample_aspect_ratio = (AVRational){1,1};
827
828     if (s->legend) {
829         s->start_x = (log10(inlink->sample_rate) + 1) * 25;
830         s->start_y = 64;
831         outlink->w += s->start_x * 2;
832         outlink->h += s->start_y * 2;
833     }
834
835     h = (s->mode == COMBINED || s->orientation == HORIZONTAL) ? s->h : s->h / inlink->channels;
836     w = (s->mode == COMBINED || s->orientation == VERTICAL)   ? s->w : s->w / inlink->channels;
837     s->channel_height = h;
838     s->channel_width  = w;
839
840     if (s->orientation == VERTICAL) {
841         /* FFT window size (precision) according to the requested output frame height */
842         for (fft_bits = 1; 1 << fft_bits < 2 * h; fft_bits++);
843     } else {
844         /* FFT window size (precision) according to the requested output frame width */
845         for (fft_bits = 1; 1 << fft_bits < 2 * w; fft_bits++);
846     }
847
848     s->win_size = 1 << fft_bits;
849     s->buf_size = s->win_size << !!s->stop;
850
851     if (!s->fft) {
852         s->fft = av_calloc(inlink->channels, sizeof(*s->fft));
853         if (!s->fft)
854             return AVERROR(ENOMEM);
855     }
856
857     if (s->stop) {
858         if (!s->ifft) {
859             s->ifft = av_calloc(inlink->channels, sizeof(*s->ifft));
860             if (!s->ifft)
861                 return AVERROR(ENOMEM);
862         }
863     }
864
865     /* (re-)configuration if the video output changed (or first init) */
866     if (fft_bits != s->fft_bits) {
867         AVFrame *outpicref;
868
869         s->fft_bits = fft_bits;
870
871         /* FFT buffers: x2 for each (display) channel buffer.
872          * Note: we use free and malloc instead of a realloc-like function to
873          * make sure the buffer is aligned in memory for the FFT functions. */
874         for (i = 0; i < s->nb_display_channels; i++) {
875             if (s->stop) {
876                 av_fft_end(s->ifft[i]);
877                 av_freep(&s->fft_scratch[i]);
878             }
879             av_fft_end(s->fft[i]);
880             av_freep(&s->fft_data[i]);
881         }
882         av_freep(&s->fft_data);
883
884         s->nb_display_channels = inlink->channels;
885         for (i = 0; i < s->nb_display_channels; i++) {
886             s->fft[i] = av_fft_init(fft_bits + !!s->stop, 0);
887             if (s->stop) {
888                 s->ifft[i] = av_fft_init(fft_bits + !!s->stop, 1);
889                 if (!s->ifft[i]) {
890                     av_log(ctx, AV_LOG_ERROR, "Unable to create Inverse FFT context. "
891                            "The window size might be too high.\n");
892                     return AVERROR(EINVAL);
893                 }
894             }
895             if (!s->fft[i]) {
896                 av_log(ctx, AV_LOG_ERROR, "Unable to create FFT context. "
897                        "The window size might be too high.\n");
898                 return AVERROR(EINVAL);
899             }
900         }
901
902         s->magnitudes = av_calloc(s->nb_display_channels, sizeof(*s->magnitudes));
903         if (!s->magnitudes)
904             return AVERROR(ENOMEM);
905         for (i = 0; i < s->nb_display_channels; i++) {
906             s->magnitudes[i] = av_calloc(s->orientation == VERTICAL ? s->h : s->w, sizeof(**s->magnitudes));
907             if (!s->magnitudes[i])
908                 return AVERROR(ENOMEM);
909         }
910
911         s->phases = av_calloc(s->nb_display_channels, sizeof(*s->phases));
912         if (!s->phases)
913             return AVERROR(ENOMEM);
914         for (i = 0; i < s->nb_display_channels; i++) {
915             s->phases[i] = av_calloc(s->orientation == VERTICAL ? s->h : s->w, sizeof(**s->phases));
916             if (!s->phases[i])
917                 return AVERROR(ENOMEM);
918         }
919
920         av_freep(&s->color_buffer);
921         s->color_buffer = av_calloc(s->nb_display_channels, sizeof(*s->color_buffer));
922         if (!s->color_buffer)
923             return AVERROR(ENOMEM);
924         for (i = 0; i < s->nb_display_channels; i++) {
925             s->color_buffer[i] = av_calloc(s->orientation == VERTICAL ? s->h * 3 : s->w * 3, sizeof(**s->color_buffer));
926             if (!s->color_buffer[i])
927                 return AVERROR(ENOMEM);
928         }
929
930         s->fft_data = av_calloc(s->nb_display_channels, sizeof(*s->fft_data));
931         if (!s->fft_data)
932             return AVERROR(ENOMEM);
933         s->fft_scratch = av_calloc(s->nb_display_channels, sizeof(*s->fft_scratch));
934         if (!s->fft_scratch)
935             return AVERROR(ENOMEM);
936         for (i = 0; i < s->nb_display_channels; i++) {
937             s->fft_data[i] = av_calloc(s->buf_size, sizeof(**s->fft_data));
938             if (!s->fft_data[i])
939                 return AVERROR(ENOMEM);
940
941             s->fft_scratch[i] = av_calloc(s->buf_size, sizeof(**s->fft_scratch));
942             if (!s->fft_scratch[i])
943                 return AVERROR(ENOMEM);
944         }
945
946         /* pre-calc windowing function */
947         s->window_func_lut =
948             av_realloc_f(s->window_func_lut, s->win_size,
949                          sizeof(*s->window_func_lut));
950         if (!s->window_func_lut)
951             return AVERROR(ENOMEM);
952         generate_window_func(s->window_func_lut, s->win_size, s->win_func, &overlap);
953         if (s->overlap == 1)
954             s->overlap = overlap;
955         s->hop_size = (1. - s->overlap) * s->win_size;
956         if (s->hop_size < 1) {
957             av_log(ctx, AV_LOG_ERROR, "overlap %f too big\n", s->overlap);
958             return AVERROR(EINVAL);
959         }
960
961         for (s->win_scale = 0, i = 0; i < s->win_size; i++) {
962             s->win_scale += s->window_func_lut[i] * s->window_func_lut[i];
963         }
964         s->win_scale = 1. / sqrt(s->win_scale);
965
966         /* prepare the initial picref buffer (black frame) */
967         av_frame_free(&s->outpicref);
968         s->outpicref = outpicref =
969             ff_get_video_buffer(outlink, outlink->w, outlink->h);
970         if (!outpicref)
971             return AVERROR(ENOMEM);
972         outpicref->sample_aspect_ratio = (AVRational){1,1};
973         for (i = 0; i < outlink->h; i++) {
974             memset(outpicref->data[0] + i * outpicref->linesize[0],   0, outlink->w);
975             memset(outpicref->data[1] + i * outpicref->linesize[1], 128, outlink->w);
976             memset(outpicref->data[2] + i * outpicref->linesize[2], 128, outlink->w);
977         }
978         outpicref->color_range = AVCOL_RANGE_JPEG;
979
980         if (!s->single_pic && s->legend)
981             draw_legend(ctx, 0);
982     }
983
984     if ((s->orientation == VERTICAL   && s->xpos >= s->w) ||
985         (s->orientation == HORIZONTAL && s->xpos >= s->h))
986         s->xpos = 0;
987
988     s->auto_frame_rate = av_make_q(inlink->sample_rate, s->hop_size);
989     if (s->orientation == VERTICAL && s->sliding == FULLFRAME)
990         s->auto_frame_rate.den *= s->w;
991     if (s->orientation == HORIZONTAL && s->sliding == FULLFRAME)
992         s->auto_frame_rate.den *= s->h;
993     if (!s->single_pic && strcmp(s->rate_str, "auto")) {
994         int ret = av_parse_video_rate(&s->frame_rate, s->rate_str);
995         if (ret < 0)
996             return ret;
997     } else {
998         s->frame_rate = s->auto_frame_rate;
999     }
1000     outlink->frame_rate = s->frame_rate;
1001     outlink->time_base = av_inv_q(outlink->frame_rate);
1002
1003     if (s->orientation == VERTICAL) {
1004         s->combine_buffer =
1005             av_realloc_f(s->combine_buffer, s->h * 3,
1006                          sizeof(*s->combine_buffer));
1007     } else {
1008         s->combine_buffer =
1009             av_realloc_f(s->combine_buffer, s->w * 3,
1010                          sizeof(*s->combine_buffer));
1011     }
1012
1013     av_log(ctx, AV_LOG_VERBOSE, "s:%dx%d FFT window size:%d\n",
1014            s->w, s->h, s->win_size);
1015
1016     av_audio_fifo_free(s->fifo);
1017     s->fifo = av_audio_fifo_alloc(inlink->format, inlink->channels, s->win_size);
1018     if (!s->fifo)
1019         return AVERROR(ENOMEM);
1020     return 0;
1021 }
1022
1023 #define RE(y, ch) s->fft_data[ch][y].re
1024 #define IM(y, ch) s->fft_data[ch][y].im
1025 #define MAGNITUDE(y, ch) hypot(RE(y, ch), IM(y, ch))
1026 #define PHASE(y, ch) atan2(IM(y, ch), RE(y, ch))
1027
1028 static int calc_channel_magnitudes(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
1029 {
1030     ShowSpectrumContext *s = ctx->priv;
1031     const double w = s->win_scale * (s->scale == LOG ? s->win_scale : 1);
1032     int y, h = s->orientation == VERTICAL ? s->h : s->w;
1033     const float f = s->gain * w;
1034     const int ch = jobnr;
1035     float *magnitudes = s->magnitudes[ch];
1036
1037     for (y = 0; y < h; y++)
1038         magnitudes[y] = MAGNITUDE(y, ch) * f;
1039
1040     return 0;
1041 }
1042
1043 static int calc_channel_phases(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
1044 {
1045     ShowSpectrumContext *s = ctx->priv;
1046     const int h = s->orientation == VERTICAL ? s->h : s->w;
1047     const int ch = jobnr;
1048     float *phases = s->phases[ch];
1049     int y;
1050
1051     for (y = 0; y < h; y++)
1052         phases[y] = (PHASE(y, ch) / M_PI + 1) / 2;
1053
1054     return 0;
1055 }
1056
1057 static void acalc_magnitudes(ShowSpectrumContext *s)
1058 {
1059     const double w = s->win_scale * (s->scale == LOG ? s->win_scale : 1);
1060     int ch, y, h = s->orientation == VERTICAL ? s->h : s->w;
1061     const float f = s->gain * w;
1062
1063     for (ch = 0; ch < s->nb_display_channels; ch++) {
1064         float *magnitudes = s->magnitudes[ch];
1065
1066         for (y = 0; y < h; y++)
1067             magnitudes[y] += MAGNITUDE(y, ch) * f;
1068     }
1069 }
1070
1071 static void scale_magnitudes(ShowSpectrumContext *s, float scale)
1072 {
1073     int ch, y, h = s->orientation == VERTICAL ? s->h : s->w;
1074
1075     for (ch = 0; ch < s->nb_display_channels; ch++) {
1076         float *magnitudes = s->magnitudes[ch];
1077
1078         for (y = 0; y < h; y++)
1079             magnitudes[y] *= scale;
1080     }
1081 }
1082
1083 static void clear_combine_buffer(ShowSpectrumContext *s, int size)
1084 {
1085     int y;
1086
1087     for (y = 0; y < size; y++) {
1088         s->combine_buffer[3 * y    ] = 0;
1089         s->combine_buffer[3 * y + 1] = 127.5;
1090         s->combine_buffer[3 * y + 2] = 127.5;
1091     }
1092 }
1093
1094 static int plot_channel(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
1095 {
1096     ShowSpectrumContext *s = ctx->priv;
1097     const int h = s->orientation == VERTICAL ? s->channel_height : s->channel_width;
1098     const int ch = jobnr;
1099     float *magnitudes = s->magnitudes[ch];
1100     float *phases = s->phases[ch];
1101     float yf, uf, vf;
1102     int y;
1103
1104     /* decide color range */
1105     color_range(s, ch, &yf, &uf, &vf);
1106
1107     /* draw the channel */
1108     for (y = 0; y < h; y++) {
1109         int row = (s->mode == COMBINED) ? y : ch * h + y;
1110         float *out = &s->color_buffer[ch][3 * row];
1111         float a;
1112
1113         switch (s->data) {
1114         case D_MAGNITUDE:
1115             /* get magnitude */
1116             a = magnitudes[y];
1117             break;
1118         case D_PHASE:
1119             /* get phase */
1120             a = phases[y];
1121             break;
1122         default:
1123             av_assert0(0);
1124         }
1125
1126         /* apply scale */
1127         switch (s->scale) {
1128         case LINEAR:
1129             a = av_clipf(a, 0, 1);
1130             break;
1131         case SQRT:
1132             a = av_clipf(sqrt(a), 0, 1);
1133             break;
1134         case CBRT:
1135             a = av_clipf(cbrt(a), 0, 1);
1136             break;
1137         case FOURTHRT:
1138             a = av_clipf(sqrt(sqrt(a)), 0, 1);
1139             break;
1140         case FIFTHRT:
1141             a = av_clipf(pow(a, 0.20), 0, 1);
1142             break;
1143         case LOG:
1144             a = 1 + log10(av_clipd(a, 1e-6, 1)) / 6; // zero = -120dBFS
1145             break;
1146         default:
1147             av_assert0(0);
1148         }
1149
1150         pick_color(s, yf, uf, vf, a, out);
1151     }
1152
1153     return 0;
1154 }
1155
1156 static int plot_spectrum_column(AVFilterLink *inlink, AVFrame *insamples)
1157 {
1158     AVFilterContext *ctx = inlink->dst;
1159     AVFilterLink *outlink = ctx->outputs[0];
1160     ShowSpectrumContext *s = ctx->priv;
1161     AVFrame *outpicref = s->outpicref;
1162     int ret, plane, x, y, z = s->orientation == VERTICAL ? s->h : s->w;
1163
1164     /* fill a new spectrum column */
1165     /* initialize buffer for combining to black */
1166     clear_combine_buffer(s, z);
1167
1168     ctx->internal->execute(ctx, plot_channel, NULL, NULL, s->nb_display_channels);
1169
1170     for (y = 0; y < z * 3; y++) {
1171         for (x = 0; x < s->nb_display_channels; x++) {
1172             s->combine_buffer[y] += s->color_buffer[x][y];
1173         }
1174     }
1175
1176     av_frame_make_writable(s->outpicref);
1177     /* copy to output */
1178     if (s->orientation == VERTICAL) {
1179         if (s->sliding == SCROLL) {
1180             for (plane = 0; plane < 3; plane++) {
1181                 for (y = 0; y < s->h; y++) {
1182                     uint8_t *p = outpicref->data[plane] + s->start_x +
1183                                  (y + s->start_y) * outpicref->linesize[plane];
1184                     memmove(p, p + 1, s->w - 1);
1185                 }
1186             }
1187             s->xpos = s->w - 1;
1188         } else if (s->sliding == RSCROLL) {
1189             for (plane = 0; plane < 3; plane++) {
1190                 for (y = 0; y < s->h; y++) {
1191                     uint8_t *p = outpicref->data[plane] + s->start_x +
1192                                  (y + s->start_y) * outpicref->linesize[plane];
1193                     memmove(p + 1, p, s->w - 1);
1194                 }
1195             }
1196             s->xpos = 0;
1197         }
1198         for (plane = 0; plane < 3; plane++) {
1199             uint8_t *p = outpicref->data[plane] + s->start_x +
1200                          (outlink->h - 1 - s->start_y) * outpicref->linesize[plane] +
1201                          s->xpos;
1202             for (y = 0; y < s->h; y++) {
1203                 *p = lrintf(av_clipf(s->combine_buffer[3 * y + plane], 0, 255));
1204                 p -= outpicref->linesize[plane];
1205             }
1206         }
1207     } else {
1208         if (s->sliding == SCROLL) {
1209             for (plane = 0; plane < 3; plane++) {
1210                 for (y = 1; y < s->h; y++) {
1211                     memmove(outpicref->data[plane] + (y-1 + s->start_y) * outpicref->linesize[plane] + s->start_x,
1212                             outpicref->data[plane] + (y   + s->start_y) * outpicref->linesize[plane] + s->start_x,
1213                             s->w);
1214                 }
1215             }
1216             s->xpos = s->h - 1;
1217         } else if (s->sliding == RSCROLL) {
1218             for (plane = 0; plane < 3; plane++) {
1219                 for (y = s->h - 1; y >= 1; y--) {
1220                     memmove(outpicref->data[plane] + (y   + s->start_y) * outpicref->linesize[plane] + s->start_x,
1221                             outpicref->data[plane] + (y-1 + s->start_y) * outpicref->linesize[plane] + s->start_x,
1222                             s->w);
1223                 }
1224             }
1225             s->xpos = 0;
1226         }
1227         for (plane = 0; plane < 3; plane++) {
1228             uint8_t *p = outpicref->data[plane] + s->start_x +
1229                          (s->xpos + s->start_y) * outpicref->linesize[plane];
1230             for (x = 0; x < s->w; x++) {
1231                 *p = lrintf(av_clipf(s->combine_buffer[3 * x + plane], 0, 255));
1232                 p++;
1233             }
1234         }
1235     }
1236
1237     if (s->sliding != FULLFRAME || s->xpos == 0)
1238         outpicref->pts = av_rescale_q(insamples->pts, inlink->time_base, outlink->time_base);
1239
1240     s->xpos++;
1241     if (s->orientation == VERTICAL && s->xpos >= s->w)
1242         s->xpos = 0;
1243     if (s->orientation == HORIZONTAL && s->xpos >= s->h)
1244         s->xpos = 0;
1245     if (!s->single_pic && (s->sliding != FULLFRAME || s->xpos == 0)) {
1246         if (s->old_pts < outpicref->pts) {
1247             if (s->legend) {
1248                 char *units = get_time(ctx, insamples->pts /(float)inlink->sample_rate, x);
1249
1250                 if (s->orientation == VERTICAL) {
1251                     for (y = 0; y < 10; y++) {
1252                         memset(s->outpicref->data[0] + outlink->w / 2 - 4 * s->old_len +
1253                                (outlink->h - s->start_y / 2 - 20 + y) * s->outpicref->linesize[0], 0, 10 * s->old_len);
1254                     }
1255                     drawtext(s->outpicref,
1256                              outlink->w / 2 - 4 * strlen(units),
1257                              outlink->h - s->start_y / 2 - 20,
1258                              units, 0);
1259                 } else  {
1260                     for (y = 0; y < 10 * s->old_len; y++) {
1261                         memset(s->outpicref->data[0] + s->start_x / 7 + 20 +
1262                                (outlink->h / 2 - 4 * s->old_len + y) * s->outpicref->linesize[0], 0, 10);
1263                     }
1264                     drawtext(s->outpicref,
1265                              s->start_x / 7 + 20,
1266                              outlink->h / 2 - 4 * strlen(units),
1267                              units, 1);
1268                 }
1269                 s->old_len = strlen(units);
1270                 av_free(units);
1271             }
1272             s->old_pts = outpicref->pts;
1273             ret = ff_filter_frame(outlink, av_frame_clone(s->outpicref));
1274             if (ret < 0)
1275                 return ret;
1276             return 0;
1277         }
1278     }
1279
1280     return 1;
1281 }
1282
1283 #if CONFIG_SHOWSPECTRUM_FILTER
1284
1285 static int activate(AVFilterContext *ctx)
1286 {
1287     AVFilterLink *inlink = ctx->inputs[0];
1288     AVFilterLink *outlink = ctx->outputs[0];
1289     ShowSpectrumContext *s = ctx->priv;
1290     int ret;
1291
1292     FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink);
1293
1294     if (av_audio_fifo_size(s->fifo) < s->win_size) {
1295         AVFrame *frame = NULL;
1296
1297         ret = ff_inlink_consume_frame(inlink, &frame);
1298         if (ret < 0)
1299             return ret;
1300         if (ret > 0) {
1301             s->pts = frame->pts;
1302             s->consumed = 0;
1303
1304             av_audio_fifo_write(s->fifo, (void **)frame->extended_data, frame->nb_samples);
1305             av_frame_free(&frame);
1306         }
1307     }
1308
1309     if (s->outpicref && av_audio_fifo_size(s->fifo) >= s->win_size) {
1310         AVFrame *fin = ff_get_audio_buffer(inlink, s->win_size);
1311         if (!fin)
1312             return AVERROR(ENOMEM);
1313
1314         fin->pts = s->pts + s->consumed;
1315         s->consumed += s->hop_size;
1316         ret = av_audio_fifo_peek(s->fifo, (void **)fin->extended_data,
1317                                  FFMIN(s->win_size, av_audio_fifo_size(s->fifo)));
1318         if (ret < 0) {
1319             av_frame_free(&fin);
1320             return ret;
1321         }
1322
1323         av_assert0(fin->nb_samples == s->win_size);
1324
1325         ctx->internal->execute(ctx, run_channel_fft, fin, NULL, s->nb_display_channels);
1326
1327         if (s->data == D_MAGNITUDE)
1328             ctx->internal->execute(ctx, calc_channel_magnitudes, NULL, NULL, s->nb_display_channels);
1329
1330         if (s->data == D_PHASE)
1331             ctx->internal->execute(ctx, calc_channel_phases, NULL, NULL, s->nb_display_channels);
1332
1333         ret = plot_spectrum_column(inlink, fin);
1334
1335         av_frame_free(&fin);
1336         av_audio_fifo_drain(s->fifo, s->hop_size);
1337         if (ret <= 0)
1338             return ret;
1339     }
1340
1341     if (ff_outlink_get_status(inlink) == AVERROR_EOF &&
1342         s->sliding == FULLFRAME &&
1343         s->xpos > 0 && s->outpicref) {
1344         int64_t pts;
1345
1346         if (s->orientation == VERTICAL) {
1347             for (int i = 0; i < outlink->h; i++) {
1348                 memset(s->outpicref->data[0] + i * s->outpicref->linesize[0] + s->xpos,   0, outlink->w - s->xpos);
1349                 memset(s->outpicref->data[1] + i * s->outpicref->linesize[1] + s->xpos, 128, outlink->w - s->xpos);
1350                 memset(s->outpicref->data[2] + i * s->outpicref->linesize[2] + s->xpos, 128, outlink->w - s->xpos);
1351             }
1352         } else {
1353             for (int i = s->xpos; i < outlink->h; i++) {
1354                 memset(s->outpicref->data[0] + i * s->outpicref->linesize[0],   0, outlink->w);
1355                 memset(s->outpicref->data[1] + i * s->outpicref->linesize[1], 128, outlink->w);
1356                 memset(s->outpicref->data[2] + i * s->outpicref->linesize[2], 128, outlink->w);
1357             }
1358         }
1359         s->outpicref->pts += s->consumed;
1360         pts = s->outpicref->pts;
1361         ret = ff_filter_frame(outlink, s->outpicref);
1362         s->outpicref = NULL;
1363         ff_outlink_set_status(outlink, AVERROR_EOF, pts);
1364         return 0;
1365     }
1366
1367     FF_FILTER_FORWARD_STATUS(inlink, outlink);
1368     if (ff_outlink_frame_wanted(outlink) && av_audio_fifo_size(s->fifo) < s->win_size) {
1369         ff_inlink_request_frame(inlink);
1370         return 0;
1371     }
1372
1373     if (av_audio_fifo_size(s->fifo) >= s->win_size) {
1374         ff_filter_set_ready(ctx, 10);
1375         return 0;
1376     }
1377     return FFERROR_NOT_READY;
1378 }
1379
1380 static const AVFilterPad showspectrum_inputs[] = {
1381     {
1382         .name         = "default",
1383         .type         = AVMEDIA_TYPE_AUDIO,
1384     },
1385     { NULL }
1386 };
1387
1388 static const AVFilterPad showspectrum_outputs[] = {
1389     {
1390         .name          = "default",
1391         .type          = AVMEDIA_TYPE_VIDEO,
1392         .config_props  = config_output,
1393     },
1394     { NULL }
1395 };
1396
1397 AVFilter ff_avf_showspectrum = {
1398     .name          = "showspectrum",
1399     .description   = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output."),
1400     .uninit        = uninit,
1401     .query_formats = query_formats,
1402     .priv_size     = sizeof(ShowSpectrumContext),
1403     .inputs        = showspectrum_inputs,
1404     .outputs       = showspectrum_outputs,
1405     .activate      = activate,
1406     .priv_class    = &showspectrum_class,
1407     .flags         = AVFILTER_FLAG_SLICE_THREADS,
1408 };
1409 #endif // CONFIG_SHOWSPECTRUM_FILTER
1410
1411 #if CONFIG_SHOWSPECTRUMPIC_FILTER
1412
1413 static const AVOption showspectrumpic_options[] = {
1414     { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "4096x2048"}, 0, 0, FLAGS },
1415     { "s",    "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "4096x2048"}, 0, 0, FLAGS },
1416     { "mode", "set channel display mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=COMBINED}, 0, NB_MODES-1, FLAGS, "mode" },
1417         { "combined", "combined mode", 0, AV_OPT_TYPE_CONST, {.i64=COMBINED}, 0, 0, FLAGS, "mode" },
1418         { "separate", "separate mode", 0, AV_OPT_TYPE_CONST, {.i64=SEPARATE}, 0, 0, FLAGS, "mode" },
1419     { "color", "set channel coloring", OFFSET(color_mode), AV_OPT_TYPE_INT, {.i64=INTENSITY}, 0, NB_CLMODES-1, FLAGS, "color" },
1420         { "channel",   "separate color for each channel", 0, AV_OPT_TYPE_CONST, {.i64=CHANNEL},   0, 0, FLAGS, "color" },
1421         { "intensity", "intensity based coloring",        0, AV_OPT_TYPE_CONST, {.i64=INTENSITY}, 0, 0, FLAGS, "color" },
1422         { "rainbow",   "rainbow based coloring",          0, AV_OPT_TYPE_CONST, {.i64=RAINBOW},   0, 0, FLAGS, "color" },
1423         { "moreland",  "moreland based coloring",         0, AV_OPT_TYPE_CONST, {.i64=MORELAND},  0, 0, FLAGS, "color" },
1424         { "nebulae",   "nebulae based coloring",          0, AV_OPT_TYPE_CONST, {.i64=NEBULAE},   0, 0, FLAGS, "color" },
1425         { "fire",      "fire based coloring",             0, AV_OPT_TYPE_CONST, {.i64=FIRE},      0, 0, FLAGS, "color" },
1426         { "fiery",     "fiery based coloring",            0, AV_OPT_TYPE_CONST, {.i64=FIERY},     0, 0, FLAGS, "color" },
1427         { "fruit",     "fruit based coloring",            0, AV_OPT_TYPE_CONST, {.i64=FRUIT},     0, 0, FLAGS, "color" },
1428         { "cool",      "cool based coloring",             0, AV_OPT_TYPE_CONST, {.i64=COOL},      0, 0, FLAGS, "color" },
1429         { "magma",     "magma based coloring",            0, AV_OPT_TYPE_CONST, {.i64=MAGMA},     0, 0, FLAGS, "color" },
1430         { "green",     "green based coloring",            0, AV_OPT_TYPE_CONST, {.i64=GREEN},     0, 0, FLAGS, "color" },
1431         { "viridis",   "viridis based coloring",          0, AV_OPT_TYPE_CONST, {.i64=VIRIDIS},   0, 0, FLAGS, "color" },
1432         { "plasma",    "plasma based coloring",           0, AV_OPT_TYPE_CONST, {.i64=PLASMA},    0, 0, FLAGS, "color" },
1433         { "cividis",   "cividis based coloring",          0, AV_OPT_TYPE_CONST, {.i64=CIVIDIS},   0, 0, FLAGS, "color" },
1434     { "scale", "set display scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64=LOG}, 0, NB_SCALES-1, FLAGS, "scale" },
1435         { "lin",  "linear",      0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, FLAGS, "scale" },
1436         { "sqrt", "square root", 0, AV_OPT_TYPE_CONST, {.i64=SQRT},   0, 0, FLAGS, "scale" },
1437         { "cbrt", "cubic root",  0, AV_OPT_TYPE_CONST, {.i64=CBRT},   0, 0, FLAGS, "scale" },
1438         { "log",  "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG},    0, 0, FLAGS, "scale" },
1439         { "4thrt","4th root",    0, AV_OPT_TYPE_CONST, {.i64=FOURTHRT}, 0, 0, FLAGS, "scale" },
1440         { "5thrt","5th root",    0, AV_OPT_TYPE_CONST, {.i64=FIFTHRT},  0, 0, FLAGS, "scale" },
1441     { "saturation", "color saturation multiplier", OFFSET(saturation), AV_OPT_TYPE_FLOAT, {.dbl = 1}, -10, 10, FLAGS },
1442     { "win_func", "set window function", OFFSET(win_func), AV_OPT_TYPE_INT, {.i64 = WFUNC_HANNING}, 0, NB_WFUNC-1, FLAGS, "win_func" },
1443         { "rect",     "Rectangular",      0, AV_OPT_TYPE_CONST, {.i64=WFUNC_RECT},     0, 0, FLAGS, "win_func" },
1444         { "bartlett", "Bartlett",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BARTLETT}, 0, 0, FLAGS, "win_func" },
1445         { "hann",     "Hann",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, FLAGS, "win_func" },
1446         { "hanning",  "Hanning",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, FLAGS, "win_func" },
1447         { "hamming",  "Hamming",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HAMMING},  0, 0, FLAGS, "win_func" },
1448         { "blackman", "Blackman",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BLACKMAN}, 0, 0, FLAGS, "win_func" },
1449         { "welch",    "Welch",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_WELCH},    0, 0, FLAGS, "win_func" },
1450         { "flattop",  "Flat-top",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_FLATTOP},  0, 0, FLAGS, "win_func" },
1451         { "bharris",  "Blackman-Harris",  0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BHARRIS},  0, 0, FLAGS, "win_func" },
1452         { "bnuttall", "Blackman-Nuttall", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BNUTTALL}, 0, 0, FLAGS, "win_func" },
1453         { "bhann",    "Bartlett-Hann",    0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BHANN},    0, 0, FLAGS, "win_func" },
1454         { "sine",     "Sine",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_SINE},     0, 0, FLAGS, "win_func" },
1455         { "nuttall",  "Nuttall",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_NUTTALL},  0, 0, FLAGS, "win_func" },
1456         { "lanczos",  "Lanczos",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_LANCZOS},  0, 0, FLAGS, "win_func" },
1457         { "gauss",    "Gauss",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_GAUSS},    0, 0, FLAGS, "win_func" },
1458         { "tukey",    "Tukey",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_TUKEY},    0, 0, FLAGS, "win_func" },
1459         { "dolph",    "Dolph-Chebyshev",  0, AV_OPT_TYPE_CONST, {.i64=WFUNC_DOLPH},    0, 0, FLAGS, "win_func" },
1460         { "cauchy",   "Cauchy",           0, AV_OPT_TYPE_CONST, {.i64=WFUNC_CAUCHY},   0, 0, FLAGS, "win_func" },
1461         { "parzen",   "Parzen",           0, AV_OPT_TYPE_CONST, {.i64=WFUNC_PARZEN},   0, 0, FLAGS, "win_func" },
1462         { "poisson",  "Poisson",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_POISSON},  0, 0, FLAGS, "win_func" },
1463         { "bohman",   "Bohman",           0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BOHMAN},   0, 0, FLAGS, "win_func" },
1464     { "orientation", "set orientation", OFFSET(orientation), AV_OPT_TYPE_INT, {.i64=VERTICAL}, 0, NB_ORIENTATIONS-1, FLAGS, "orientation" },
1465         { "vertical",   NULL, 0, AV_OPT_TYPE_CONST, {.i64=VERTICAL},   0, 0, FLAGS, "orientation" },
1466         { "horizontal", NULL, 0, AV_OPT_TYPE_CONST, {.i64=HORIZONTAL}, 0, 0, FLAGS, "orientation" },
1467     { "gain", "set scale gain", OFFSET(gain), AV_OPT_TYPE_FLOAT, {.dbl = 1}, 0, 128, FLAGS },
1468     { "legend", "draw legend", OFFSET(legend), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, FLAGS },
1469     { "rotation", "color rotation", OFFSET(rotation), AV_OPT_TYPE_FLOAT, {.dbl = 0}, -1, 1, FLAGS },
1470     { "start", "start frequency", OFFSET(start), AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT32_MAX, FLAGS },
1471     { "stop",  "stop frequency",  OFFSET(stop),  AV_OPT_TYPE_INT, {.i64 = 0}, 0, INT32_MAX, FLAGS },
1472     { NULL }
1473 };
1474
1475 AVFILTER_DEFINE_CLASS(showspectrumpic);
1476
1477 static int showspectrumpic_request_frame(AVFilterLink *outlink)
1478 {
1479     AVFilterContext *ctx = outlink->src;
1480     ShowSpectrumContext *s = ctx->priv;
1481     AVFilterLink *inlink = ctx->inputs[0];
1482     int ret, samples;
1483
1484     ret = ff_request_frame(inlink);
1485     samples = av_audio_fifo_size(s->fifo);
1486     if (ret == AVERROR_EOF && s->outpicref && samples > 0) {
1487         int consumed = 0;
1488         int x = 0, sz = s->orientation == VERTICAL ? s->w : s->h;
1489         int ch, spf, spb;
1490         AVFrame *fin;
1491
1492         spf = s->win_size * (samples / ((s->win_size * sz) * ceil(samples / (float)(s->win_size * sz))));
1493         spf = FFMAX(1, spf);
1494
1495         spb = (samples / (spf * sz)) * spf;
1496
1497         fin = ff_get_audio_buffer(inlink, s->win_size);
1498         if (!fin)
1499             return AVERROR(ENOMEM);
1500
1501         while (x < sz) {
1502             ret = av_audio_fifo_peek(s->fifo, (void **)fin->extended_data, s->win_size);
1503             if (ret < 0) {
1504                 av_frame_free(&fin);
1505                 return ret;
1506             }
1507
1508             av_audio_fifo_drain(s->fifo, spf);
1509
1510             if (ret < s->win_size) {
1511                 for (ch = 0; ch < s->nb_display_channels; ch++) {
1512                     memset(fin->extended_data[ch] + ret * sizeof(float), 0,
1513                            (s->win_size - ret) * sizeof(float));
1514                 }
1515             }
1516
1517             ctx->internal->execute(ctx, run_channel_fft, fin, NULL, s->nb_display_channels);
1518             acalc_magnitudes(s);
1519
1520             consumed += spf;
1521             if (consumed >= spb) {
1522                 int h = s->orientation == VERTICAL ? s->h : s->w;
1523
1524                 scale_magnitudes(s, 1. / (consumed / spf));
1525                 plot_spectrum_column(inlink, fin);
1526                 consumed = 0;
1527                 x++;
1528                 for (ch = 0; ch < s->nb_display_channels; ch++)
1529                     memset(s->magnitudes[ch], 0, h * sizeof(float));
1530             }
1531         }
1532
1533         av_frame_free(&fin);
1534         s->outpicref->pts = 0;
1535
1536         if (s->legend)
1537             draw_legend(ctx, samples);
1538
1539         ret = ff_filter_frame(outlink, s->outpicref);
1540         s->outpicref = NULL;
1541     }
1542
1543     return ret;
1544 }
1545
1546 static int showspectrumpic_filter_frame(AVFilterLink *inlink, AVFrame *insamples)
1547 {
1548     AVFilterContext *ctx = inlink->dst;
1549     ShowSpectrumContext *s = ctx->priv;
1550     int ret;
1551
1552     ret = av_audio_fifo_write(s->fifo, (void **)insamples->extended_data, insamples->nb_samples);
1553     av_frame_free(&insamples);
1554     return ret;
1555 }
1556
1557 static const AVFilterPad showspectrumpic_inputs[] = {
1558     {
1559         .name         = "default",
1560         .type         = AVMEDIA_TYPE_AUDIO,
1561         .filter_frame = showspectrumpic_filter_frame,
1562     },
1563     { NULL }
1564 };
1565
1566 static const AVFilterPad showspectrumpic_outputs[] = {
1567     {
1568         .name          = "default",
1569         .type          = AVMEDIA_TYPE_VIDEO,
1570         .config_props  = config_output,
1571         .request_frame = showspectrumpic_request_frame,
1572     },
1573     { NULL }
1574 };
1575
1576 AVFilter ff_avf_showspectrumpic = {
1577     .name          = "showspectrumpic",
1578     .description   = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output single picture."),
1579     .uninit        = uninit,
1580     .query_formats = query_formats,
1581     .priv_size     = sizeof(ShowSpectrumContext),
1582     .inputs        = showspectrumpic_inputs,
1583     .outputs       = showspectrumpic_outputs,
1584     .priv_class    = &showspectrumpic_class,
1585     .flags         = AVFILTER_FLAG_SLICE_THREADS,
1586 };
1587
1588 #endif // CONFIG_SHOWSPECTRUMPIC_FILTER