2 * Copyright (c) 2012-2013 Clément Bœsch
3 * Copyright (c) 2013 Rudolf Polzer <divverent@xonotic.org>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * audio to spectrum (video) transmedia filter, based on ffplay rdft showmode
25 * (by Michael Niedermayer) and lavfi/avf_showwaves (by Stefano Sabatini).
30 #include "libavcodec/avfft.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/channel_layout.h"
33 #include "libavutil/opt.h"
37 enum DisplayMode { COMBINED, SEPARATE, NB_MODES };
38 enum DisplayScale { LINEAR, SQRT, CBRT, LOG, NB_SCALES };
39 enum ColorMode { CHANNEL, INTENSITY, NB_CLMODES };
40 enum WindowFunc { WFUNC_NONE, WFUNC_HANN, WFUNC_HAMMING, WFUNC_BLACKMAN, NB_WFUNC };
47 int nb_display_channels;
49 int sliding; ///< 1 if sliding mode, 0 otherwise
50 enum DisplayMode mode; ///< channel display mode
51 enum ColorMode color_mode; ///< display color scheme
52 enum DisplayScale scale;
53 float saturation; ///< color saturation multiplier
54 int xpos; ///< x position (current column)
55 RDFTContext *rdft; ///< Real Discrete Fourier Transform context
56 int rdft_bits; ///< number of bits (RDFT window size = 1<<rdft_bits)
57 FFTSample **rdft_data; ///< bins holder for each (displayed) channels
58 int filled; ///< number of samples (per channel) filled in current rdft_buffer
59 int consumed; ///< number of samples (per channel) consumed from the input frame
60 float *window_func_lut; ///< Window function LUT
61 enum WindowFunc win_func;
62 float *combine_buffer; ///< color combining buffer (3 * h items)
63 } ShowSpectrumContext;
65 #define OFFSET(x) offsetof(ShowSpectrumContext, x)
66 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
68 static const AVOption showspectrum_options[] = {
69 { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
70 { "s", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
71 { "slide", "set sliding mode", OFFSET(sliding), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, FLAGS },
72 { "mode", "set channel display mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=COMBINED}, COMBINED, NB_MODES-1, FLAGS, "mode" },
73 { "combined", "combined mode", 0, AV_OPT_TYPE_CONST, {.i64=COMBINED}, 0, 0, FLAGS, "mode" },
74 { "separate", "separate mode", 0, AV_OPT_TYPE_CONST, {.i64=SEPARATE}, 0, 0, FLAGS, "mode" },
75 { "color", "set channel coloring", OFFSET(color_mode), AV_OPT_TYPE_INT, {.i64=CHANNEL}, CHANNEL, NB_CLMODES-1, FLAGS, "color" },
76 { "channel", "separate color for each channel", 0, AV_OPT_TYPE_CONST, {.i64=CHANNEL}, 0, 0, FLAGS, "color" },
77 { "intensity", "intensity based coloring", 0, AV_OPT_TYPE_CONST, {.i64=INTENSITY}, 0, 0, FLAGS, "color" },
78 { "scale", "set display scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64=SQRT}, LINEAR, NB_SCALES-1, FLAGS, "scale" },
79 { "sqrt", "square root", 0, AV_OPT_TYPE_CONST, {.i64=SQRT}, 0, 0, FLAGS, "scale" },
80 { "cbrt", "cubic root", 0, AV_OPT_TYPE_CONST, {.i64=CBRT}, 0, 0, FLAGS, "scale" },
81 { "log", "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG}, 0, 0, FLAGS, "scale" },
82 { "lin", "linear", 0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, FLAGS, "scale" },
83 { "saturation", "color saturation multiplier", OFFSET(saturation), AV_OPT_TYPE_FLOAT, {.dbl = 1}, -10, 10, FLAGS },
84 { "win_func", "set window function", OFFSET(win_func), AV_OPT_TYPE_INT, {.i64 = WFUNC_HANN}, 0, NB_WFUNC-1, FLAGS, "win_func" },
85 { "hann", "Hann window", 0, AV_OPT_TYPE_CONST, {.i64 = WFUNC_HANN}, 0, 0, FLAGS, "win_func" },
86 { "hamming", "Hamming window", 0, AV_OPT_TYPE_CONST, {.i64 = WFUNC_HAMMING}, 0, 0, FLAGS, "win_func" },
87 { "blackman", "Blackman window", 0, AV_OPT_TYPE_CONST, {.i64 = WFUNC_BLACKMAN}, 0, 0, FLAGS, "win_func" },
91 AVFILTER_DEFINE_CLASS(showspectrum);
95 } intensity_color_table[] = {
97 { 0.13, .03587126228984074, .1573300977624594, -.02548747583751842 },
98 { 0.30, .18572281794568020, .1772436246393981, .17475554840414750 },
99 { 0.60, .28184980583656130, -.1593064119945782, .47132074554608920 },
100 { 0.73, .65830621175547810, -.3716070802232764, .24352759331252930 },
101 { 0.78, .76318535758242900, -.4307467689263783, .16866496622310430 },
102 { 0.91, .95336363636363640, -.2045454545454546, .03313636363636363 },
106 static av_cold void uninit(AVFilterContext *ctx)
108 ShowSpectrumContext *s = ctx->priv;
111 av_freep(&s->combine_buffer);
112 av_rdft_end(s->rdft);
113 for (i = 0; i < s->nb_display_channels; i++)
114 av_freep(&s->rdft_data[i]);
115 av_freep(&s->rdft_data);
116 av_freep(&s->window_func_lut);
117 av_frame_free(&s->outpicref);
120 static int query_formats(AVFilterContext *ctx)
122 AVFilterFormats *formats = NULL;
123 AVFilterChannelLayouts *layouts = NULL;
124 AVFilterLink *inlink = ctx->inputs[0];
125 AVFilterLink *outlink = ctx->outputs[0];
126 static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE };
127 static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_NONE };
129 /* set input audio formats */
130 formats = ff_make_format_list(sample_fmts);
132 return AVERROR(ENOMEM);
133 ff_formats_ref(formats, &inlink->out_formats);
135 layouts = ff_all_channel_layouts();
137 return AVERROR(ENOMEM);
138 ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts);
140 formats = ff_all_samplerates();
142 return AVERROR(ENOMEM);
143 ff_formats_ref(formats, &inlink->out_samplerates);
145 /* set output video format */
146 formats = ff_make_format_list(pix_fmts);
148 return AVERROR(ENOMEM);
149 ff_formats_ref(formats, &outlink->in_formats);
154 static int config_output(AVFilterLink *outlink)
156 AVFilterContext *ctx = outlink->src;
157 AVFilterLink *inlink = ctx->inputs[0];
158 ShowSpectrumContext *s = ctx->priv;
159 int i, rdft_bits, win_size, h;
164 h = (s->mode == COMBINED) ? outlink->h : outlink->h / inlink->channels;
165 s->channel_height = h;
167 /* RDFT window size (precision) according to the requested output frame height */
168 for (rdft_bits = 1; 1 << rdft_bits < 2 * h; rdft_bits++);
169 win_size = 1 << rdft_bits;
171 /* (re-)configuration if the video output changed (or first init) */
172 if (rdft_bits != s->rdft_bits) {
173 size_t rdft_size, rdft_listsize;
176 av_rdft_end(s->rdft);
177 s->rdft = av_rdft_init(rdft_bits, DFT_R2C);
178 s->rdft_bits = rdft_bits;
180 /* RDFT buffers: x2 for each (display) channel buffer.
181 * Note: we use free and malloc instead of a realloc-like function to
182 * make sure the buffer is aligned in memory for the FFT functions. */
183 for (i = 0; i < s->nb_display_channels; i++)
184 av_freep(&s->rdft_data[i]);
185 av_freep(&s->rdft_data);
186 s->nb_display_channels = inlink->channels;
188 if (av_size_mult(sizeof(*s->rdft_data),
189 s->nb_display_channels, &rdft_listsize) < 0)
190 return AVERROR(EINVAL);
191 if (av_size_mult(sizeof(**s->rdft_data),
192 win_size, &rdft_size) < 0)
193 return AVERROR(EINVAL);
194 s->rdft_data = av_malloc(rdft_listsize);
196 return AVERROR(ENOMEM);
197 for (i = 0; i < s->nb_display_channels; i++) {
198 s->rdft_data[i] = av_malloc(rdft_size);
199 if (!s->rdft_data[i])
200 return AVERROR(ENOMEM);
204 /* pre-calc windowing function */
206 av_realloc_f(s->window_func_lut, win_size,
207 sizeof(*s->window_func_lut));
208 if (!s->window_func_lut)
209 return AVERROR(ENOMEM);
210 switch (s->win_func) {
212 for (i = 0; i < win_size; i++)
213 s->window_func_lut[i] = 1.;
216 for (i = 0; i < win_size; i++)
217 s->window_func_lut[i] = .5f * (1 - cos(2*M_PI*i / (win_size-1)));
220 for (i = 0; i < win_size; i++)
221 s->window_func_lut[i] = .54f - .46f * cos(2*M_PI*i / (win_size-1));
223 case WFUNC_BLACKMAN: {
224 for (i = 0; i < win_size; i++)
225 s->window_func_lut[i] = .42f - .5f*cos(2*M_PI*i / (win_size-1)) + .08f*cos(4*M_PI*i / (win_size-1));
232 /* prepare the initial picref buffer (black frame) */
233 av_frame_free(&s->outpicref);
234 s->outpicref = outpicref =
235 ff_get_video_buffer(outlink, outlink->w, outlink->h);
237 return AVERROR(ENOMEM);
238 outlink->sample_aspect_ratio = (AVRational){1,1};
239 for (i = 0; i < outlink->h; i++) {
240 memset(outpicref->data[0] + i * outpicref->linesize[0], 0, outlink->w);
241 memset(outpicref->data[1] + i * outpicref->linesize[1], 128, outlink->w);
242 memset(outpicref->data[2] + i * outpicref->linesize[2], 128, outlink->w);
246 if (s->xpos >= outlink->w)
250 av_realloc_f(s->combine_buffer, outlink->h * 3,
251 sizeof(*s->combine_buffer));
253 av_log(ctx, AV_LOG_VERBOSE, "s:%dx%d RDFT window size:%d\n",
254 s->w, s->h, win_size);
258 inline static int push_frame(AVFilterLink *outlink)
260 ShowSpectrumContext *s = outlink->src->priv;
263 if (s->xpos >= outlink->w)
266 s->req_fullfilled = 1;
268 return ff_filter_frame(outlink, av_frame_clone(s->outpicref));
271 static int request_frame(AVFilterLink *outlink)
273 ShowSpectrumContext *s = outlink->src->priv;
274 AVFilterLink *inlink = outlink->src->inputs[0];
277 s->req_fullfilled = 0;
279 ret = ff_request_frame(inlink);
280 } while (!s->req_fullfilled && ret >= 0);
282 if (ret == AVERROR_EOF && s->outpicref)
287 static int plot_spectrum_column(AVFilterLink *inlink, AVFrame *insamples, int nb_samples)
290 AVFilterContext *ctx = inlink->dst;
291 AVFilterLink *outlink = ctx->outputs[0];
292 ShowSpectrumContext *s = ctx->priv;
293 AVFrame *outpicref = s->outpicref;
295 /* nb_freq contains the power of two superior or equal to the output image
296 * height (or half the RDFT window size) */
297 const int nb_freq = 1 << (s->rdft_bits - 1);
298 const int win_size = nb_freq << 1;
299 const double w = 1. / (sqrt(nb_freq) * 32768.);
302 const int start = s->filled;
303 const int add_samples = FFMIN(win_size - start, nb_samples);
305 /* fill RDFT input with the number of samples available */
306 for (ch = 0; ch < s->nb_display_channels; ch++) {
307 const int16_t *p = (int16_t *)insamples->extended_data[ch];
310 for (n = 0; n < add_samples; n++)
311 s->rdft_data[ch][start + n] = p[n] * s->window_func_lut[start + n];
313 s->filled += add_samples;
315 /* complete RDFT window size? */
316 if (s->filled == win_size) {
319 int h = s->channel_height;
321 /* run RDFT on each samples set */
322 for (ch = 0; ch < s->nb_display_channels; ch++)
323 av_rdft_calc(s->rdft, s->rdft_data[ch]);
325 /* fill a new spectrum column */
326 #define RE(y, ch) s->rdft_data[ch][2 * y + 0]
327 #define IM(y, ch) s->rdft_data[ch][2 * y + 1]
328 #define MAGNITUDE(y, ch) hypot(RE(y, ch), IM(y, ch))
330 /* initialize buffer for combining to black */
331 for (y = 0; y < outlink->h; y++) {
332 s->combine_buffer[3 * y ] = 0;
333 s->combine_buffer[3 * y + 1] = 127.5;
334 s->combine_buffer[3 * y + 2] = 127.5;
337 for (ch = 0; ch < s->nb_display_channels; ch++) {
340 /* decide color range */
343 // reduce range by channel count
344 yf = 256.0f / s->nb_display_channels;
345 switch (s->color_mode) {
351 /* adjust saturation for mixed UV coloring */
352 /* this factor is correct for infinite channels, an approximation otherwise */
370 if (s->color_mode == CHANNEL) {
371 if (s->nb_display_channels > 1) {
372 uf *= 0.5 * sin((2 * M_PI * ch) / s->nb_display_channels);
373 vf *= 0.5 * cos((2 * M_PI * ch) / s->nb_display_channels);
382 /* draw the channel */
383 for (y = 0; y < h; y++) {
384 int row = (s->mode == COMBINED) ? y : ch * h + y;
385 float *out = &s->combine_buffer[3 * row];
388 float a = w * MAGNITUDE(y, ch);
401 a = 1 - log(FFMAX(FFMIN(1, a), 1e-6)) / log(1e-6); // zero = -120dBFS
407 if (s->color_mode == INTENSITY) {
411 for (i = 1; i < sizeof(intensity_color_table) / sizeof(*intensity_color_table) - 1; i++)
412 if (intensity_color_table[i].a >= a)
414 // i now is the first item >= the color
415 // now we know to interpolate between item i - 1 and i
416 if (a <= intensity_color_table[i - 1].a) {
417 y = intensity_color_table[i - 1].y;
418 u = intensity_color_table[i - 1].u;
419 v = intensity_color_table[i - 1].v;
420 } else if (a >= intensity_color_table[i].a) {
421 y = intensity_color_table[i].y;
422 u = intensity_color_table[i].u;
423 v = intensity_color_table[i].v;
425 float start = intensity_color_table[i - 1].a;
426 float end = intensity_color_table[i].a;
427 float lerpfrac = (a - start) / (end - start);
428 y = intensity_color_table[i - 1].y * (1.0f - lerpfrac)
429 + intensity_color_table[i].y * lerpfrac;
430 u = intensity_color_table[i - 1].u * (1.0f - lerpfrac)
431 + intensity_color_table[i].u * lerpfrac;
432 v = intensity_color_table[i - 1].v * (1.0f - lerpfrac)
433 + intensity_color_table[i].v * lerpfrac;
449 for (plane = 0; plane < 3; plane++) {
450 for (y = 0; y < outlink->h; y++) {
451 uint8_t *p = outpicref->data[plane] +
452 y * outpicref->linesize[plane];
453 memmove(p, p + 1, outlink->w - 1);
456 s->xpos = outlink->w - 1;
458 for (plane = 0; plane < 3; plane++) {
459 uint8_t *p = outpicref->data[plane] +
460 (outlink->h - 1) * outpicref->linesize[plane] +
462 for (y = 0; y < outlink->h; y++) {
463 *p = rint(FFMAX(0, FFMIN(s->combine_buffer[3 * y + plane], 255)));
464 p -= outpicref->linesize[plane];
468 outpicref->pts = insamples->pts +
469 av_rescale_q(s->consumed,
470 (AVRational){ 1, inlink->sample_rate },
472 ret = push_frame(outlink);
480 static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
482 AVFilterContext *ctx = inlink->dst;
483 ShowSpectrumContext *s = ctx->priv;
484 int ret = 0, left_samples = insamples->nb_samples;
487 while (left_samples) {
488 int ret = plot_spectrum_column(inlink, insamples, left_samples);
495 av_frame_free(&insamples);
499 static const AVFilterPad showspectrum_inputs[] = {
502 .type = AVMEDIA_TYPE_AUDIO,
503 .filter_frame = filter_frame,
508 static const AVFilterPad showspectrum_outputs[] = {
511 .type = AVMEDIA_TYPE_VIDEO,
512 .config_props = config_output,
513 .request_frame = request_frame,
518 AVFilter ff_avf_showspectrum = {
519 .name = "showspectrum",
520 .description = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output."),
522 .query_formats = query_formats,
523 .priv_size = sizeof(ShowSpectrumContext),
524 .inputs = showspectrum_inputs,
525 .outputs = showspectrum_outputs,
526 .priv_class = &showspectrum_class,