]> git.sesse.net Git - ffmpeg/blob - libavfilter/avf_showspectrum.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavfilter / avf_showspectrum.c
1 /*
2  * Copyright (c) 2012 Clément Bœsch
3  *
4  * This file is part of FFmpeg.
5  *
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.
10  *
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.
15  *
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
19  */
20
21 /**
22  * @file
23  * audio to spectrum (video) transmedia filter, based on ffplay rdft showmode
24  * (by Michael Niedermayer) and lavfi/avf_showwaves (by Stefano Sabatini).
25  */
26
27 #include <math.h>
28
29 #include "libavcodec/avfft.h"
30 #include "libavutil/audioconvert.h"
31 #include "libavutil/opt.h"
32 #include "avfilter.h"
33 #include "internal.h"
34
35 typedef struct {
36     const AVClass *class;
37     int w, h;
38     AVFilterBufferRef *outpicref;
39     int req_fullfilled;
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;
48
49 #define OFFSET(x) offsetof(ShowSpectrumContext, x)
50 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
51
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 },
55     { NULL },
56 };
57
58 AVFILTER_DEFINE_CLASS(showspectrum);
59
60 static av_cold int init(AVFilterContext *ctx, const char *args)
61 {
62     ShowSpectrumContext *showspectrum = ctx->priv;
63     int err;
64
65     showspectrum->class = &showspectrum_class;
66     av_opt_set_defaults(showspectrum);
67
68     if ((err = av_set_options_string(showspectrum, args, "=", ":")) < 0)
69         return err;
70
71     return 0;
72 }
73
74 static av_cold void uninit(AVFilterContext *ctx)
75 {
76     ShowSpectrumContext *showspectrum = ctx->priv;
77
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);
82 }
83
84 static int query_formats(AVFilterContext *ctx)
85 {
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 AVPixelFormat pix_fmts[] = { AV_PIX_FMT_RGB24, -1 };
92
93     /* set input audio formats */
94     formats = ff_make_format_list(sample_fmts);
95     if (!formats)
96         return AVERROR(ENOMEM);
97     ff_formats_ref(formats, &inlink->out_formats);
98
99     layouts = ff_all_channel_layouts();
100     if (!layouts)
101         return AVERROR(ENOMEM);
102     ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts);
103
104     formats = ff_all_samplerates();
105     if (!formats)
106         return AVERROR(ENOMEM);
107     ff_formats_ref(formats, &inlink->out_samplerates);
108
109     /* set output video format */
110     formats = ff_make_format_list(pix_fmts);
111     if (!formats)
112         return AVERROR(ENOMEM);
113     ff_formats_ref(formats, &outlink->in_formats);
114
115     return 0;
116 }
117
118 static int config_output(AVFilterLink *outlink)
119 {
120     AVFilterContext *ctx = outlink->src;
121     ShowSpectrumContext *showspectrum = ctx->priv;
122     int i, rdft_bits, win_size;
123
124     outlink->w = showspectrum->w;
125     outlink->h = showspectrum->h;
126
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;
130
131     /* (re-)configuration if the video output changed (or first init) */
132     if (rdft_bits != showspectrum->rdft_bits) {
133         AVFilterBufferRef *outpicref;
134
135         av_rdft_end(showspectrum->rdft);
136         showspectrum->rdft = av_rdft_init(rdft_bits, DFT_R2C);
137         showspectrum->rdft_bits = rdft_bits;
138
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;
146
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)));
155
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);
161         if (!outpicref)
162             return AVERROR(ENOMEM);
163         outlink->sample_aspect_ratio = (AVRational){1,1};
164         memset(outpicref->data[0], 0, outlink->h * outpicref->linesize[0]);
165     }
166
167     if (showspectrum->xpos >= outlink->w)
168         showspectrum->xpos = 0;
169
170     av_log(ctx, AV_LOG_VERBOSE, "s:%dx%d RDFT window size:%d\n",
171            showspectrum->w, showspectrum->h, win_size);
172     return 0;
173 }
174
175 inline static void push_frame(AVFilterLink *outlink)
176 {
177     ShowSpectrumContext *showspectrum = outlink->src->priv;
178
179     showspectrum->xpos++;
180     if (showspectrum->xpos >= outlink->w)
181         showspectrum->xpos = 0;
182     showspectrum->filled = 0;
183     showspectrum->req_fullfilled = 1;
184
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);
188 }
189
190 static int request_frame(AVFilterLink *outlink)
191 {
192     ShowSpectrumContext *showspectrum = outlink->src->priv;
193     AVFilterLink *inlink = outlink->src->inputs[0];
194     int ret;
195
196     showspectrum->req_fullfilled = 0;
197     do {
198         ret = ff_request_frame(inlink);
199     } while (!showspectrum->req_fullfilled && ret >= 0);
200
201     if (ret == AVERROR_EOF && showspectrum->outpicref)
202         push_frame(outlink);
203     return ret;
204 }
205
206 static int plot_spectrum_column(AVFilterLink *inlink, AVFilterBufferRef *insamples, int nb_samples)
207 {
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);
213
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;
218
219     int ch, n, y;
220     FFTSample *data[2];
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);
224
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];
228
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];
233     }
234     showspectrum->filled += add_samples;
235
236     /* complete RDFT window size? */
237     if (showspectrum->filled == win_size) {
238
239         /* run RDFT on each samples set */
240         for (ch = 0; ch < nb_display_channels; ch++)
241             av_rdft_calc(showspectrum->rdft, data[ch]);
242
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))
247
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;
254
255             a = FFMIN(a, 255);
256             b = FFMIN(b, 255);
257             outpicref->data[0][pos]   = a;
258             outpicref->data[0][pos+1] = b;
259             outpicref->data[0][pos+2] = (a + b) / 2;
260         }
261         outpicref->pts = insamples->pts +
262             av_rescale_q(showspectrum->consumed,
263                          (AVRational){ 1, inlink->sample_rate },
264                          outlink->time_base);
265         push_frame(outlink);
266     }
267
268     return add_samples;
269 }
270
271 static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
272 {
273     AVFilterContext *ctx = inlink->dst;
274     ShowSpectrumContext *showspectrum = ctx->priv;
275     int left_samples = insamples->audio->nb_samples;
276
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;
282     }
283
284     avfilter_unref_buffer(insamples);
285     return 0;
286 }
287
288 AVFilter avfilter_avf_showspectrum = {
289     .name           = "showspectrum",
290     .description    = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output."),
291     .init           = init,
292     .uninit         = uninit,
293     .query_formats  = query_formats,
294     .priv_size      = sizeof(ShowSpectrumContext),
295
296     .inputs  = (const AVFilterPad[]) {
297         {
298             .name           = "default",
299             .type           = AVMEDIA_TYPE_AUDIO,
300             .filter_samples = filter_samples,
301             .min_perms      = AV_PERM_READ,
302         },
303         { .name = NULL }
304     },
305
306     .outputs = (const AVFilterPad[]) {
307         {
308             .name           = "default",
309             .type           = AVMEDIA_TYPE_VIDEO,
310             .config_props   = config_output,
311             .request_frame  = request_frame,
312         },
313         { .name = NULL }
314     },
315
316     .priv_class = &showspectrum_class,
317 };