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