2 * Copyright (c) 2012 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 };
46 int nb_display_channels;
48 int sliding; ///< 1 if sliding mode, 0 otherwise
49 enum DisplayMode mode; ///< channel display mode
50 enum ColorMode color_mode; ///< display color scheme
51 enum DisplayScale scale;
52 float saturation; ///< color saturation multiplier
53 int xpos; ///< x position (current column)
54 RDFTContext *rdft; ///< Real Discrete Fourier Transform context
55 int rdft_bits; ///< number of bits (RDFT window size = 1<<rdft_bits)
56 FFTSample **rdft_data; ///< bins holder for each (displayed) channels
57 int filled; ///< number of samples (per channel) filled in current rdft_buffer
58 int consumed; ///< number of samples (per channel) consumed from the input frame
59 float *window_func_lut; ///< Window function LUT
60 float *combine_buffer; ///< color combining buffer (3 * h items)
61 } ShowSpectrumContext;
63 #define OFFSET(x) offsetof(ShowSpectrumContext, x)
64 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
66 static const AVOption showspectrum_options[] = {
67 { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
68 { "s", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
69 { "slide", "set sliding mode", OFFSET(sliding), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, FLAGS },
70 { "mode", "set channel display mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=COMBINED}, COMBINED, NB_MODES-1, FLAGS, "mode" },
71 { "combined", "combined mode", 0, AV_OPT_TYPE_CONST, {.i64=COMBINED}, 0, 0, FLAGS, "mode" },
72 { "separate", "separate mode", 0, AV_OPT_TYPE_CONST, {.i64=SEPARATE}, 0, 0, FLAGS, "mode" },
73 { "color", "set channel coloring", OFFSET(color_mode), AV_OPT_TYPE_INT, {.i64=CHANNEL}, CHANNEL, NB_CLMODES-1, FLAGS, "color" },
74 { "channel", "separate color for each channel", 0, AV_OPT_TYPE_CONST, {.i64=CHANNEL}, 0, 0, FLAGS, "color" },
75 { "intensity", "intensity based coloring", 0, AV_OPT_TYPE_CONST, {.i64=INTENSITY}, 0, 0, FLAGS, "color" },
76 { "scale", "set display scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64=SQRT}, LINEAR, NB_SCALES-1, FLAGS, "scale" },
77 { "sqrt", "square root", 0, AV_OPT_TYPE_CONST, {.i64=SQRT}, 0, 0, FLAGS, "scale" },
78 { "cbrt", "cubic root", 0, AV_OPT_TYPE_CONST, {.i64=CBRT}, 0, 0, FLAGS, "scale" },
79 { "log", "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG}, 0, 0, FLAGS, "scale" },
80 { "lin", "linear", 0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, FLAGS, "scale" },
81 { "saturation", "color saturation multiplier", OFFSET(saturation), AV_OPT_TYPE_FLOAT, {.dbl = 1}, -10, 10, FLAGS },
85 AVFILTER_DEFINE_CLASS(showspectrum);
89 } intensity_color_table[] = {
91 { 0.13, .03587126228984074, .1573300977624594, -.02548747583751842 },
92 { 0.30, .18572281794568020, .1772436246393981, .17475554840414750 },
93 { 0.60, .28184980583656130, -.1593064119945782, .47132074554608920 },
94 { 0.73, .65830621175547810, -.3716070802232764, .24352759331252930 },
95 { 0.78, .76318535758242900, -.4307467689263783, .16866496622310430 },
96 { 0.91, .95336363636363640, -.2045454545454546, .03313636363636363 },
100 static av_cold int init(AVFilterContext *ctx, const char *args)
102 ShowSpectrumContext *showspectrum = ctx->priv;
105 showspectrum->class = &showspectrum_class;
106 av_opt_set_defaults(showspectrum);
108 if ((err = av_set_options_string(showspectrum, args, "=", ":")) < 0)
114 static av_cold void uninit(AVFilterContext *ctx)
116 ShowSpectrumContext *showspectrum = ctx->priv;
119 av_freep(&showspectrum->combine_buffer);
120 av_rdft_end(showspectrum->rdft);
121 for (i = 0; i < showspectrum->nb_display_channels; i++)
122 av_freep(&showspectrum->rdft_data[i]);
123 av_freep(&showspectrum->rdft_data);
124 av_freep(&showspectrum->window_func_lut);
125 av_frame_free(&showspectrum->outpicref);
128 static int query_formats(AVFilterContext *ctx)
130 AVFilterFormats *formats = NULL;
131 AVFilterChannelLayouts *layouts = NULL;
132 AVFilterLink *inlink = ctx->inputs[0];
133 AVFilterLink *outlink = ctx->outputs[0];
134 static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE };
135 static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_NONE };
137 /* set input audio formats */
138 formats = ff_make_format_list(sample_fmts);
140 return AVERROR(ENOMEM);
141 ff_formats_ref(formats, &inlink->out_formats);
143 layouts = ff_all_channel_layouts();
145 return AVERROR(ENOMEM);
146 ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts);
148 formats = ff_all_samplerates();
150 return AVERROR(ENOMEM);
151 ff_formats_ref(formats, &inlink->out_samplerates);
153 /* set output video format */
154 formats = ff_make_format_list(pix_fmts);
156 return AVERROR(ENOMEM);
157 ff_formats_ref(formats, &outlink->in_formats);
162 static int config_output(AVFilterLink *outlink)
164 AVFilterContext *ctx = outlink->src;
165 AVFilterLink *inlink = ctx->inputs[0];
166 ShowSpectrumContext *showspectrum = ctx->priv;
167 int i, rdft_bits, win_size, h;
169 outlink->w = showspectrum->w;
170 outlink->h = showspectrum->h;
172 h = (showspectrum->mode == COMBINED) ? outlink->h : outlink->h / inlink->channels;
173 showspectrum->channel_height = h;
175 /* RDFT window size (precision) according to the requested output frame height */
176 for (rdft_bits = 1; 1 << rdft_bits < 2 * h; rdft_bits++);
177 win_size = 1 << rdft_bits;
179 /* (re-)configuration if the video output changed (or first init) */
180 if (rdft_bits != showspectrum->rdft_bits) {
181 size_t rdft_size, rdft_listsize;
184 av_rdft_end(showspectrum->rdft);
185 showspectrum->rdft = av_rdft_init(rdft_bits, DFT_R2C);
186 showspectrum->rdft_bits = rdft_bits;
188 /* RDFT buffers: x2 for each (display) channel buffer.
189 * Note: we use free and malloc instead of a realloc-like function to
190 * make sure the buffer is aligned in memory for the FFT functions. */
191 for (i = 0; i < showspectrum->nb_display_channels; i++)
192 av_freep(&showspectrum->rdft_data[i]);
193 av_freep(&showspectrum->rdft_data);
194 showspectrum->nb_display_channels = inlink->channels;
196 if (av_size_mult(sizeof(*showspectrum->rdft_data),
197 showspectrum->nb_display_channels, &rdft_listsize) < 0)
198 return AVERROR(EINVAL);
199 if (av_size_mult(sizeof(**showspectrum->rdft_data),
200 win_size, &rdft_size) < 0)
201 return AVERROR(EINVAL);
202 showspectrum->rdft_data = av_malloc(rdft_listsize);
203 if (!showspectrum->rdft_data)
204 return AVERROR(ENOMEM);
205 for (i = 0; i < showspectrum->nb_display_channels; i++) {
206 showspectrum->rdft_data[i] = av_malloc(rdft_size);
207 if (!showspectrum->rdft_data[i])
208 return AVERROR(ENOMEM);
210 showspectrum->filled = 0;
212 /* pre-calc windowing function (hann here) */
213 showspectrum->window_func_lut =
214 av_realloc_f(showspectrum->window_func_lut, win_size,
215 sizeof(*showspectrum->window_func_lut));
216 if (!showspectrum->window_func_lut)
217 return AVERROR(ENOMEM);
218 for (i = 0; i < win_size; i++)
219 showspectrum->window_func_lut[i] = .5f * (1 - cos(2*M_PI*i / (win_size-1)));
221 /* prepare the initial picref buffer (black frame) */
222 av_frame_free(&showspectrum->outpicref);
223 showspectrum->outpicref = outpicref =
224 ff_get_video_buffer(outlink, outlink->w, outlink->h);
226 return AVERROR(ENOMEM);
227 outlink->sample_aspect_ratio = (AVRational){1,1};
228 memset(outpicref->data[0], 0, outlink->h * outpicref->linesize[0]);
229 memset(outpicref->data[1], 128, outlink->h * outpicref->linesize[1]);
230 memset(outpicref->data[2], 128, outlink->h * outpicref->linesize[2]);
233 if (showspectrum->xpos >= outlink->w)
234 showspectrum->xpos = 0;
236 showspectrum->combine_buffer =
237 av_realloc_f(showspectrum->combine_buffer, outlink->h * 3,
238 sizeof(*showspectrum->combine_buffer));
240 av_log(ctx, AV_LOG_VERBOSE, "s:%dx%d RDFT window size:%d\n",
241 showspectrum->w, showspectrum->h, win_size);
245 inline static int push_frame(AVFilterLink *outlink)
247 ShowSpectrumContext *showspectrum = outlink->src->priv;
249 showspectrum->xpos++;
250 if (showspectrum->xpos >= outlink->w)
251 showspectrum->xpos = 0;
252 showspectrum->filled = 0;
253 showspectrum->req_fullfilled = 1;
255 return ff_filter_frame(outlink, av_frame_clone(showspectrum->outpicref));
258 static int request_frame(AVFilterLink *outlink)
260 ShowSpectrumContext *showspectrum = outlink->src->priv;
261 AVFilterLink *inlink = outlink->src->inputs[0];
264 showspectrum->req_fullfilled = 0;
266 ret = ff_request_frame(inlink);
267 } while (!showspectrum->req_fullfilled && ret >= 0);
269 if (ret == AVERROR_EOF && showspectrum->outpicref)
274 static int plot_spectrum_column(AVFilterLink *inlink, AVFrame *insamples, int nb_samples)
277 AVFilterContext *ctx = inlink->dst;
278 AVFilterLink *outlink = ctx->outputs[0];
279 ShowSpectrumContext *showspectrum = ctx->priv;
280 AVFrame *outpicref = showspectrum->outpicref;
282 /* nb_freq contains the power of two superior or equal to the output image
283 * height (or half the RDFT window size) */
284 const int nb_freq = 1 << (showspectrum->rdft_bits - 1);
285 const int win_size = nb_freq << 1;
286 const double w = 1. / (sqrt(nb_freq) * 32768.);
289 const int start = showspectrum->filled;
290 const int add_samples = FFMIN(win_size - start, nb_samples);
292 /* fill RDFT input with the number of samples available */
293 for (ch = 0; ch < showspectrum->nb_display_channels; ch++) {
294 const int16_t *p = (int16_t *)insamples->extended_data[ch];
296 p += showspectrum->consumed;
297 for (n = 0; n < add_samples; n++)
298 showspectrum->rdft_data[ch][start + n] = p[n] * showspectrum->window_func_lut[start + n];
300 showspectrum->filled += add_samples;
302 /* complete RDFT window size? */
303 if (showspectrum->filled == win_size) {
306 int h = showspectrum->channel_height;
308 /* run RDFT on each samples set */
309 for (ch = 0; ch < showspectrum->nb_display_channels; ch++)
310 av_rdft_calc(showspectrum->rdft, showspectrum->rdft_data[ch]);
312 /* fill a new spectrum column */
313 #define RE(y, ch) showspectrum->rdft_data[ch][2 * y + 0]
314 #define IM(y, ch) showspectrum->rdft_data[ch][2 * y + 1]
315 #define MAGNITUDE(y, ch) hypot(RE(y, ch), IM(y, ch))
317 /* initialize buffer for combining to black */
318 for (y = 0; y < outlink->h; y++) {
319 showspectrum->combine_buffer[3 * y ] = 0;
320 showspectrum->combine_buffer[3 * y + 1] = 127.5;
321 showspectrum->combine_buffer[3 * y + 2] = 127.5;
324 for (ch = 0; ch < showspectrum->nb_display_channels; ch++) {
327 /* decide color range */
328 switch (showspectrum->mode) {
330 // reduce range by channel count
331 yf = 256.0f / showspectrum->nb_display_channels;
332 switch (showspectrum->color_mode) {
338 /* adjust saturation for mixed UV coloring */
339 /* this factor is correct for infinite channels, an approximation otherwise */
357 if (showspectrum->color_mode == CHANNEL) {
358 if (showspectrum->nb_display_channels > 1) {
359 uf *= 0.5 * sin((2 * M_PI * ch) / showspectrum->nb_display_channels);
360 vf *= 0.5 * cos((2 * M_PI * ch) / showspectrum->nb_display_channels);
366 uf *= showspectrum->saturation;
367 vf *= showspectrum->saturation;
369 /* draw the channel */
370 for (y = 0; y < h; y++) {
371 int row = (showspectrum->mode == COMBINED) ? y : ch * h + y;
372 float *out = &showspectrum->combine_buffer[3 * row];
375 float a = w * MAGNITUDE(y, ch);
378 switch (showspectrum->scale) {
388 a = 1 - log(FFMAX(FFMIN(1, a), 1e-6)) / log(1e-6); // zero = -120dBFS
394 if (showspectrum->color_mode == INTENSITY) {
398 for (i = 1; i < sizeof(intensity_color_table) / sizeof(*intensity_color_table) - 1; i++)
399 if (intensity_color_table[i].a >= a)
401 // i now is the first item >= the color
402 // now we know to interpolate between item i - 1 and i
403 if (a <= intensity_color_table[i - 1].a) {
404 y = intensity_color_table[i - 1].y;
405 u = intensity_color_table[i - 1].u;
406 v = intensity_color_table[i - 1].v;
407 } else if (a >= intensity_color_table[i].a) {
408 y = intensity_color_table[i].y;
409 u = intensity_color_table[i].u;
410 v = intensity_color_table[i].v;
412 float start = intensity_color_table[i - 1].a;
413 float end = intensity_color_table[i].a;
414 float lerpfrac = (a - start) / (end - start);
415 y = intensity_color_table[i - 1].y * (1.0f - lerpfrac)
416 + intensity_color_table[i].y * lerpfrac;
417 u = intensity_color_table[i - 1].u * (1.0f - lerpfrac)
418 + intensity_color_table[i].u * lerpfrac;
419 v = intensity_color_table[i - 1].v * (1.0f - lerpfrac)
420 + intensity_color_table[i].v * lerpfrac;
435 if (showspectrum->sliding) {
436 for (plane = 0; plane < 3; plane++) {
437 for (y = 0; y < outlink->h; y++) {
438 uint8_t *p = outpicref->data[plane] +
439 y * outpicref->linesize[plane];
440 memmove(p, p + 1, outlink->w - 1);
443 showspectrum->xpos = outlink->w - 1;
445 for (plane = 0; plane < 3; plane++) {
446 uint8_t *p = outpicref->data[plane] +
447 (outlink->h - 1) * outpicref->linesize[plane] +
449 for (y = 0; y < outlink->h; y++) {
450 *p = rint(FFMAX(0, FFMIN(showspectrum->combine_buffer[3 * y + plane], 255)));
451 p -= outpicref->linesize[plane];
455 outpicref->pts = insamples->pts +
456 av_rescale_q(showspectrum->consumed,
457 (AVRational){ 1, inlink->sample_rate },
459 ret = push_frame(outlink);
467 static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
469 AVFilterContext *ctx = inlink->dst;
470 ShowSpectrumContext *showspectrum = ctx->priv;
471 int ret = 0, left_samples = insamples->nb_samples;
473 showspectrum->consumed = 0;
474 while (left_samples) {
475 int ret = plot_spectrum_column(inlink, insamples, left_samples);
478 showspectrum->consumed += ret;
482 av_frame_free(&insamples);
486 static const AVFilterPad showspectrum_inputs[] = {
489 .type = AVMEDIA_TYPE_AUDIO,
490 .filter_frame = filter_frame,
495 static const AVFilterPad showspectrum_outputs[] = {
498 .type = AVMEDIA_TYPE_VIDEO,
499 .config_props = config_output,
500 .request_frame = request_frame,
505 AVFilter avfilter_avf_showspectrum = {
506 .name = "showspectrum",
507 .description = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output."),
510 .query_formats = query_formats,
511 .priv_size = sizeof(ShowSpectrumContext),
512 .inputs = showspectrum_inputs,
513 .outputs = showspectrum_outputs,
514 .priv_class = &showspectrum_class,