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