]> git.sesse.net Git - ffmpeg/blob - libavfilter/avf_showspectrum.c
avfilter/avf_showspectrum: make some helper functions
[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, FIERY, 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     float **magnitudes;
67     int win_func;
68     int win_size;
69     double win_scale;
70     float overlap;
71     int skip_samples;
72     float *combine_buffer;      ///< color combining buffer (3 * h items)
73     AVAudioFifo *fifo;
74     int64_t pts;
75     int single_pic;
76 } ShowSpectrumContext;
77
78 #define OFFSET(x) offsetof(ShowSpectrumContext, x)
79 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
80
81 static const AVOption showspectrum_options[] = {
82     { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
83     { "s",    "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
84     { "slide", "set sliding mode", OFFSET(sliding), AV_OPT_TYPE_INT, {.i64 = 0}, 0, NB_SLIDES-1, FLAGS, "slide" },
85         { "replace", "replace old columns with new", 0, AV_OPT_TYPE_CONST, {.i64=REPLACE}, 0, 0, FLAGS, "slide" },
86         { "scroll", "scroll from right to left", 0, AV_OPT_TYPE_CONST, {.i64=SCROLL}, 0, 0, FLAGS, "slide" },
87         { "rscroll", "scroll from left to right", 0, AV_OPT_TYPE_CONST, {.i64=RSCROLL}, 0, 0, FLAGS, "slide" },
88         { "fullframe", "return full frames", 0, AV_OPT_TYPE_CONST, {.i64=FULLFRAME}, 0, 0, FLAGS, "slide" },
89     { "mode", "set channel display mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=COMBINED}, COMBINED, NB_MODES-1, FLAGS, "mode" },
90         { "combined", "combined mode", 0, AV_OPT_TYPE_CONST, {.i64=COMBINED}, 0, 0, FLAGS, "mode" },
91         { "separate", "separate mode", 0, AV_OPT_TYPE_CONST, {.i64=SEPARATE}, 0, 0, FLAGS, "mode" },
92     { "color", "set channel coloring", OFFSET(color_mode), AV_OPT_TYPE_INT, {.i64=CHANNEL}, CHANNEL, NB_CLMODES-1, FLAGS, "color" },
93         { "channel",   "separate color for each channel", 0, AV_OPT_TYPE_CONST, {.i64=CHANNEL},   0, 0, FLAGS, "color" },
94         { "intensity", "intensity based coloring",        0, AV_OPT_TYPE_CONST, {.i64=INTENSITY}, 0, 0, FLAGS, "color" },
95         { "rainbow",   "rainbow based coloring",          0, AV_OPT_TYPE_CONST, {.i64=RAINBOW},   0, 0, FLAGS, "color" },
96         { "moreland",  "moreland based coloring",         0, AV_OPT_TYPE_CONST, {.i64=MORELAND},  0, 0, FLAGS, "color" },
97         { "nebulae",   "nebulae based coloring",          0, AV_OPT_TYPE_CONST, {.i64=NEBULAE},   0, 0, FLAGS, "color" },
98         { "fire",      "fire based coloring",             0, AV_OPT_TYPE_CONST, {.i64=FIRE},      0, 0, FLAGS, "color" },
99         { "fiery",     "fiery based coloring",            0, AV_OPT_TYPE_CONST, {.i64=FIERY},     0, 0, FLAGS, "color" },
100     { "scale", "set display scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64=SQRT}, LINEAR, NB_SCALES-1, FLAGS, "scale" },
101         { "sqrt", "square root", 0, AV_OPT_TYPE_CONST, {.i64=SQRT},   0, 0, FLAGS, "scale" },
102         { "cbrt", "cubic root",  0, AV_OPT_TYPE_CONST, {.i64=CBRT},   0, 0, FLAGS, "scale" },
103         { "log",  "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG},    0, 0, FLAGS, "scale" },
104         { "lin",  "linear",      0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, FLAGS, "scale" },
105     { "saturation", "color saturation multiplier", OFFSET(saturation), AV_OPT_TYPE_FLOAT, {.dbl = 1}, -10, 10, FLAGS },
106     { "win_func", "set window function", OFFSET(win_func), AV_OPT_TYPE_INT, {.i64 = WFUNC_HANNING}, 0, NB_WFUNC-1, FLAGS, "win_func" },
107         { "rect",     "Rectangular",      0, AV_OPT_TYPE_CONST, {.i64=WFUNC_RECT},     0, 0, FLAGS, "win_func" },
108         { "bartlett", "Bartlett",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BARTLETT}, 0, 0, FLAGS, "win_func" },
109         { "hann",     "Hann",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, FLAGS, "win_func" },
110         { "hanning",  "Hanning",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, FLAGS, "win_func" },
111         { "hamming",  "Hamming",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HAMMING},  0, 0, FLAGS, "win_func" },
112         { "blackman", "Blackman",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BLACKMAN}, 0, 0, FLAGS, "win_func" },
113         { "welch",    "Welch",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_WELCH},    0, 0, FLAGS, "win_func" },
114         { "flattop",  "Flat-top",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_FLATTOP},  0, 0, FLAGS, "win_func" },
115         { "bharris",  "Blackman-Harris",  0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BHARRIS},  0, 0, FLAGS, "win_func" },
116         { "bnuttall", "Blackman-Nuttall", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BNUTTALL}, 0, 0, FLAGS, "win_func" },
117         { "bhann",    "Bartlett-Hann",    0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BHANN},    0, 0, FLAGS, "win_func" },
118         { "sine",     "Sine",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_SINE},     0, 0, FLAGS, "win_func" },
119         { "nuttall",  "Nuttall",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_NUTTALL},  0, 0, FLAGS, "win_func" },
120         { "lanczos",  "Lanczos",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_LANCZOS},  0, 0, FLAGS, "win_func" },
121         { "gauss",    "Gauss",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_GAUSS},    0, 0, FLAGS, "win_func" },
122     { "orientation", "set orientation", OFFSET(orientation), AV_OPT_TYPE_INT, {.i64=VERTICAL}, 0, NB_ORIENTATIONS-1, FLAGS, "orientation" },
123         { "vertical",   NULL, 0, AV_OPT_TYPE_CONST, {.i64=VERTICAL},   0, 0, FLAGS, "orientation" },
124         { "horizontal", NULL, 0, AV_OPT_TYPE_CONST, {.i64=HORIZONTAL}, 0, 0, FLAGS, "orientation" },
125     { "overlap", "set window overlap", OFFSET(overlap), AV_OPT_TYPE_FLOAT, {.dbl = 0}, 0, 1, FLAGS },
126     { NULL }
127 };
128
129 AVFILTER_DEFINE_CLASS(showspectrum);
130
131 static const struct ColorTable {
132     float a, y, u, v;
133 } color_table[][8] = {
134     [INTENSITY] = {
135     {    0,                  0,                  0,                   0 },
136     { 0.13, .03587126228984074,  .1573300977624594, -.02548747583751842 },
137     { 0.30, .18572281794568020,  .1772436246393981,  .17475554840414750 },
138     { 0.60, .28184980583656130, -.1593064119945782,  .47132074554608920 },
139     { 0.73, .65830621175547810, -.3716070802232764,  .24352759331252930 },
140     { 0.78, .76318535758242900, -.4307467689263783,  .16866496622310430 },
141     { 0.91, .95336363636363640, -.2045454545454546,  .03313636363636363 },
142     {    1,                  1,                  0,                   0 }},
143     [RAINBOW] = {
144     {    0,                  0,                  0,                   0 },
145     { 0.13,            44/256.,     (189-128)/256.,      (138-128)/256. },
146     { 0.25,            29/256.,     (186-128)/256.,      (119-128)/256. },
147     { 0.38,           119/256.,     (194-128)/256.,       (53-128)/256. },
148     { 0.60,           111/256.,      (73-128)/256.,       (59-128)/256. },
149     { 0.73,           205/256.,      (19-128)/256.,      (149-128)/256. },
150     { 0.86,           135/256.,      (83-128)/256.,      (200-128)/256. },
151     {    1,            73/256.,      (95-128)/256.,      (225-128)/256. }},
152     [MORELAND] = {
153     {    0,            44/256.,     (181-128)/256.,      (112-128)/256. },
154     { 0.13,           126/256.,     (177-128)/256.,      (106-128)/256. },
155     { 0.25,           164/256.,     (163-128)/256.,      (109-128)/256. },
156     { 0.38,           200/256.,     (140-128)/256.,      (120-128)/256. },
157     { 0.60,           201/256.,     (117-128)/256.,      (141-128)/256. },
158     { 0.73,           177/256.,     (103-128)/256.,      (165-128)/256. },
159     { 0.86,           136/256.,     (100-128)/256.,      (183-128)/256. },
160     {    1,            68/256.,     (117-128)/256.,      (203-128)/256. }},
161     [NEBULAE] = {
162     {    0,            10/256.,     (134-128)/256.,      (132-128)/256. },
163     { 0.23,            21/256.,     (137-128)/256.,      (130-128)/256. },
164     { 0.45,            35/256.,     (134-128)/256.,      (134-128)/256. },
165     { 0.57,            51/256.,     (130-128)/256.,      (139-128)/256. },
166     { 0.67,           104/256.,     (116-128)/256.,      (162-128)/256. },
167     { 0.77,           120/256.,     (105-128)/256.,      (188-128)/256. },
168     { 0.87,           140/256.,     (105-128)/256.,      (188-128)/256. },
169     {    1,                  1,                  0,                   0 }},
170     [FIRE] = {
171     {    0,                  0,                  0,                   0 },
172     { 0.23,            44/256.,     (132-128)/256.,      (127-128)/256. },
173     { 0.45,            62/256.,     (116-128)/256.,      (140-128)/256. },
174     { 0.57,            75/256.,     (105-128)/256.,      (152-128)/256. },
175     { 0.67,            95/256.,      (91-128)/256.,      (166-128)/256. },
176     { 0.77,           126/256.,      (74-128)/256.,      (172-128)/256. },
177     { 0.87,           164/256.,      (73-128)/256.,      (162-128)/256. },
178     {    1,                  1,                  0,                   0 }},
179     [FIERY] = {
180     {    0,                  0,                  0,                   0 },
181     { 0.23,            36/256.,     (116-128)/256.,      (163-128)/256. },
182     { 0.45,            52/256.,     (102-128)/256.,      (200-128)/256. },
183     { 0.57,           116/256.,      (84-128)/256.,      (196-128)/256. },
184     { 0.67,           157/256.,      (67-128)/256.,      (181-128)/256. },
185     { 0.77,           193/256.,      (40-128)/256.,      (155-128)/256. },
186     { 0.87,           221/256.,     (101-128)/256.,      (134-128)/256. },
187     {    1,                  1,                  0,                   0 }},
188 };
189
190 static av_cold void uninit(AVFilterContext *ctx)
191 {
192     ShowSpectrumContext *s = ctx->priv;
193     int i;
194
195     av_freep(&s->combine_buffer);
196     av_rdft_end(s->rdft);
197     if (s->rdft_data) {
198         for (i = 0; i < s->nb_display_channels; i++)
199             av_freep(&s->rdft_data[i]);
200     }
201     av_freep(&s->rdft_data);
202     av_freep(&s->window_func_lut);
203     if (s->magnitudes) {
204         for (i = 0; i < s->nb_display_channels; i++)
205             av_freep(&s->magnitudes[i]);
206     }
207     av_freep(&s->magnitudes);
208     av_frame_free(&s->outpicref);
209     av_audio_fifo_free(s->fifo);
210 }
211
212 static int query_formats(AVFilterContext *ctx)
213 {
214     AVFilterFormats *formats = NULL;
215     AVFilterChannelLayouts *layouts = NULL;
216     AVFilterLink *inlink = ctx->inputs[0];
217     AVFilterLink *outlink = ctx->outputs[0];
218     static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE };
219     static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_NONE };
220     int ret;
221
222     /* set input audio formats */
223     formats = ff_make_format_list(sample_fmts);
224     if ((ret = ff_formats_ref(formats, &inlink->out_formats)) < 0)
225         return ret;
226
227     layouts = ff_all_channel_layouts();
228     if ((ret = ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts)) < 0)
229         return ret;
230
231     formats = ff_all_samplerates();
232     if ((ret = ff_formats_ref(formats, &inlink->out_samplerates)) < 0)
233         return ret;
234
235     /* set output video format */
236     formats = ff_make_format_list(pix_fmts);
237     if ((ret = ff_formats_ref(formats, &outlink->in_formats)) < 0)
238         return ret;
239
240     return 0;
241 }
242
243 static int config_output(AVFilterLink *outlink)
244 {
245     AVFilterContext *ctx = outlink->src;
246     AVFilterLink *inlink = ctx->inputs[0];
247     ShowSpectrumContext *s = ctx->priv;
248     int i, rdft_bits, h, w;
249     float overlap;
250
251     if (!strcmp(ctx->filter->name, "showspectrumpic"))
252         s->single_pic = 1;
253
254     outlink->w = s->w;
255     outlink->h = s->h;
256
257     h = (s->mode == COMBINED || s->orientation == HORIZONTAL) ? outlink->h : outlink->h / inlink->channels;
258     w = (s->mode == COMBINED || s->orientation == VERTICAL)   ? outlink->w : outlink->w / inlink->channels;
259     s->channel_height = h;
260     s->channel_width  = w;
261
262     if (s->orientation == VERTICAL) {
263         /* RDFT window size (precision) according to the requested output frame height */
264         for (rdft_bits = 1; 1 << rdft_bits < 2 * h; rdft_bits++);
265     } else {
266         /* RDFT window size (precision) according to the requested output frame width */
267         for (rdft_bits = 1; 1 << rdft_bits < 2 * w; rdft_bits++);
268     }
269     s->win_size = 1 << rdft_bits;
270
271     /* (re-)configuration if the video output changed (or first init) */
272     if (rdft_bits != s->rdft_bits) {
273         AVFrame *outpicref;
274
275         av_rdft_end(s->rdft);
276         s->rdft = av_rdft_init(rdft_bits, DFT_R2C);
277         if (!s->rdft) {
278             av_log(ctx, AV_LOG_ERROR, "Unable to create RDFT context. "
279                    "The window size might be too high.\n");
280             return AVERROR(EINVAL);
281         }
282         s->rdft_bits = rdft_bits;
283
284         /* RDFT buffers: x2 for each (display) channel buffer.
285          * Note: we use free and malloc instead of a realloc-like function to
286          * make sure the buffer is aligned in memory for the FFT functions. */
287         for (i = 0; i < s->nb_display_channels; i++)
288             av_freep(&s->rdft_data[i]);
289         av_freep(&s->rdft_data);
290         s->nb_display_channels = inlink->channels;
291
292         s->magnitudes = av_calloc(s->nb_display_channels, sizeof(*s->magnitudes));
293         if (!s->magnitudes)
294             return AVERROR(ENOMEM);
295         for (i = 0; i < s->nb_display_channels; i++) {
296             s->magnitudes[i] = av_calloc(s->orientation == VERTICAL ? s->h : s->w, sizeof(**s->magnitudes));
297             if (!s->magnitudes[i])
298                 return AVERROR(ENOMEM);
299         }
300
301         s->rdft_data = av_calloc(s->nb_display_channels, sizeof(*s->rdft_data));
302         if (!s->rdft_data)
303             return AVERROR(ENOMEM);
304         for (i = 0; i < s->nb_display_channels; i++) {
305             s->rdft_data[i] = av_calloc(s->win_size, sizeof(**s->rdft_data));
306             if (!s->rdft_data[i])
307                 return AVERROR(ENOMEM);
308         }
309
310         /* pre-calc windowing function */
311         s->window_func_lut =
312             av_realloc_f(s->window_func_lut, s->win_size,
313                          sizeof(*s->window_func_lut));
314         if (!s->window_func_lut)
315             return AVERROR(ENOMEM);
316         ff_generate_window_func(s->window_func_lut, s->win_size, s->win_func, &overlap);
317         if (s->overlap == 1)
318             s->overlap = overlap;
319         s->skip_samples = (1. - s->overlap) * s->win_size;
320         if (s->skip_samples < 1) {
321             av_log(ctx, AV_LOG_ERROR, "overlap %f too big\n", s->overlap);
322             return AVERROR(EINVAL);
323         }
324
325         for (s->win_scale = 0, i = 0; i < s->win_size; i++) {
326             s->win_scale += s->window_func_lut[i] * s->window_func_lut[i];
327         }
328         s->win_scale = 1. / (sqrt(s->win_scale) * 32768.);
329
330         /* prepare the initial picref buffer (black frame) */
331         av_frame_free(&s->outpicref);
332         s->outpicref = outpicref =
333             ff_get_video_buffer(outlink, outlink->w, outlink->h);
334         if (!outpicref)
335             return AVERROR(ENOMEM);
336         outlink->sample_aspect_ratio = (AVRational){1,1};
337         for (i = 0; i < outlink->h; i++) {
338             memset(outpicref->data[0] + i * outpicref->linesize[0],   0, outlink->w);
339             memset(outpicref->data[1] + i * outpicref->linesize[1], 128, outlink->w);
340             memset(outpicref->data[2] + i * outpicref->linesize[2], 128, outlink->w);
341         }
342     }
343
344     if ((s->orientation == VERTICAL   && s->xpos >= outlink->w) ||
345         (s->orientation == HORIZONTAL && s->xpos >= outlink->h))
346         s->xpos = 0;
347
348     outlink->frame_rate = av_make_q(inlink->sample_rate, s->win_size * (1.-s->overlap));
349     if (s->orientation == VERTICAL && s->sliding == FULLFRAME)
350         outlink->frame_rate.den *= outlink->w;
351     if (s->orientation == HORIZONTAL && s->sliding == FULLFRAME)
352         outlink->frame_rate.den *= outlink->h;
353
354     if (s->orientation == VERTICAL) {
355         s->combine_buffer =
356             av_realloc_f(s->combine_buffer, outlink->h * 3,
357                          sizeof(*s->combine_buffer));
358     } else {
359         s->combine_buffer =
360             av_realloc_f(s->combine_buffer, outlink->w * 3,
361                          sizeof(*s->combine_buffer));
362     }
363
364     av_log(ctx, AV_LOG_VERBOSE, "s:%dx%d RDFT window size:%d\n",
365            s->w, s->h, s->win_size);
366
367     av_audio_fifo_free(s->fifo);
368     s->fifo = av_audio_fifo_alloc(inlink->format, inlink->channels, s->win_size);
369     if (!s->fifo)
370         return AVERROR(ENOMEM);
371     return 0;
372 }
373
374 static void run_rdft(ShowSpectrumContext *s, AVFrame *fin)
375 {
376     int ch, n;
377
378     /* fill RDFT input with the number of samples available */
379     for (ch = 0; ch < s->nb_display_channels; ch++) {
380         const int16_t *p = (int16_t *)fin->extended_data[ch];
381
382         for (n = 0; n < s->win_size; n++)
383             s->rdft_data[ch][n] = p[n] * s->window_func_lut[n];
384     }
385
386     /* run RDFT on each samples set */
387     for (ch = 0; ch < s->nb_display_channels; ch++)
388         av_rdft_calc(s->rdft, s->rdft_data[ch]);
389 }
390
391 #define RE(y, ch) s->rdft_data[ch][2 * (y) + 0]
392 #define IM(y, ch) s->rdft_data[ch][2 * (y) + 1]
393 #define MAGNITUDE(y, ch) hypot(RE(y, ch), IM(y, ch))
394
395 static void calc_magnitudes(ShowSpectrumContext *s)
396 {
397     int ch, y, h = s->orientation == VERTICAL ? s->h : s->w;
398
399     for (ch = 0; ch < s->nb_display_channels; ch++) {
400         float *magnitudes = s->magnitudes[ch];
401
402         for (y = 0; y < h; y++)
403             magnitudes[y] = MAGNITUDE(y, ch);
404     }
405 }
406
407 static void acalc_magnitudes(ShowSpectrumContext *s)
408 {
409     int ch, y, h = s->orientation == VERTICAL ? s->h : s->w;
410
411     for (ch = 0; ch < s->nb_display_channels; ch++) {
412         float *magnitudes = s->magnitudes[ch];
413
414         for (y = 0; y < h; y++)
415             magnitudes[y] += MAGNITUDE(y, ch);
416     }
417 }
418
419 static void scale_magnitudes(ShowSpectrumContext *s, float scale)
420 {
421     int ch, y, h = s->orientation == VERTICAL ? s->h : s->w;
422
423     for (ch = 0; ch < s->nb_display_channels; ch++) {
424         float *magnitudes = s->magnitudes[ch];
425
426         for (y = 0; y < h; y++)
427             magnitudes[y] *= scale;
428     }
429 }
430
431 static void pick_color(ShowSpectrumContext *s,
432                        float yf, float uf, float vf,
433                        float a, float *out)
434 {
435     if (s->color_mode > CHANNEL) {
436         const int cm = s->color_mode;
437         float y, u, v;
438         int i;
439
440         for (i = 1; i < FF_ARRAY_ELEMS(color_table[cm]) - 1; i++)
441             if (color_table[cm][i].a >= a)
442                 break;
443         // i now is the first item >= the color
444         // now we know to interpolate between item i - 1 and i
445         if (a <= color_table[cm][i - 1].a) {
446             y = color_table[cm][i - 1].y;
447             u = color_table[cm][i - 1].u;
448             v = color_table[cm][i - 1].v;
449         } else if (a >= color_table[cm][i].a) {
450             y = color_table[cm][i].y;
451             u = color_table[cm][i].u;
452             v = color_table[cm][i].v;
453         } else {
454             float start = color_table[cm][i - 1].a;
455             float end = color_table[cm][i].a;
456             float lerpfrac = (a - start) / (end - start);
457             y = color_table[cm][i - 1].y * (1.0f - lerpfrac)
458               + color_table[cm][i].y * lerpfrac;
459             u = color_table[cm][i - 1].u * (1.0f - lerpfrac)
460               + color_table[cm][i].u * lerpfrac;
461             v = color_table[cm][i - 1].v * (1.0f - lerpfrac)
462               + color_table[cm][i].v * lerpfrac;
463         }
464
465         out[0] += y * yf;
466         out[1] += u * uf;
467         out[2] += v * vf;
468     } else {
469         out[0] += a * yf;
470         out[1] += a * uf;
471         out[2] += a * vf;
472     }
473 }
474
475 static void clear_combine_buffer(ShowSpectrumContext *s, int size)
476 {
477     int y;
478
479     for (y = 0; y < size; y++) {
480         s->combine_buffer[3 * y    ] = 0;
481         s->combine_buffer[3 * y + 1] = 127.5;
482         s->combine_buffer[3 * y + 2] = 127.5;
483     }
484 }
485
486 static int plot_spectrum_column(AVFilterLink *inlink, AVFrame *insamples)
487 {
488     int ret;
489     AVFilterContext *ctx = inlink->dst;
490     AVFilterLink *outlink = ctx->outputs[0];
491     ShowSpectrumContext *s = ctx->priv;
492     AVFrame *outpicref = s->outpicref;
493     const double w = s->win_scale;
494     int h = s->orientation == VERTICAL ? s->channel_height : s->channel_width;
495
496     int ch, plane, x, y;
497
498     /* fill a new spectrum column */
499     /* initialize buffer for combining to black */
500     clear_combine_buffer(s, s->orientation == VERTICAL ? outlink->h : outlink->w);
501
502     for (ch = 0; ch < s->nb_display_channels; ch++) {
503         float *magnitudes = s->magnitudes[ch];
504         float yf, uf, vf;
505
506         /* decide color range */
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 INTENSITY:
518                 uf = yf;
519                 vf = yf;
520                 break;
521             case CHANNEL:
522                 /* adjust saturation for mixed UV coloring */
523                 /* this factor is correct for infinite channels, an approximation otherwise */
524                 uf = yf * M_PI;
525                 vf = yf * M_PI;
526                 break;
527             default:
528                 av_assert0(0);
529             }
530             break;
531         case SEPARATE:
532             // full range
533             yf = 256.0f;
534             uf = 256.0f;
535             vf = 256.0f;
536             break;
537         default:
538             av_assert0(0);
539         }
540
541         if (s->color_mode == CHANNEL) {
542             if (s->nb_display_channels > 1) {
543                 uf *= 0.5 * sin((2 * M_PI * ch) / s->nb_display_channels);
544                 vf *= 0.5 * cos((2 * M_PI * ch) / s->nb_display_channels);
545             } else {
546                 uf = 0.0f;
547                 vf = 0.0f;
548             }
549         }
550         uf *= s->saturation;
551         vf *= s->saturation;
552
553         /* draw the channel */
554         for (y = 0; y < h; y++) {
555             int row = (s->mode == COMBINED) ? y : ch * h + y;
556             float *out = &s->combine_buffer[3 * row];
557
558             /* get magnitude */
559             float a = w * magnitudes[y];
560
561             /* apply scale */
562             switch (s->scale) {
563             case LINEAR:
564                 break;
565             case SQRT:
566                 a = sqrt(a);
567                 break;
568             case CBRT:
569                 a = cbrt(a);
570                 break;
571             case LOG:
572                 a = 1 + log10(FFMAX(FFMIN(1, a), 1e-6)) / 5; // zero = -120dBFS
573                 break;
574             default:
575                 av_assert0(0);
576             }
577
578             pick_color(s, yf, uf, vf, a, out);
579         }
580     }
581
582     av_frame_make_writable(s->outpicref);
583     /* copy to output */
584     if (s->orientation == VERTICAL) {
585         if (s->sliding == SCROLL) {
586             for (plane = 0; plane < 3; plane++) {
587                 for (y = 0; y < outlink->h; y++) {
588                     uint8_t *p = outpicref->data[plane] +
589                                  y * outpicref->linesize[plane];
590                     memmove(p, p + 1, outlink->w - 1);
591                 }
592             }
593             s->xpos = outlink->w - 1;
594         } else if (s->sliding == RSCROLL) {
595             for (plane = 0; plane < 3; plane++) {
596                 for (y = 0; y < outlink->h; y++) {
597                     uint8_t *p = outpicref->data[plane] +
598                                  y * outpicref->linesize[plane];
599                     memmove(p + 1, p, outlink->w - 1);
600                 }
601             }
602             s->xpos = 0;
603         }
604         for (plane = 0; plane < 3; plane++) {
605             uint8_t *p = outpicref->data[plane] +
606                          (outlink->h - 1) * outpicref->linesize[plane] +
607                          s->xpos;
608             for (y = 0; y < outlink->h; y++) {
609                 *p = lrint(FFMAX(0, FFMIN(s->combine_buffer[3 * y + plane], 255)));
610                 p -= outpicref->linesize[plane];
611             }
612         }
613     } else {
614         if (s->sliding == SCROLL) {
615             for (plane = 0; plane < 3; plane++) {
616                 for (y = 1; y < outlink->h; y++) {
617                     memmove(outpicref->data[plane] + (y-1) * outpicref->linesize[plane],
618                             outpicref->data[plane] + (y  ) * outpicref->linesize[plane],
619                             outlink->w);
620                 }
621             }
622             s->xpos = outlink->h - 1;
623         } else if (s->sliding == RSCROLL) {
624             for (plane = 0; plane < 3; plane++) {
625                 for (y = outlink->h - 1; y >= 1; y--) {
626                     memmove(outpicref->data[plane] + (y  ) * outpicref->linesize[plane],
627                             outpicref->data[plane] + (y-1) * outpicref->linesize[plane],
628                             outlink->w);
629                 }
630             }
631             s->xpos = 0;
632         }
633         for (plane = 0; plane < 3; plane++) {
634             uint8_t *p = outpicref->data[plane] +
635                          s->xpos * outpicref->linesize[plane];
636             for (x = 0; x < outlink->w; x++) {
637                 *p = lrint(FFMAX(0, FFMIN(s->combine_buffer[3 * x + plane], 255)));
638                 p++;
639             }
640         }
641     }
642
643     if (s->sliding != FULLFRAME || s->xpos == 0)
644         outpicref->pts = insamples->pts;
645
646     s->xpos++;
647     if (s->orientation == VERTICAL && s->xpos >= outlink->w)
648         s->xpos = 0;
649     if (s->orientation == HORIZONTAL && s->xpos >= outlink->h)
650         s->xpos = 0;
651     if (!s->single_pic && (s->sliding != FULLFRAME || s->xpos == 0)) {
652         ret = ff_filter_frame(outlink, av_frame_clone(s->outpicref));
653         if (ret < 0)
654             return ret;
655     }
656
657     return s->win_size;
658 }
659
660 #if CONFIG_SHOWSPECTRUM_FILTER
661
662 static int request_frame(AVFilterLink *outlink)
663 {
664     ShowSpectrumContext *s = outlink->src->priv;
665     AVFilterLink *inlink = outlink->src->inputs[0];
666     unsigned i;
667     int ret;
668
669     ret = ff_request_frame(inlink);
670     if (ret == AVERROR_EOF && s->sliding == FULLFRAME && s->xpos > 0 &&
671         s->outpicref) {
672         if (s->orientation == VERTICAL) {
673             for (i = 0; i < outlink->h; i++) {
674                 memset(s->outpicref->data[0] + i * s->outpicref->linesize[0] + s->xpos,   0, outlink->w - s->xpos);
675                 memset(s->outpicref->data[1] + i * s->outpicref->linesize[1] + s->xpos, 128, outlink->w - s->xpos);
676                 memset(s->outpicref->data[2] + i * s->outpicref->linesize[2] + s->xpos, 128, outlink->w - s->xpos);
677             }
678         } else {
679             for (i = s->xpos; i < outlink->h; i++) {
680                 memset(s->outpicref->data[0] + i * s->outpicref->linesize[0],   0, outlink->w);
681                 memset(s->outpicref->data[1] + i * s->outpicref->linesize[1], 128, outlink->w);
682                 memset(s->outpicref->data[2] + i * s->outpicref->linesize[2], 128, outlink->w);
683             }
684         }
685         ret = ff_filter_frame(outlink, s->outpicref);
686         s->outpicref = NULL;
687     }
688
689     return ret;
690 }
691
692 static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
693 {
694     AVFilterContext *ctx = inlink->dst;
695     ShowSpectrumContext *s = ctx->priv;
696     AVFrame *fin = NULL;
697     int ret = 0;
698
699     av_audio_fifo_write(s->fifo, (void **)insamples->extended_data, insamples->nb_samples);
700     av_frame_free(&insamples);
701     while (av_audio_fifo_size(s->fifo) >= s->win_size) {
702         fin = ff_get_audio_buffer(inlink, s->win_size);
703         if (!fin) {
704             ret = AVERROR(ENOMEM);
705             goto fail;
706         }
707
708         fin->pts = s->pts;
709         s->pts += s->skip_samples;
710         ret = av_audio_fifo_peek(s->fifo, (void **)fin->extended_data, s->win_size);
711         if (ret < 0)
712             goto fail;
713
714         av_assert0(fin->nb_samples == s->win_size);
715
716         run_rdft(s, fin);
717         calc_magnitudes(s);
718
719         ret = plot_spectrum_column(inlink, fin);
720         av_frame_free(&fin);
721         av_audio_fifo_drain(s->fifo, s->skip_samples);
722         if (ret < 0)
723             goto fail;
724     }
725
726 fail:
727     av_frame_free(&fin);
728     return ret;
729 }
730
731 static const AVFilterPad showspectrum_inputs[] = {
732     {
733         .name         = "default",
734         .type         = AVMEDIA_TYPE_AUDIO,
735         .filter_frame = filter_frame,
736     },
737     { NULL }
738 };
739
740 static const AVFilterPad showspectrum_outputs[] = {
741     {
742         .name          = "default",
743         .type          = AVMEDIA_TYPE_VIDEO,
744         .config_props  = config_output,
745         .request_frame = request_frame,
746     },
747     { NULL }
748 };
749
750 AVFilter ff_avf_showspectrum = {
751     .name          = "showspectrum",
752     .description   = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output."),
753     .uninit        = uninit,
754     .query_formats = query_formats,
755     .priv_size     = sizeof(ShowSpectrumContext),
756     .inputs        = showspectrum_inputs,
757     .outputs       = showspectrum_outputs,
758     .priv_class    = &showspectrum_class,
759 };
760 #endif // CONFIG_SHOWSPECTRUM_FILTER
761
762 #if CONFIG_SHOWSPECTRUMPIC_FILTER
763
764 static const AVOption showspectrumpic_options[] = {
765     { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "4096x2048"}, 0, 0, FLAGS },
766     { "s",    "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "4096x2048"}, 0, 0, FLAGS },
767     { "mode", "set channel display mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=COMBINED}, 0, NB_MODES-1, FLAGS, "mode" },
768         { "combined", "combined mode", 0, AV_OPT_TYPE_CONST, {.i64=COMBINED}, 0, 0, FLAGS, "mode" },
769         { "separate", "separate mode", 0, AV_OPT_TYPE_CONST, {.i64=SEPARATE}, 0, 0, FLAGS, "mode" },
770     { "color", "set channel coloring", OFFSET(color_mode), AV_OPT_TYPE_INT, {.i64=INTENSITY}, 0, NB_CLMODES-1, FLAGS, "color" },
771         { "channel",   "separate color for each channel", 0, AV_OPT_TYPE_CONST, {.i64=CHANNEL},   0, 0, FLAGS, "color" },
772         { "intensity", "intensity based coloring",        0, AV_OPT_TYPE_CONST, {.i64=INTENSITY}, 0, 0, FLAGS, "color" },
773         { "rainbow",   "rainbow based coloring",          0, AV_OPT_TYPE_CONST, {.i64=RAINBOW},   0, 0, FLAGS, "color" },
774         { "moreland",  "moreland based coloring",         0, AV_OPT_TYPE_CONST, {.i64=MORELAND},  0, 0, FLAGS, "color" },
775         { "nebulae",   "nebulae based coloring",          0, AV_OPT_TYPE_CONST, {.i64=NEBULAE},   0, 0, FLAGS, "color" },
776         { "fire",      "fire based coloring",             0, AV_OPT_TYPE_CONST, {.i64=FIRE},      0, 0, FLAGS, "color" },
777         { "fiery",     "fiery based coloring",            0, AV_OPT_TYPE_CONST, {.i64=FIERY},     0, 0, FLAGS, "color" },
778     { "scale", "set display scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64=LOG}, 0, NB_SCALES-1, FLAGS, "scale" },
779         { "sqrt", "square root", 0, AV_OPT_TYPE_CONST, {.i64=SQRT},   0, 0, FLAGS, "scale" },
780         { "cbrt", "cubic root",  0, AV_OPT_TYPE_CONST, {.i64=CBRT},   0, 0, FLAGS, "scale" },
781         { "log",  "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG},    0, 0, FLAGS, "scale" },
782         { "lin",  "linear",      0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, FLAGS, "scale" },
783     { "saturation", "color saturation multiplier", OFFSET(saturation), AV_OPT_TYPE_FLOAT, {.dbl = 1}, -10, 10, FLAGS },
784     { "win_func", "set window function", OFFSET(win_func), AV_OPT_TYPE_INT, {.i64 = WFUNC_HANNING}, 0, NB_WFUNC-1, FLAGS, "win_func" },
785         { "rect",     "Rectangular",      0, AV_OPT_TYPE_CONST, {.i64=WFUNC_RECT},     0, 0, FLAGS, "win_func" },
786         { "bartlett", "Bartlett",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BARTLETT}, 0, 0, FLAGS, "win_func" },
787         { "hann",     "Hann",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, FLAGS, "win_func" },
788         { "hanning",  "Hanning",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, FLAGS, "win_func" },
789         { "hamming",  "Hamming",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HAMMING},  0, 0, FLAGS, "win_func" },
790         { "blackman", "Blackman",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BLACKMAN}, 0, 0, FLAGS, "win_func" },
791         { "welch",    "Welch",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_WELCH},    0, 0, FLAGS, "win_func" },
792         { "flattop",  "Flat-top",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_FLATTOP},  0, 0, FLAGS, "win_func" },
793         { "bharris",  "Blackman-Harris",  0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BHARRIS},  0, 0, FLAGS, "win_func" },
794         { "bnuttall", "Blackman-Nuttall", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BNUTTALL}, 0, 0, FLAGS, "win_func" },
795         { "bhann",    "Bartlett-Hann",    0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BHANN},    0, 0, FLAGS, "win_func" },
796         { "sine",     "Sine",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_SINE},     0, 0, FLAGS, "win_func" },
797         { "nuttall",  "Nuttall",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_NUTTALL},  0, 0, FLAGS, "win_func" },
798         { "lanczos",  "Lanczos",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_LANCZOS},  0, 0, FLAGS, "win_func" },
799         { "gauss",    "Gauss",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_GAUSS},    0, 0, FLAGS, "win_func" },
800     { "orientation", "set orientation", OFFSET(orientation), AV_OPT_TYPE_INT, {.i64=VERTICAL}, 0, NB_ORIENTATIONS-1, FLAGS, "orientation" },
801         { "vertical",   NULL, 0, AV_OPT_TYPE_CONST, {.i64=VERTICAL},   0, 0, FLAGS, "orientation" },
802         { "horizontal", NULL, 0, AV_OPT_TYPE_CONST, {.i64=HORIZONTAL}, 0, 0, FLAGS, "orientation" },
803     { NULL }
804 };
805
806 AVFILTER_DEFINE_CLASS(showspectrumpic);
807
808 static int showspectrumpic_request_frame(AVFilterLink *outlink)
809 {
810     ShowSpectrumContext *s = outlink->src->priv;
811     AVFilterLink *inlink = outlink->src->inputs[0];
812     int ret;
813
814     ret = ff_request_frame(inlink);
815     if (ret == AVERROR_EOF && s->outpicref) {
816         int samples = av_audio_fifo_size(s->fifo);
817         int consumed = 0;
818         int x = 0, sz = s->orientation == VERTICAL ? s->w : s->h;
819         int ch, spf, spb;
820         AVFrame *fin;
821
822         spf = s->win_size * (samples / ((s->win_size * sz) * ceil(samples / (float)(s->win_size * sz))));
823         spb = (samples / (spf * sz)) * spf;
824
825         fin = ff_get_audio_buffer(inlink, s->win_size);
826         if (!fin)
827             return AVERROR(ENOMEM);
828
829         while (x < sz) {
830             ret = av_audio_fifo_peek(s->fifo, (void **)fin->extended_data, s->win_size);
831             if (ret < 0) {
832                 av_frame_free(&fin);
833                 return ret;
834             }
835
836             av_audio_fifo_drain(s->fifo, spf);
837
838             if (ret < s->win_size) {
839                 for (ch = 0; ch < s->nb_display_channels; ch++) {
840                     memset(fin->extended_data[ch] + ret * sizeof(int16_t), 0,
841                            (s->win_size - ret) * sizeof(int16_t));
842                 }
843             }
844
845             run_rdft(s, fin);
846             acalc_magnitudes(s);
847
848             consumed += spf;
849             if (consumed >= spb) {
850                 int h = s->orientation == VERTICAL ? s->h : s->w;
851
852                 scale_magnitudes(s, 1. / (consumed / spf));
853                 plot_spectrum_column(inlink, fin);
854                 consumed = 0;
855                 x++;
856                 for (ch = 0; ch < s->nb_display_channels; ch++)
857                     memset(s->magnitudes[ch], 0, h * sizeof(float));
858             }
859         }
860
861         av_frame_free(&fin);
862         s->outpicref->pts = 0;
863         ret = ff_filter_frame(outlink, s->outpicref);
864         s->outpicref = NULL;
865     }
866
867     return ret;
868 }
869
870 static int showspectrumpic_filter_frame(AVFilterLink *inlink, AVFrame *insamples)
871 {
872     AVFilterContext *ctx = inlink->dst;
873     ShowSpectrumContext *s = ctx->priv;
874     int ret;
875
876     ret = av_audio_fifo_write(s->fifo, (void **)insamples->extended_data, insamples->nb_samples);
877     av_frame_free(&insamples);
878     return ret;
879 }
880
881 static const AVFilterPad showspectrumpic_inputs[] = {
882     {
883         .name         = "default",
884         .type         = AVMEDIA_TYPE_AUDIO,
885         .filter_frame = showspectrumpic_filter_frame,
886     },
887     { NULL }
888 };
889
890 static const AVFilterPad showspectrumpic_outputs[] = {
891     {
892         .name          = "default",
893         .type          = AVMEDIA_TYPE_VIDEO,
894         .config_props  = config_output,
895         .request_frame = showspectrumpic_request_frame,
896     },
897     { NULL }
898 };
899
900 AVFilter ff_avf_showspectrumpic = {
901     .name          = "showspectrumpic",
902     .description   = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output single picture."),
903     .uninit        = uninit,
904     .query_formats = query_formats,
905     .priv_size     = sizeof(ShowSpectrumContext),
906     .inputs        = showspectrumpic_inputs,
907     .outputs       = showspectrumpic_outputs,
908     .priv_class    = &showspectrumpic_class,
909 };
910
911 #endif // CONFIG_SHOWSPECTRUMPIC_FILTER