]> git.sesse.net Git - ffmpeg/blob - libavfilter/avf_showspectrum.c
Merge commit '5049f6b772891cdf4030a9d572362efc8f7ae97f'
[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/channel_layout.h"
35 #include "libavutil/opt.h"
36 #include "audio.h"
37 #include "video.h"
38 #include "avfilter.h"
39 #include "internal.h"
40 #include "window_func.h"
41
42 enum DisplayMode  { COMBINED, SEPARATE, NB_MODES };
43 enum DisplayScale { LINEAR, SQRT, CBRT, LOG, NB_SCALES };
44 enum ColorMode    { CHANNEL, INTENSITY, RAINBOW, MORELAND, NEBULAE, FIRE, NB_CLMODES };
45 enum SlideMode    { REPLACE, SCROLL, FULLFRAME, RSCROLL, NB_SLIDES };
46 enum Orientation  { VERTICAL, HORIZONTAL, NB_ORIENTATIONS };
47
48 typedef struct {
49     const AVClass *class;
50     int w, h;
51     AVFrame *outpicref;
52     int nb_display_channels;
53     int orientation;
54     int channel_width;
55     int channel_height;
56     int sliding;                ///< 1 if sliding mode, 0 otherwise
57     int mode;                   ///< channel display mode
58     int color_mode;             ///< display color scheme
59     int scale;
60     float saturation;           ///< color saturation multiplier
61     int xpos;                   ///< x position (current column)
62     RDFTContext *rdft;          ///< Real Discrete Fourier Transform context
63     int rdft_bits;              ///< number of bits (RDFT window size = 1<<rdft_bits)
64     FFTSample **rdft_data;      ///< bins holder for each (displayed) channels
65     float *window_func_lut;     ///< Window function LUT
66     int win_func;
67     double win_scale;
68     float overlap;
69     int skip_samples;
70     float *combine_buffer;      ///< color combining buffer (3 * h items)
71     AVAudioFifo *fifo;
72     int64_t pts;
73 } ShowSpectrumContext;
74
75 #define OFFSET(x) offsetof(ShowSpectrumContext, x)
76 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
77
78 static const AVOption showspectrum_options[] = {
79     { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
80     { "s",    "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
81     { "slide", "set sliding mode", OFFSET(sliding), AV_OPT_TYPE_INT, {.i64 = 0}, 0, NB_SLIDES-1, FLAGS, "slide" },
82         { "replace", "replace old columns with new", 0, AV_OPT_TYPE_CONST, {.i64=REPLACE}, 0, 0, FLAGS, "slide" },
83         { "scroll", "scroll from right to left", 0, AV_OPT_TYPE_CONST, {.i64=SCROLL}, 0, 0, FLAGS, "slide" },
84         { "rscroll", "scroll from left to right", 0, AV_OPT_TYPE_CONST, {.i64=RSCROLL}, 0, 0, FLAGS, "slide" },
85         { "fullframe", "return full frames", 0, AV_OPT_TYPE_CONST, {.i64=FULLFRAME}, 0, 0, FLAGS, "slide" },
86     { "mode", "set channel display mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=COMBINED}, COMBINED, NB_MODES-1, FLAGS, "mode" },
87         { "combined", "combined mode", 0, AV_OPT_TYPE_CONST, {.i64=COMBINED}, 0, 0, FLAGS, "mode" },
88         { "separate", "separate mode", 0, AV_OPT_TYPE_CONST, {.i64=SEPARATE}, 0, 0, FLAGS, "mode" },
89     { "color", "set channel coloring", OFFSET(color_mode), AV_OPT_TYPE_INT, {.i64=CHANNEL}, CHANNEL, NB_CLMODES-1, FLAGS, "color" },
90         { "channel",   "separate color for each channel", 0, AV_OPT_TYPE_CONST, {.i64=CHANNEL},   0, 0, FLAGS, "color" },
91         { "intensity", "intensity based coloring",        0, AV_OPT_TYPE_CONST, {.i64=INTENSITY}, 0, 0, FLAGS, "color" },
92         { "rainbow",   "rainbow based coloring",          0, AV_OPT_TYPE_CONST, {.i64=RAINBOW},   0, 0, FLAGS, "color" },
93         { "moreland",  "moreland based coloring",         0, AV_OPT_TYPE_CONST, {.i64=MORELAND},  0, 0, FLAGS, "color" },
94         { "nebulae",   "nebulae based coloring",          0, AV_OPT_TYPE_CONST, {.i64=NEBULAE},   0, 0, FLAGS, "color" },
95         { "fire",      "fire based coloring",             0, AV_OPT_TYPE_CONST, {.i64=FIRE},      0, 0, FLAGS, "color" },
96     { "scale", "set display scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64=SQRT}, LINEAR, NB_SCALES-1, FLAGS, "scale" },
97         { "sqrt", "square root", 0, AV_OPT_TYPE_CONST, {.i64=SQRT},   0, 0, FLAGS, "scale" },
98         { "cbrt", "cubic root",  0, AV_OPT_TYPE_CONST, {.i64=CBRT},   0, 0, FLAGS, "scale" },
99         { "log",  "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG},    0, 0, FLAGS, "scale" },
100         { "lin",  "linear",      0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, FLAGS, "scale" },
101     { "saturation", "color saturation multiplier", OFFSET(saturation), AV_OPT_TYPE_FLOAT, {.dbl = 1}, -10, 10, FLAGS },
102     { "win_func", "set window function", OFFSET(win_func), AV_OPT_TYPE_INT, {.i64 = WFUNC_HANNING}, 0, NB_WFUNC-1, FLAGS, "win_func" },
103         { "rect",     "Rectangular",      0, AV_OPT_TYPE_CONST, {.i64=WFUNC_RECT},     0, 0, FLAGS, "win_func" },
104         { "bartlett", "Bartlett",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BARTLETT}, 0, 0, FLAGS, "win_func" },
105         { "hann",     "Hann",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, FLAGS, "win_func" },
106         { "hanning",  "Hanning",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, FLAGS, "win_func" },
107         { "hamming",  "Hamming",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HAMMING},  0, 0, FLAGS, "win_func" },
108         { "blackman", "Blackman",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BLACKMAN}, 0, 0, FLAGS, "win_func" },
109         { "welch",    "Welch",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_WELCH},    0, 0, FLAGS, "win_func" },
110         { "flattop",  "Flat-top",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_FLATTOP},  0, 0, FLAGS, "win_func" },
111         { "bharris",  "Blackman-Harris",  0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BHARRIS},  0, 0, FLAGS, "win_func" },
112         { "bnuttall", "Blackman-Nuttall", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BNUTTALL}, 0, 0, FLAGS, "win_func" },
113         { "bhann",    "Bartlett-Hann",    0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BHANN},    0, 0, FLAGS, "win_func" },
114         { "sine",     "Sine",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_SINE},     0, 0, FLAGS, "win_func" },
115         { "nuttall",  "Nuttall",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_NUTTALL},  0, 0, FLAGS, "win_func" },
116         { "lanczos",  "Lanczos",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_LANCZOS},  0, 0, FLAGS, "win_func" },
117         { "gauss",    "Gauss",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_GAUSS},    0, 0, FLAGS, "win_func" },
118     { "orientation", "set orientation", OFFSET(orientation), AV_OPT_TYPE_INT, {.i64=VERTICAL}, 0, NB_ORIENTATIONS-1, FLAGS, "orientation" },
119         { "vertical",   NULL, 0, AV_OPT_TYPE_CONST, {.i64=VERTICAL},   0, 0, FLAGS, "orientation" },
120         { "horizontal", NULL, 0, AV_OPT_TYPE_CONST, {.i64=HORIZONTAL}, 0, 0, FLAGS, "orientation" },
121     { "overlap", "set window overlap", OFFSET(overlap), AV_OPT_TYPE_FLOAT, {.dbl = 0}, 0, 1, FLAGS },
122     { NULL }
123 };
124
125 AVFILTER_DEFINE_CLASS(showspectrum);
126
127 static const struct ColorTable {
128     float a, y, u, v;
129 } color_table[][8] = {
130     [INTENSITY] = {
131     {    0,                  0,                  0,                   0 },
132     { 0.13, .03587126228984074,  .1573300977624594, -.02548747583751842 },
133     { 0.30, .18572281794568020,  .1772436246393981,  .17475554840414750 },
134     { 0.60, .28184980583656130, -.1593064119945782,  .47132074554608920 },
135     { 0.73, .65830621175547810, -.3716070802232764,  .24352759331252930 },
136     { 0.78, .76318535758242900, -.4307467689263783,  .16866496622310430 },
137     { 0.91, .95336363636363640, -.2045454545454546,  .03313636363636363 },
138     {    1,                  1,                  0,                   0 }},
139     [RAINBOW] = {
140     {    0,                  0,                  0,                   0 },
141     { 0.13,            44/256.,     (189-128)/256.,      (138-128)/256. },
142     { 0.25,            29/256.,     (186-128)/256.,      (119-128)/256. },
143     { 0.38,           119/256.,     (194-128)/256.,       (53-128)/256. },
144     { 0.60,           111/256.,      (73-128)/256.,       (59-128)/256. },
145     { 0.73,           205/256.,      (19-128)/256.,      (149-128)/256. },
146     { 0.86,           135/256.,      (83-128)/256.,      (200-128)/256. },
147     {    1,            73/256.,      (95-128)/256.,      (225-128)/256. }},
148     [MORELAND] = {
149     {    0,            44/256.,     (181-128)/256.,      (112-128)/256. },
150     { 0.13,           126/256.,     (177-128)/256.,      (106-128)/256. },
151     { 0.25,           164/256.,     (163-128)/256.,      (109-128)/256. },
152     { 0.38,           200/256.,     (140-128)/256.,      (120-128)/256. },
153     { 0.60,           201/256.,     (117-128)/256.,      (141-128)/256. },
154     { 0.73,           177/256.,     (103-128)/256.,      (165-128)/256. },
155     { 0.86,           136/256.,     (100-128)/256.,      (183-128)/256. },
156     {    1,            68/256.,     (117-128)/256.,      (203-128)/256. }},
157     [NEBULAE] = {
158     {    0,            10/256.,     (134-128)/256.,      (132-128)/256. },
159     { 0.23,            21/256.,     (137-128)/256.,      (130-128)/256. },
160     { 0.45,            35/256.,     (134-128)/256.,      (134-128)/256. },
161     { 0.57,            51/256.,     (130-128)/256.,      (139-128)/256. },
162     { 0.67,           104/256.,     (116-128)/256.,      (162-128)/256. },
163     { 0.77,           120/256.,     (105-128)/256.,      (188-128)/256. },
164     { 0.87,           140/256.,     (105-128)/256.,      (188-128)/256. },
165     {    1,                  1,                  0,                   0 }},
166     [FIRE] = {
167     {    0,                  0,                  0,                   0 },
168     { 0.23,            44/256.,     (132-128)/256.,      (127-128)/256. },
169     { 0.45,            62/256.,     (116-128)/256.,      (140-128)/256. },
170     { 0.57,            75/256.,     (105-128)/256.,      (152-128)/256. },
171     { 0.67,            95/256.,      (91-128)/256.,      (166-128)/256. },
172     { 0.77,           126/256.,      (74-128)/256.,      (172-128)/256. },
173     { 0.87,           164/256.,      (73-128)/256.,      (162-128)/256. },
174     {    1,                  1,                  0,                   0 }},
175 };
176
177 static av_cold void uninit(AVFilterContext *ctx)
178 {
179     ShowSpectrumContext *s = ctx->priv;
180     int i;
181
182     av_freep(&s->combine_buffer);
183     av_rdft_end(s->rdft);
184     for (i = 0; i < s->nb_display_channels; i++)
185         av_freep(&s->rdft_data[i]);
186     av_freep(&s->rdft_data);
187     av_freep(&s->window_func_lut);
188     av_frame_free(&s->outpicref);
189     av_audio_fifo_free(s->fifo);
190 }
191
192 static int query_formats(AVFilterContext *ctx)
193 {
194     AVFilterFormats *formats = NULL;
195     AVFilterChannelLayouts *layouts = NULL;
196     AVFilterLink *inlink = ctx->inputs[0];
197     AVFilterLink *outlink = ctx->outputs[0];
198     static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE };
199     static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_NONE };
200     int ret;
201
202     /* set input audio formats */
203     formats = ff_make_format_list(sample_fmts);
204     if ((ret = ff_formats_ref(formats, &inlink->out_formats)) < 0)
205         return ret;
206
207     layouts = ff_all_channel_layouts();
208     if ((ret = ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts)) < 0)
209         return ret;
210
211     formats = ff_all_samplerates();
212     if ((ret = ff_formats_ref(formats, &inlink->out_samplerates)) < 0)
213         return ret;
214
215     /* set output video format */
216     formats = ff_make_format_list(pix_fmts);
217     if ((ret = ff_formats_ref(formats, &outlink->in_formats)) < 0)
218         return ret;
219
220     return 0;
221 }
222
223 static int config_output(AVFilterLink *outlink)
224 {
225     AVFilterContext *ctx = outlink->src;
226     AVFilterLink *inlink = ctx->inputs[0];
227     ShowSpectrumContext *s = ctx->priv;
228     int i, rdft_bits, win_size, h, w;
229     float overlap;
230
231     outlink->w = s->w;
232     outlink->h = s->h;
233
234     h = (s->mode == COMBINED || s->orientation == HORIZONTAL) ? outlink->h : outlink->h / inlink->channels;
235     w = (s->mode == COMBINED || s->orientation == VERTICAL)   ? outlink->w : outlink->w / inlink->channels;
236     s->channel_height = h;
237     s->channel_width  = w;
238
239     if (s->orientation == VERTICAL) {
240         /* RDFT window size (precision) according to the requested output frame height */
241         for (rdft_bits = 1; 1 << rdft_bits < 2 * h; rdft_bits++);
242     } else {
243         /* RDFT window size (precision) according to the requested output frame width */
244         for (rdft_bits = 1; 1 << rdft_bits < 2 * w; rdft_bits++);
245     }
246     win_size = 1 << rdft_bits;
247
248     /* (re-)configuration if the video output changed (or first init) */
249     if (rdft_bits != s->rdft_bits) {
250         AVFrame *outpicref;
251
252         av_rdft_end(s->rdft);
253         s->rdft = av_rdft_init(rdft_bits, DFT_R2C);
254         if (!s->rdft) {
255             av_log(ctx, AV_LOG_ERROR, "Unable to create RDFT context. "
256                    "The window size might be too high.\n");
257             return AVERROR(EINVAL);
258         }
259         s->rdft_bits = rdft_bits;
260
261         /* RDFT buffers: x2 for each (display) channel buffer.
262          * Note: we use free and malloc instead of a realloc-like function to
263          * make sure the buffer is aligned in memory for the FFT functions. */
264         for (i = 0; i < s->nb_display_channels; i++)
265             av_freep(&s->rdft_data[i]);
266         av_freep(&s->rdft_data);
267         s->nb_display_channels = inlink->channels;
268
269         s->rdft_data = av_calloc(s->nb_display_channels, sizeof(*s->rdft_data));
270         if (!s->rdft_data)
271             return AVERROR(ENOMEM);
272         for (i = 0; i < s->nb_display_channels; i++) {
273             s->rdft_data[i] = av_calloc(win_size, sizeof(**s->rdft_data));
274             if (!s->rdft_data[i])
275                 return AVERROR(ENOMEM);
276         }
277
278         /* pre-calc windowing function */
279         s->window_func_lut =
280             av_realloc_f(s->window_func_lut, win_size,
281                          sizeof(*s->window_func_lut));
282         if (!s->window_func_lut)
283             return AVERROR(ENOMEM);
284         ff_generate_window_func(s->window_func_lut, win_size, s->win_func, &overlap);
285         if (s->overlap == 1)
286             s->overlap = overlap;
287         s->skip_samples = (1. - s->overlap) * win_size;
288         if (s->skip_samples < 1) {
289             av_log(ctx, AV_LOG_ERROR, "overlap %f too big\n", s->overlap);
290             return AVERROR(EINVAL);
291         }
292
293         for (s->win_scale = 0, i = 0; i < win_size; i++) {
294             s->win_scale += s->window_func_lut[i] * s->window_func_lut[i];
295         }
296         s->win_scale = 1. / (sqrt(s->win_scale) * 32768.);
297
298         /* prepare the initial picref buffer (black frame) */
299         av_frame_free(&s->outpicref);
300         s->outpicref = outpicref =
301             ff_get_video_buffer(outlink, outlink->w, outlink->h);
302         if (!outpicref)
303             return AVERROR(ENOMEM);
304         outlink->sample_aspect_ratio = (AVRational){1,1};
305         for (i = 0; i < outlink->h; i++) {
306             memset(outpicref->data[0] + i * outpicref->linesize[0],   0, outlink->w);
307             memset(outpicref->data[1] + i * outpicref->linesize[1], 128, outlink->w);
308             memset(outpicref->data[2] + i * outpicref->linesize[2], 128, outlink->w);
309         }
310     }
311
312     if ((s->orientation == VERTICAL   && s->xpos >= outlink->w) ||
313         (s->orientation == HORIZONTAL && s->xpos >= outlink->h))
314         s->xpos = 0;
315
316     outlink->frame_rate = av_make_q(inlink->sample_rate, win_size * (1.-s->overlap));
317     if (s->orientation == VERTICAL && s->sliding == FULLFRAME)
318         outlink->frame_rate.den *= outlink->w;
319     if (s->orientation == HORIZONTAL && s->sliding == FULLFRAME)
320         outlink->frame_rate.den *= outlink->h;
321
322     if (s->orientation == VERTICAL) {
323         s->combine_buffer =
324             av_realloc_f(s->combine_buffer, outlink->h * 3,
325                          sizeof(*s->combine_buffer));
326     } else {
327         s->combine_buffer =
328             av_realloc_f(s->combine_buffer, outlink->w * 3,
329                          sizeof(*s->combine_buffer));
330     }
331
332     av_log(ctx, AV_LOG_VERBOSE, "s:%dx%d RDFT window size:%d\n",
333            s->w, s->h, win_size);
334
335     av_audio_fifo_free(s->fifo);
336     s->fifo = av_audio_fifo_alloc(inlink->format, inlink->channels, win_size);
337     if (!s->fifo)
338         return AVERROR(ENOMEM);
339     return 0;
340 }
341
342 static int request_frame(AVFilterLink *outlink)
343 {
344     ShowSpectrumContext *s = outlink->src->priv;
345     AVFilterLink *inlink = outlink->src->inputs[0];
346     unsigned i;
347     int ret;
348
349     ret = ff_request_frame(inlink);
350     if (ret == AVERROR_EOF && s->sliding == FULLFRAME && s->xpos > 0 &&
351         s->outpicref) {
352         if (s->orientation == VERTICAL) {
353             for (i = 0; i < outlink->h; i++) {
354                 memset(s->outpicref->data[0] + i * s->outpicref->linesize[0] + s->xpos,   0, outlink->w - s->xpos);
355                 memset(s->outpicref->data[1] + i * s->outpicref->linesize[1] + s->xpos, 128, outlink->w - s->xpos);
356                 memset(s->outpicref->data[2] + i * s->outpicref->linesize[2] + s->xpos, 128, outlink->w - s->xpos);
357             }
358         } else {
359             for (i = s->xpos; i < outlink->h; i++) {
360                 memset(s->outpicref->data[0] + i * s->outpicref->linesize[0],   0, outlink->w);
361                 memset(s->outpicref->data[1] + i * s->outpicref->linesize[1], 128, outlink->w);
362                 memset(s->outpicref->data[2] + i * s->outpicref->linesize[2], 128, outlink->w);
363             }
364         }
365         ret = ff_filter_frame(outlink, s->outpicref);
366         s->outpicref = NULL;
367     }
368
369     return ret;
370 }
371
372 static int plot_spectrum_column(AVFilterLink *inlink, AVFrame *insamples)
373 {
374     int ret;
375     AVFilterContext *ctx = inlink->dst;
376     AVFilterLink *outlink = ctx->outputs[0];
377     ShowSpectrumContext *s = ctx->priv;
378     AVFrame *outpicref = s->outpicref;
379
380     /* nb_freq contains the power of two superior or equal to the output image
381      * height (or half the RDFT window size) */
382     const int nb_freq = 1 << (s->rdft_bits - 1);
383     const int win_size = nb_freq << 1;
384     const double w = s->win_scale;
385     int h = s->orientation == VERTICAL ? s->channel_height : s->channel_width;
386
387     int ch, plane, n, x, y;
388
389     av_assert0(insamples->nb_samples == win_size);
390
391     /* fill RDFT input with the number of samples available */
392     for (ch = 0; ch < s->nb_display_channels; ch++) {
393         const int16_t *p = (int16_t *)insamples->extended_data[ch];
394
395         for (n = 0; n < win_size; n++)
396             s->rdft_data[ch][n] = p[n] * s->window_func_lut[n];
397     }
398
399     /* run RDFT on each samples set */
400     for (ch = 0; ch < s->nb_display_channels; ch++)
401         av_rdft_calc(s->rdft, s->rdft_data[ch]);
402
403     /* fill a new spectrum column */
404 #define RE(y, ch) s->rdft_data[ch][2 * (y) + 0]
405 #define IM(y, ch) s->rdft_data[ch][2 * (y) + 1]
406 #define MAGNITUDE(y, ch) hypot(RE(y, ch), IM(y, ch))
407
408     /* initialize buffer for combining to black */
409     if (s->orientation == VERTICAL) {
410         for (y = 0; y < outlink->h; y++) {
411             s->combine_buffer[3 * y    ] = 0;
412             s->combine_buffer[3 * y + 1] = 127.5;
413             s->combine_buffer[3 * y + 2] = 127.5;
414         }
415     } else {
416         for (y = 0; y < outlink->w; y++) {
417             s->combine_buffer[3 * y    ] = 0;
418             s->combine_buffer[3 * y + 1] = 127.5;
419             s->combine_buffer[3 * y + 2] = 127.5;
420         }
421     }
422
423     for (ch = 0; ch < s->nb_display_channels; ch++) {
424         float yf, uf, vf;
425
426         /* decide color range */
427         switch (s->mode) {
428         case COMBINED:
429             // reduce range by channel count
430             yf = 256.0f / s->nb_display_channels;
431             switch (s->color_mode) {
432             case RAINBOW:
433             case MORELAND:
434             case NEBULAE:
435             case FIRE:
436             case INTENSITY:
437                 uf = yf;
438                 vf = yf;
439                 break;
440             case CHANNEL:
441                 /* adjust saturation for mixed UV coloring */
442                 /* this factor is correct for infinite channels, an approximation otherwise */
443                 uf = yf * M_PI;
444                 vf = yf * M_PI;
445                 break;
446             default:
447                 av_assert0(0);
448             }
449             break;
450         case SEPARATE:
451             // full range
452             yf = 256.0f;
453             uf = 256.0f;
454             vf = 256.0f;
455             break;
456         default:
457             av_assert0(0);
458         }
459
460         if (s->color_mode == CHANNEL) {
461             if (s->nb_display_channels > 1) {
462                 uf *= 0.5 * sin((2 * M_PI * ch) / s->nb_display_channels);
463                 vf *= 0.5 * cos((2 * M_PI * ch) / s->nb_display_channels);
464             } else {
465                 uf = 0.0f;
466                 vf = 0.0f;
467             }
468         }
469         uf *= s->saturation;
470         vf *= s->saturation;
471
472         /* draw the channel */
473         for (y = 0; y < h; y++) {
474             int row = (s->mode == COMBINED) ? y : ch * h + y;
475             float *out = &s->combine_buffer[3 * row];
476
477             /* get magnitude */
478             float a = w * MAGNITUDE(y, ch);
479
480             /* apply scale */
481             switch (s->scale) {
482             case LINEAR:
483                 break;
484             case SQRT:
485                 a = sqrt(a);
486                 break;
487             case CBRT:
488                 a = cbrt(a);
489                 break;
490             case LOG:
491                 a = 1 + log10(FFMAX(FFMIN(1, a), 1e-6)) / 5; // zero = -120dBFS
492                 break;
493             default:
494                 av_assert0(0);
495             }
496
497             if (s->color_mode > CHANNEL) {
498                 const int cm = s->color_mode;
499                 float y, u, v;
500                 int i;
501
502                 for (i = 1; i < FF_ARRAY_ELEMS(color_table[cm]) - 1; i++)
503                     if (color_table[cm][i].a >= a)
504                         break;
505                 // i now is the first item >= the color
506                 // now we know to interpolate between item i - 1 and i
507                 if (a <= color_table[cm][i - 1].a) {
508                     y = color_table[cm][i - 1].y;
509                     u = color_table[cm][i - 1].u;
510                     v = color_table[cm][i - 1].v;
511                 } else if (a >= color_table[cm][i].a) {
512                     y = color_table[cm][i].y;
513                     u = color_table[cm][i].u;
514                     v = color_table[cm][i].v;
515                 } else {
516                     float start = color_table[cm][i - 1].a;
517                     float end = color_table[cm][i].a;
518                     float lerpfrac = (a - start) / (end - start);
519                     y = color_table[cm][i - 1].y * (1.0f - lerpfrac)
520                       + color_table[cm][i].y * lerpfrac;
521                     u = color_table[cm][i - 1].u * (1.0f - lerpfrac)
522                       + color_table[cm][i].u * lerpfrac;
523                     v = color_table[cm][i - 1].v * (1.0f - lerpfrac)
524                       + color_table[cm][i].v * lerpfrac;
525                 }
526
527                 out[0] += y * yf;
528                 out[1] += u * uf;
529                 out[2] += v * vf;
530             } else {
531                 out[0] += a * yf;
532                 out[1] += a * uf;
533                 out[2] += a * vf;
534             }
535         }
536     }
537
538     av_frame_make_writable(s->outpicref);
539     /* copy to output */
540     if (s->orientation == VERTICAL) {
541         if (s->sliding == SCROLL) {
542             for (plane = 0; plane < 3; plane++) {
543                 for (y = 0; y < outlink->h; y++) {
544                     uint8_t *p = outpicref->data[plane] +
545                                  y * outpicref->linesize[plane];
546                     memmove(p, p + 1, outlink->w - 1);
547                 }
548             }
549             s->xpos = outlink->w - 1;
550         } else if (s->sliding == RSCROLL) {
551             for (plane = 0; plane < 3; plane++) {
552                 for (y = 0; y < outlink->h; y++) {
553                     uint8_t *p = outpicref->data[plane] +
554                                  y * outpicref->linesize[plane];
555                     memmove(p + 1, p, outlink->w - 1);
556                 }
557             }
558             s->xpos = 0;
559         }
560         for (plane = 0; plane < 3; plane++) {
561             uint8_t *p = outpicref->data[plane] +
562                          (outlink->h - 1) * outpicref->linesize[plane] +
563                          s->xpos;
564             for (y = 0; y < outlink->h; y++) {
565                 *p = lrint(FFMAX(0, FFMIN(s->combine_buffer[3 * y + plane], 255)));
566                 p -= outpicref->linesize[plane];
567             }
568         }
569     } else {
570         if (s->sliding == SCROLL) {
571             for (plane = 0; plane < 3; plane++) {
572                 for (y = 1; y < outlink->h; y++) {
573                     memmove(outpicref->data[plane] + (y-1) * outpicref->linesize[plane],
574                             outpicref->data[plane] + (y  ) * outpicref->linesize[plane],
575                             outlink->w);
576                 }
577             }
578             s->xpos = outlink->h - 1;
579         } else if (s->sliding == RSCROLL) {
580             for (plane = 0; plane < 3; plane++) {
581                 for (y = outlink->h - 1; y >= 1; y--) {
582                     memmove(outpicref->data[plane] + (y  ) * outpicref->linesize[plane],
583                             outpicref->data[plane] + (y-1) * outpicref->linesize[plane],
584                             outlink->w);
585                 }
586             }
587             s->xpos = 0;
588         }
589         for (plane = 0; plane < 3; plane++) {
590             uint8_t *p = outpicref->data[plane] +
591                          s->xpos * outpicref->linesize[plane];
592             for (x = 0; x < outlink->w; x++) {
593                 *p = lrint(FFMAX(0, FFMIN(s->combine_buffer[3 * x + plane], 255)));
594                 p++;
595             }
596         }
597     }
598
599     if (s->sliding != FULLFRAME || s->xpos == 0)
600         outpicref->pts = insamples->pts;
601
602     s->xpos++;
603     if (s->orientation == VERTICAL && s->xpos >= outlink->w)
604         s->xpos = 0;
605     if (s->orientation == HORIZONTAL && s->xpos >= outlink->h)
606         s->xpos = 0;
607     if (s->sliding != FULLFRAME || s->xpos == 0) {
608         ret = ff_filter_frame(outlink, av_frame_clone(s->outpicref));
609         if (ret < 0)
610             return ret;
611     }
612
613     return win_size;
614 }
615
616 static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
617 {
618     AVFilterContext *ctx = inlink->dst;
619     ShowSpectrumContext *s = ctx->priv;
620     unsigned win_size = 1 << s->rdft_bits;
621     AVFrame *fin = NULL;
622     int ret = 0;
623
624     av_audio_fifo_write(s->fifo, (void **)insamples->extended_data, insamples->nb_samples);
625     av_frame_free(&insamples);
626     while (av_audio_fifo_size(s->fifo) >= win_size) {
627         fin = ff_get_audio_buffer(inlink, win_size);
628         if (!fin) {
629             ret = AVERROR(ENOMEM);
630             goto fail;
631         }
632
633         fin->pts = s->pts;
634         s->pts += s->skip_samples;
635         ret = av_audio_fifo_peek(s->fifo, (void **)fin->extended_data, win_size);
636         if (ret < 0)
637             goto fail;
638
639         ret = plot_spectrum_column(inlink, fin);
640         av_frame_free(&fin);
641         av_audio_fifo_drain(s->fifo, s->skip_samples);
642         if (ret < 0)
643             goto fail;
644     }
645
646 fail:
647     av_frame_free(&fin);
648     return ret;
649 }
650
651 static const AVFilterPad showspectrum_inputs[] = {
652     {
653         .name         = "default",
654         .type         = AVMEDIA_TYPE_AUDIO,
655         .filter_frame = filter_frame,
656     },
657     { NULL }
658 };
659
660 static const AVFilterPad showspectrum_outputs[] = {
661     {
662         .name          = "default",
663         .type          = AVMEDIA_TYPE_VIDEO,
664         .config_props  = config_output,
665         .request_frame = request_frame,
666     },
667     { NULL }
668 };
669
670 AVFilter ff_avf_showspectrum = {
671     .name          = "showspectrum",
672     .description   = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output."),
673     .uninit        = uninit,
674     .query_formats = query_formats,
675     .priv_size     = sizeof(ShowSpectrumContext),
676     .inputs        = showspectrum_inputs,
677     .outputs       = showspectrum_outputs,
678     .priv_class    = &showspectrum_class,
679 };