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