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