]> git.sesse.net Git - ffmpeg/blob - libavfilter/avf_showspectrum.c
Merge commit '1fc94724f1fd52944bb5ae571475c621da4b77a0'
[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  *
5  * This file is part of FFmpeg.
6  *
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.
11  *
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.
16  *
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
20  */
21
22 /**
23  * @file
24  * audio to spectrum (video) transmedia filter, based on ffplay rdft showmode
25  * (by Michael Niedermayer) and lavfi/avf_showwaves (by Stefano Sabatini).
26  */
27
28 #include <math.h>
29
30 #include "libavcodec/avfft.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/channel_layout.h"
33 #include "libavutil/opt.h"
34 #include "avfilter.h"
35 #include "internal.h"
36
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 };
41 enum SlideMode    { REPLACE, SCROLL, FULLFRAME, NB_SLIDES };
42
43 typedef struct {
44     const AVClass *class;
45     int w, h;
46     AVFrame *outpicref;
47     int nb_display_channels;
48     int channel_height;
49     int sliding;                ///< 1 if sliding mode, 0 otherwise
50     int mode;                   ///< channel display mode
51     int color_mode;             ///< display color scheme
52     int 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     float *window_func_lut;     ///< Window function LUT
59     int win_func;
60     float *combine_buffer;      ///< color combining buffer (3 * h items)
61 } ShowSpectrumContext;
62
63 #define OFFSET(x) offsetof(ShowSpectrumContext, x)
64 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
65
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, NB_SLIDES, FLAGS, "slide" },
70         { "replace", "replace old columns with new", 0, AV_OPT_TYPE_CONST, {.i64=REPLACE}, 0, 0, FLAGS, "slide" },
71         { "scroll", "scroll from right to left", 0, AV_OPT_TYPE_CONST, {.i64=SCROLL}, 0, 0, FLAGS, "slide" },
72         { "fullframe", "return full frames", 0, AV_OPT_TYPE_CONST, {.i64=FULLFRAME}, 0, 0, FLAGS, "slide" },
73     { "mode", "set channel display mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=COMBINED}, COMBINED, NB_MODES-1, FLAGS, "mode" },
74         { "combined", "combined mode", 0, AV_OPT_TYPE_CONST, {.i64=COMBINED}, 0, 0, FLAGS, "mode" },
75         { "separate", "separate mode", 0, AV_OPT_TYPE_CONST, {.i64=SEPARATE}, 0, 0, FLAGS, "mode" },
76     { "color", "set channel coloring", OFFSET(color_mode), AV_OPT_TYPE_INT, {.i64=CHANNEL}, CHANNEL, NB_CLMODES-1, FLAGS, "color" },
77         { "channel",   "separate color for each channel", 0, AV_OPT_TYPE_CONST, {.i64=CHANNEL},   0, 0, FLAGS, "color" },
78         { "intensity", "intensity based coloring",        0, AV_OPT_TYPE_CONST, {.i64=INTENSITY}, 0, 0, FLAGS, "color" },
79     { "scale", "set display scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64=SQRT}, LINEAR, NB_SCALES-1, FLAGS, "scale" },
80         { "sqrt", "square root", 0, AV_OPT_TYPE_CONST, {.i64=SQRT},   0, 0, FLAGS, "scale" },
81         { "cbrt", "cubic root",  0, AV_OPT_TYPE_CONST, {.i64=CBRT},   0, 0, FLAGS, "scale" },
82         { "log",  "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG},    0, 0, FLAGS, "scale" },
83         { "lin",  "linear",      0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, FLAGS, "scale" },
84     { "saturation", "color saturation multiplier", OFFSET(saturation), AV_OPT_TYPE_FLOAT, {.dbl = 1}, -10, 10, FLAGS },
85     { "win_func", "set window function", OFFSET(win_func), AV_OPT_TYPE_INT, {.i64 = WFUNC_HANN}, 0, NB_WFUNC-1, FLAGS, "win_func" },
86         { "hann",     "Hann window",     0, AV_OPT_TYPE_CONST, {.i64 = WFUNC_HANN},     0, 0, FLAGS, "win_func" },
87         { "hamming",  "Hamming window",  0, AV_OPT_TYPE_CONST, {.i64 = WFUNC_HAMMING},  0, 0, FLAGS, "win_func" },
88         { "blackman", "Blackman window", 0, AV_OPT_TYPE_CONST, {.i64 = WFUNC_BLACKMAN}, 0, 0, FLAGS, "win_func" },
89     { NULL }
90 };
91
92 AVFILTER_DEFINE_CLASS(showspectrum);
93
94 static const struct {
95     float a, y, u, v;
96 } intensity_color_table[] = {
97     {    0,                  0,                  0,                   0 },
98     { 0.13, .03587126228984074,  .1573300977624594, -.02548747583751842 },
99     { 0.30, .18572281794568020,  .1772436246393981,  .17475554840414750 },
100     { 0.60, .28184980583656130, -.1593064119945782,  .47132074554608920 },
101     { 0.73, .65830621175547810, -.3716070802232764,  .24352759331252930 },
102     { 0.78, .76318535758242900, -.4307467689263783,  .16866496622310430 },
103     { 0.91, .95336363636363640, -.2045454545454546,  .03313636363636363 },
104     {    1,                  1,                  0,                   0 }
105 };
106
107 static av_cold void uninit(AVFilterContext *ctx)
108 {
109     ShowSpectrumContext *s = ctx->priv;
110     int i;
111
112     av_freep(&s->combine_buffer);
113     av_rdft_end(s->rdft);
114     for (i = 0; i < s->nb_display_channels; i++)
115         av_freep(&s->rdft_data[i]);
116     av_freep(&s->rdft_data);
117     av_freep(&s->window_func_lut);
118     av_frame_free(&s->outpicref);
119 }
120
121 static int query_formats(AVFilterContext *ctx)
122 {
123     AVFilterFormats *formats = NULL;
124     AVFilterChannelLayouts *layouts = NULL;
125     AVFilterLink *inlink = ctx->inputs[0];
126     AVFilterLink *outlink = ctx->outputs[0];
127     static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE };
128     static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_NONE };
129     int ret;
130
131     /* set input audio formats */
132     formats = ff_make_format_list(sample_fmts);
133     if ((ret = ff_formats_ref(formats, &inlink->out_formats)) < 0)
134         return ret;
135
136     layouts = ff_all_channel_layouts();
137     if ((ret = ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts)) < 0)
138         return ret;
139
140     formats = ff_all_samplerates();
141     if ((ret = ff_formats_ref(formats, &inlink->out_samplerates)) < 0)
142         return ret;
143
144     /* set output video format */
145     formats = ff_make_format_list(pix_fmts);
146     if ((ret = ff_formats_ref(formats, &outlink->in_formats)) < 0)
147         return ret;
148
149     return 0;
150 }
151
152 static int config_output(AVFilterLink *outlink)
153 {
154     AVFilterContext *ctx = outlink->src;
155     AVFilterLink *inlink = ctx->inputs[0];
156     ShowSpectrumContext *s = ctx->priv;
157     int i, rdft_bits, win_size, h;
158
159     outlink->w = s->w;
160     outlink->h = s->h;
161
162     h = (s->mode == COMBINED) ? outlink->h : outlink->h / inlink->channels;
163     s->channel_height = h;
164
165     /* RDFT window size (precision) according to the requested output frame height */
166     for (rdft_bits = 1; 1 << rdft_bits < 2 * h; rdft_bits++);
167     win_size = 1 << rdft_bits;
168
169     /* (re-)configuration if the video output changed (or first init) */
170     if (rdft_bits != s->rdft_bits) {
171         AVFrame *outpicref;
172
173         av_rdft_end(s->rdft);
174         s->rdft = av_rdft_init(rdft_bits, DFT_R2C);
175         if (!s->rdft) {
176             av_log(ctx, AV_LOG_ERROR, "Unable to create RDFT context. "
177                    "The window size might be too high.\n");
178             return AVERROR(EINVAL);
179         }
180         s->rdft_bits = rdft_bits;
181
182         /* RDFT buffers: x2 for each (display) channel buffer.
183          * Note: we use free and malloc instead of a realloc-like function to
184          * make sure the buffer is aligned in memory for the FFT functions. */
185         for (i = 0; i < s->nb_display_channels; i++)
186             av_freep(&s->rdft_data[i]);
187         av_freep(&s->rdft_data);
188         s->nb_display_channels = inlink->channels;
189
190         s->rdft_data = av_calloc(s->nb_display_channels, sizeof(*s->rdft_data));
191         if (!s->rdft_data)
192             return AVERROR(ENOMEM);
193         for (i = 0; i < s->nb_display_channels; i++) {
194             s->rdft_data[i] = av_calloc(win_size, sizeof(**s->rdft_data));
195             if (!s->rdft_data[i])
196                 return AVERROR(ENOMEM);
197         }
198
199         /* pre-calc windowing function */
200         s->window_func_lut =
201             av_realloc_f(s->window_func_lut, win_size,
202                          sizeof(*s->window_func_lut));
203         if (!s->window_func_lut)
204             return AVERROR(ENOMEM);
205         switch (s->win_func) {
206         case WFUNC_NONE:
207             for (i = 0; i < win_size; i++)
208                 s->window_func_lut[i] = 1.;
209             break;
210         case WFUNC_HANN:
211             for (i = 0; i < win_size; i++)
212                 s->window_func_lut[i] = .5f * (1 - cos(2*M_PI*i / (win_size-1)));
213             break;
214         case WFUNC_HAMMING:
215             for (i = 0; i < win_size; i++)
216                 s->window_func_lut[i] = .54f - .46f * cos(2*M_PI*i / (win_size-1));
217             break;
218         case WFUNC_BLACKMAN: {
219             for (i = 0; i < win_size; i++)
220                 s->window_func_lut[i] = .42f - .5f*cos(2*M_PI*i / (win_size-1)) + .08f*cos(4*M_PI*i / (win_size-1));
221             break;
222         }
223         default:
224             av_assert0(0);
225         }
226
227         /* prepare the initial picref buffer (black frame) */
228         av_frame_free(&s->outpicref);
229         s->outpicref = outpicref =
230             ff_get_video_buffer(outlink, outlink->w, outlink->h);
231         if (!outpicref)
232             return AVERROR(ENOMEM);
233         outlink->sample_aspect_ratio = (AVRational){1,1};
234         for (i = 0; i < outlink->h; i++) {
235             memset(outpicref->data[0] + i * outpicref->linesize[0],   0, outlink->w);
236             memset(outpicref->data[1] + i * outpicref->linesize[1], 128, outlink->w);
237             memset(outpicref->data[2] + i * outpicref->linesize[2], 128, outlink->w);
238         }
239     }
240
241     if (s->xpos >= outlink->w)
242         s->xpos = 0;
243
244     outlink->frame_rate = av_make_q(inlink->sample_rate, win_size);
245     if (s->sliding == FULLFRAME)
246         outlink->frame_rate.den *= outlink->w;
247
248     inlink->min_samples = inlink->max_samples = inlink->partial_buf_size =
249         win_size;
250
251     s->combine_buffer =
252         av_realloc_f(s->combine_buffer, outlink->h * 3,
253                      sizeof(*s->combine_buffer));
254
255     av_log(ctx, AV_LOG_VERBOSE, "s:%dx%d RDFT window size:%d\n",
256            s->w, s->h, win_size);
257     return 0;
258 }
259
260 static int request_frame(AVFilterLink *outlink)
261 {
262     ShowSpectrumContext *s = outlink->src->priv;
263     AVFilterLink *inlink = outlink->src->inputs[0];
264     unsigned i;
265     int ret;
266
267     ret = ff_request_frame(inlink);
268     if (ret == AVERROR_EOF && s->sliding == FULLFRAME && s->xpos > 0 &&
269         s->outpicref) {
270         for (i = 0; i < outlink->h; i++) {
271             memset(s->outpicref->data[0] + i * s->outpicref->linesize[0] + s->xpos,   0, outlink->w - s->xpos);
272             memset(s->outpicref->data[1] + i * s->outpicref->linesize[1] + s->xpos, 128, outlink->w - s->xpos);
273             memset(s->outpicref->data[2] + i * s->outpicref->linesize[2] + s->xpos, 128, outlink->w - s->xpos);
274         }
275         ret = ff_filter_frame(outlink, s->outpicref);
276         s->outpicref = NULL;
277     }
278
279     return ret;
280 }
281
282 static int plot_spectrum_column(AVFilterLink *inlink, AVFrame *insamples)
283 {
284     int ret;
285     AVFilterContext *ctx = inlink->dst;
286     AVFilterLink *outlink = ctx->outputs[0];
287     ShowSpectrumContext *s = ctx->priv;
288     AVFrame *outpicref = s->outpicref;
289
290     /* nb_freq contains the power of two superior or equal to the output image
291      * height (or half the RDFT window size) */
292     const int nb_freq = 1 << (s->rdft_bits - 1);
293     const int win_size = nb_freq << 1;
294     const double w = 1. / (sqrt(nb_freq) * 32768.);
295     int h = s->channel_height;
296
297     int ch, plane, n, y;
298
299     av_assert0(insamples->nb_samples == win_size);
300
301     /* fill RDFT input with the number of samples available */
302     for (ch = 0; ch < s->nb_display_channels; ch++) {
303         const int16_t *p = (int16_t *)insamples->extended_data[ch];
304
305         for (n = 0; n < win_size; n++)
306             s->rdft_data[ch][n] = p[n] * s->window_func_lut[n];
307     }
308
309     /* run RDFT on each samples set */
310     for (ch = 0; ch < s->nb_display_channels; ch++)
311         av_rdft_calc(s->rdft, s->rdft_data[ch]);
312
313     /* fill a new spectrum column */
314 #define RE(y, ch) s->rdft_data[ch][2 * (y) + 0]
315 #define IM(y, ch) s->rdft_data[ch][2 * (y) + 1]
316 #define MAGNITUDE(y, ch) hypot(RE(y, ch), IM(y, ch))
317
318     /* initialize buffer for combining to black */
319     for (y = 0; y < outlink->h; y++) {
320         s->combine_buffer[3 * y    ] = 0;
321         s->combine_buffer[3 * y + 1] = 127.5;
322         s->combine_buffer[3 * y + 2] = 127.5;
323     }
324
325     for (ch = 0; ch < s->nb_display_channels; ch++) {
326         float yf, uf, vf;
327
328         /* decide color range */
329         switch (s->mode) {
330         case COMBINED:
331             // reduce range by channel count
332             yf = 256.0f / s->nb_display_channels;
333             switch (s->color_mode) {
334             case INTENSITY:
335                 uf = yf;
336                 vf = yf;
337                 break;
338             case CHANNEL:
339                 /* adjust saturation for mixed UV coloring */
340                 /* this factor is correct for infinite channels, an approximation otherwise */
341                 uf = yf * M_PI;
342                 vf = yf * M_PI;
343                 break;
344             default:
345                 av_assert0(0);
346             }
347             break;
348         case SEPARATE:
349             // full range
350             yf = 256.0f;
351             uf = 256.0f;
352             vf = 256.0f;
353             break;
354         default:
355             av_assert0(0);
356         }
357
358         if (s->color_mode == CHANNEL) {
359             if (s->nb_display_channels > 1) {
360                 uf *= 0.5 * sin((2 * M_PI * ch) / s->nb_display_channels);
361                 vf *= 0.5 * cos((2 * M_PI * ch) / s->nb_display_channels);
362             } else {
363                 uf = 0.0f;
364                 vf = 0.0f;
365             }
366         }
367         uf *= s->saturation;
368         vf *= s->saturation;
369
370         /* draw the channel */
371         for (y = 0; y < h; y++) {
372             int row = (s->mode == COMBINED) ? y : ch * h + y;
373             float *out = &s->combine_buffer[3 * row];
374
375             /* get magnitude */
376             float a = w * MAGNITUDE(y, ch);
377
378             /* apply scale */
379             switch (s->scale) {
380             case LINEAR:
381                 break;
382             case SQRT:
383                 a = sqrt(a);
384                 break;
385             case CBRT:
386                 a = cbrt(a);
387                 break;
388             case LOG:
389                 a = 1 + log10(FFMAX(FFMIN(1, a), 1e-6)) / 6; // zero = -120dBFS
390                 break;
391             default:
392                 av_assert0(0);
393             }
394
395             if (s->color_mode == INTENSITY) {
396                 float y, u, v;
397                 int i;
398
399                 for (i = 1; i < sizeof(intensity_color_table) / sizeof(*intensity_color_table) - 1; i++)
400                     if (intensity_color_table[i].a >= a)
401                         break;
402                 // i now is the first item >= the color
403                 // now we know to interpolate between item i - 1 and i
404                 if (a <= intensity_color_table[i - 1].a) {
405                     y = intensity_color_table[i - 1].y;
406                     u = intensity_color_table[i - 1].u;
407                     v = intensity_color_table[i - 1].v;
408                 } else if (a >= intensity_color_table[i].a) {
409                     y = intensity_color_table[i].y;
410                     u = intensity_color_table[i].u;
411                     v = intensity_color_table[i].v;
412                 } else {
413                     float start = intensity_color_table[i - 1].a;
414                     float end = intensity_color_table[i].a;
415                     float lerpfrac = (a - start) / (end - start);
416                     y = intensity_color_table[i - 1].y * (1.0f - lerpfrac)
417                       + intensity_color_table[i].y * lerpfrac;
418                     u = intensity_color_table[i - 1].u * (1.0f - lerpfrac)
419                       + intensity_color_table[i].u * lerpfrac;
420                     v = intensity_color_table[i - 1].v * (1.0f - lerpfrac)
421                       + intensity_color_table[i].v * lerpfrac;
422                 }
423
424                 out[0] += y * yf;
425                 out[1] += u * uf;
426                 out[2] += v * vf;
427             } else {
428                 out[0] += a * yf;
429                 out[1] += a * uf;
430                 out[2] += a * vf;
431             }
432         }
433     }
434
435     /* copy to output */
436     if (s->sliding == SCROLL) {
437         for (plane = 0; plane < 3; plane++) {
438             for (y = 0; y < outlink->h; y++) {
439                 uint8_t *p = outpicref->data[plane] +
440                              y * outpicref->linesize[plane];
441                 memmove(p, p + 1, outlink->w - 1);
442             }
443         }
444         s->xpos = outlink->w - 1;
445     }
446     for (plane = 0; plane < 3; plane++) {
447         uint8_t *p = outpicref->data[plane] +
448                      (outlink->h - 1) * outpicref->linesize[plane] +
449                      s->xpos;
450         for (y = 0; y < outlink->h; y++) {
451             *p = rint(FFMAX(0, FFMIN(s->combine_buffer[3 * y + plane], 255)));
452             p -= outpicref->linesize[plane];
453         }
454     }
455
456     if (s->sliding != FULLFRAME || s->xpos == 0)
457         outpicref->pts = insamples->pts;
458
459     s->xpos++;
460     if (s->xpos >= outlink->w)
461         s->xpos = 0;
462     if (s->sliding != FULLFRAME || s->xpos == 0) {
463         ret = ff_filter_frame(outlink, av_frame_clone(s->outpicref));
464         if (ret < 0)
465             return ret;
466     }
467
468     return win_size;
469 }
470
471 static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
472 {
473     AVFilterContext *ctx = inlink->dst;
474     ShowSpectrumContext *s = ctx->priv;
475     unsigned win_size = 1 << s->rdft_bits;
476     int ret = 0;
477
478     av_assert0(insamples->nb_samples <= win_size);
479     if (insamples->nb_samples == win_size)
480         ret = plot_spectrum_column(inlink, insamples);
481
482     av_frame_free(&insamples);
483     return ret;
484 }
485
486 static const AVFilterPad showspectrum_inputs[] = {
487     {
488         .name         = "default",
489         .type         = AVMEDIA_TYPE_AUDIO,
490         .filter_frame = filter_frame,
491     },
492     { NULL }
493 };
494
495 static const AVFilterPad showspectrum_outputs[] = {
496     {
497         .name          = "default",
498         .type          = AVMEDIA_TYPE_VIDEO,
499         .config_props  = config_output,
500         .request_frame = request_frame,
501     },
502     { NULL }
503 };
504
505 AVFilter ff_avf_showspectrum = {
506     .name          = "showspectrum",
507     .description   = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output."),
508     .uninit        = uninit,
509     .query_formats = query_formats,
510     .priv_size     = sizeof(ShowSpectrumContext),
511     .inputs        = showspectrum_inputs,
512     .outputs       = showspectrum_outputs,
513     .priv_class    = &showspectrum_class,
514 };