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