2 * Copyright (c) 2012 Clément Bœsch
4 * This file is part of FFmpeg.
6 * FFmpeg is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * FFmpeg is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with FFmpeg; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 * audio to spectrum (video) transmedia filter, based on ffplay rdft showmode
24 * (by Michael Niedermayer) and lavfi/avf_showwaves (by Stefano Sabatini).
29 #include "libavcodec/avfft.h"
30 #include "libavutil/audioconvert.h"
31 #include "libavutil/opt.h"
38 AVFilterBufferRef *outpicref;
40 int xpos; ///< x position (current column)
41 RDFTContext *rdft; ///< Real Discrete Fourier Transform context
42 int rdft_bits; ///< number of bits (RDFT window size = 1<<rdft_bits)
43 FFTSample *rdft_data; ///< bins holder for each (displayed) channels
44 int filled; ///< number of samples (per channel) filled in current rdft_buffer
45 int consumed; ///< number of samples (per channel) consumed from the input frame
46 float *window_func_lut; ///< Window function LUT
47 } ShowSpectrumContext;
49 #define OFFSET(x) offsetof(ShowSpectrumContext, x)
50 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
52 static const AVOption showspectrum_options[] = {
53 { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x480"}, 0, 0, FLAGS },
54 { "s", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x480"}, 0, 0, FLAGS },
58 AVFILTER_DEFINE_CLASS(showspectrum);
60 static av_cold int init(AVFilterContext *ctx, const char *args)
62 ShowSpectrumContext *showspectrum = ctx->priv;
65 showspectrum->class = &showspectrum_class;
66 av_opt_set_defaults(showspectrum);
68 if ((err = av_set_options_string(showspectrum, args, "=", ":")) < 0)
74 static av_cold void uninit(AVFilterContext *ctx)
76 ShowSpectrumContext *showspectrum = ctx->priv;
78 av_rdft_end(showspectrum->rdft);
79 av_freep(&showspectrum->rdft_data);
80 av_freep(&showspectrum->window_func_lut);
81 avfilter_unref_bufferp(&showspectrum->outpicref);
84 static int query_formats(AVFilterContext *ctx)
86 AVFilterFormats *formats = NULL;
87 AVFilterChannelLayouts *layouts = NULL;
88 AVFilterLink *inlink = ctx->inputs[0];
89 AVFilterLink *outlink = ctx->outputs[0];
90 static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16P, -1 };
91 static const enum PixelFormat pix_fmts[] = { PIX_FMT_RGB24, -1 };
93 /* set input audio formats */
94 formats = ff_make_format_list(sample_fmts);
96 return AVERROR(ENOMEM);
97 ff_formats_ref(formats, &inlink->out_formats);
99 layouts = ff_all_channel_layouts();
101 return AVERROR(ENOMEM);
102 ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts);
104 formats = ff_all_samplerates();
106 return AVERROR(ENOMEM);
107 ff_formats_ref(formats, &inlink->out_samplerates);
109 /* set output video format */
110 formats = ff_make_format_list(pix_fmts);
112 return AVERROR(ENOMEM);
113 ff_formats_ref(formats, &outlink->in_formats);
118 static int config_output(AVFilterLink *outlink)
120 AVFilterContext *ctx = outlink->src;
121 ShowSpectrumContext *showspectrum = ctx->priv;
122 int i, rdft_bits, win_size;
124 outlink->w = showspectrum->w;
125 outlink->h = showspectrum->h;
127 /* RDFT window size (precision) according to the requested output frame height */
128 for (rdft_bits = 1; 1<<rdft_bits < 2*outlink->h; rdft_bits++);
129 win_size = 1 << rdft_bits;
131 /* (re-)configuration if the video output changed (or first init) */
132 if (rdft_bits != showspectrum->rdft_bits) {
133 AVFilterBufferRef *outpicref;
135 av_rdft_end(showspectrum->rdft);
136 showspectrum->rdft = av_rdft_init(rdft_bits, DFT_R2C);
137 showspectrum->rdft_bits = rdft_bits;
139 /* RDFT buffers: x2 for each (display) channel buffer */
140 showspectrum->rdft_data =
141 av_realloc_f(showspectrum->rdft_data, 2 * win_size,
142 sizeof(*showspectrum->rdft_data));
143 if (!showspectrum->rdft_data)
144 return AVERROR(ENOMEM);
145 showspectrum->filled = 0;
147 /* pre-calc windowing function (hann here) */
148 showspectrum->window_func_lut =
149 av_realloc_f(showspectrum->window_func_lut, win_size,
150 sizeof(*showspectrum->window_func_lut));
151 if (!showspectrum->window_func_lut)
152 return AVERROR(ENOMEM);
153 for (i = 0; i < win_size; i++)
154 showspectrum->window_func_lut[i] = .5f * (1 - cos(2*M_PI*i / (win_size-1)));
156 /* prepare the initial picref buffer (black frame) */
157 avfilter_unref_bufferp(&showspectrum->outpicref);
158 showspectrum->outpicref = outpicref =
159 ff_get_video_buffer(outlink, AV_PERM_WRITE|AV_PERM_PRESERVE|AV_PERM_REUSE2,
160 outlink->w, outlink->h);
162 return AVERROR(ENOMEM);
163 outlink->sample_aspect_ratio = (AVRational){1,1};
164 memset(outpicref->data[0], 0, outlink->h * outpicref->linesize[0]);
167 if (showspectrum->xpos >= outlink->w)
168 showspectrum->xpos = 0;
170 av_log(ctx, AV_LOG_VERBOSE, "s:%dx%d RDFT window size:%d\n",
171 showspectrum->w, showspectrum->h, win_size);
175 inline static void push_frame(AVFilterLink *outlink)
177 ShowSpectrumContext *showspectrum = outlink->src->priv;
179 showspectrum->xpos++;
180 if (showspectrum->xpos >= outlink->w)
181 showspectrum->xpos = 0;
182 showspectrum->filled = 0;
183 showspectrum->req_fullfilled = 1;
185 ff_start_frame(outlink, avfilter_ref_buffer(showspectrum->outpicref, ~AV_PERM_WRITE));
186 ff_draw_slice(outlink, 0, outlink->h, 1);
187 ff_end_frame(outlink);
190 static int request_frame(AVFilterLink *outlink)
192 ShowSpectrumContext *showspectrum = outlink->src->priv;
193 AVFilterLink *inlink = outlink->src->inputs[0];
196 showspectrum->req_fullfilled = 0;
198 ret = ff_request_frame(inlink);
199 } while (!showspectrum->req_fullfilled && ret >= 0);
201 if (ret == AVERROR_EOF && showspectrum->outpicref)
206 static int plot_spectrum_column(AVFilterLink *inlink, AVFilterBufferRef *insamples, int nb_samples)
208 AVFilterContext *ctx = inlink->dst;
209 AVFilterLink *outlink = ctx->outputs[0];
210 ShowSpectrumContext *showspectrum = ctx->priv;
211 AVFilterBufferRef *outpicref = showspectrum->outpicref;
212 const int nb_channels = av_get_channel_layout_nb_channels(insamples->audio->channel_layout);
214 /* nb_freq contains the power of two superior or equal to the output image
215 * height (or half the RDFT window size) */
216 const int nb_freq = 1 << (showspectrum->rdft_bits - 1);
217 const int win_size = nb_freq << 1;
221 const int nb_display_channels = FFMIN(nb_channels, 2);
222 const int start = showspectrum->filled;
223 const int add_samples = FFMIN(win_size - start, nb_samples);
225 /* fill RDFT input with the number of samples available */
226 for (ch = 0; ch < nb_display_channels; ch++) {
227 const int16_t *p = (int16_t *)insamples->extended_data[ch];
229 p += showspectrum->consumed;
230 data[ch] = showspectrum->rdft_data + win_size * ch; // select channel buffer
231 for (n = 0; n < add_samples; n++)
232 data[ch][start + n] = p[n] * showspectrum->window_func_lut[start + n];
234 showspectrum->filled += add_samples;
236 /* complete RDFT window size? */
237 if (showspectrum->filled == win_size) {
239 /* run RDFT on each samples set */
240 for (ch = 0; ch < nb_display_channels; ch++)
241 av_rdft_calc(showspectrum->rdft, data[ch]);
243 /* fill a new spectrum column */
244 #define RE(ch) data[ch][2*y + 0]
245 #define IM(ch) data[ch][2*y + 1]
246 #define MAGNITUDE(re, im) sqrt((re)*(re) + (im)*(im))
248 for (y = 0; y < outlink->h; y++) {
249 // FIXME: bin[0] contains first and last bins
250 const int pos = showspectrum->xpos * 3 + (outlink->h - y - 1) * outpicref->linesize[0];
251 const double w = 1. / sqrt(nb_freq);
252 int a = sqrt(w * MAGNITUDE(RE(0), IM(0)));
253 int b = nb_display_channels > 1 ? sqrt(w * MAGNITUDE(RE(1), IM(1))) : a;
257 outpicref->data[0][pos] = a;
258 outpicref->data[0][pos+1] = b;
259 outpicref->data[0][pos+2] = (a + b) / 2;
261 outpicref->pts = insamples->pts +
262 av_rescale_q(showspectrum->consumed,
263 (AVRational){ 1, inlink->sample_rate },
271 static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
273 AVFilterContext *ctx = inlink->dst;
274 ShowSpectrumContext *showspectrum = ctx->priv;
275 int left_samples = insamples->audio->nb_samples;
277 showspectrum->consumed = 0;
278 while (left_samples) {
279 const int added_samples = plot_spectrum_column(inlink, insamples, left_samples);
280 showspectrum->consumed += added_samples;
281 left_samples -= added_samples;
284 avfilter_unref_buffer(insamples);
288 AVFilter avfilter_avf_showspectrum = {
289 .name = "showspectrum",
290 .description = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output."),
293 .query_formats = query_formats,
294 .priv_size = sizeof(ShowSpectrumContext),
296 .inputs = (const AVFilterPad[]) {
299 .type = AVMEDIA_TYPE_AUDIO,
300 .filter_samples = filter_samples,
301 .min_perms = AV_PERM_READ,
306 .outputs = (const AVFilterPad[]) {
309 .type = AVMEDIA_TYPE_VIDEO,
310 .config_props = config_output,
311 .request_frame = request_frame,
316 .priv_class = &showspectrum_class,