]> git.sesse.net Git - ffmpeg/blob - libavfilter/avf_showspectrum.c
Merge commit '8b830ee9a26d47b138f12a82085cdb372f407f1e'
[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
130     /* set input audio formats */
131     formats = ff_make_format_list(sample_fmts);
132     if (!formats)
133         return AVERROR(ENOMEM);
134     ff_formats_ref(formats, &inlink->out_formats);
135
136     layouts = ff_all_channel_layouts();
137     if (!layouts)
138         return AVERROR(ENOMEM);
139     ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts);
140
141     formats = ff_all_samplerates();
142     if (!formats)
143         return AVERROR(ENOMEM);
144     ff_formats_ref(formats, &inlink->out_samplerates);
145
146     /* set output video format */
147     formats = ff_make_format_list(pix_fmts);
148     if (!formats)
149         return AVERROR(ENOMEM);
150     ff_formats_ref(formats, &outlink->in_formats);
151
152     return 0;
153 }
154
155 static int config_output(AVFilterLink *outlink)
156 {
157     AVFilterContext *ctx = outlink->src;
158     AVFilterLink *inlink = ctx->inputs[0];
159     ShowSpectrumContext *s = ctx->priv;
160     int i, rdft_bits, win_size, h;
161
162     outlink->w = s->w;
163     outlink->h = s->h;
164
165     h = (s->mode == COMBINED) ? outlink->h : outlink->h / inlink->channels;
166     s->channel_height = h;
167
168     /* RDFT window size (precision) according to the requested output frame height */
169     for (rdft_bits = 1; 1 << rdft_bits < 2 * h; rdft_bits++);
170     win_size = 1 << rdft_bits;
171
172     /* (re-)configuration if the video output changed (or first init) */
173     if (rdft_bits != s->rdft_bits) {
174         AVFrame *outpicref;
175
176         av_rdft_end(s->rdft);
177         s->rdft = av_rdft_init(rdft_bits, DFT_R2C);
178         if (!s->rdft) {
179             av_log(ctx, AV_LOG_ERROR, "Unable to create RDFT context. "
180                    "The window size might be too high.\n");
181             return AVERROR(EINVAL);
182         }
183         s->rdft_bits = rdft_bits;
184
185         /* RDFT buffers: x2 for each (display) channel buffer.
186          * Note: we use free and malloc instead of a realloc-like function to
187          * make sure the buffer is aligned in memory for the FFT functions. */
188         for (i = 0; i < s->nb_display_channels; i++)
189             av_freep(&s->rdft_data[i]);
190         av_freep(&s->rdft_data);
191         s->nb_display_channels = inlink->channels;
192
193         s->rdft_data = av_calloc(s->nb_display_channels, sizeof(*s->rdft_data));
194         if (!s->rdft_data)
195             return AVERROR(ENOMEM);
196         for (i = 0; i < s->nb_display_channels; i++) {
197             s->rdft_data[i] = av_calloc(win_size, sizeof(**s->rdft_data));
198             if (!s->rdft_data[i])
199                 return AVERROR(ENOMEM);
200         }
201
202         /* pre-calc windowing function */
203         s->window_func_lut =
204             av_realloc_f(s->window_func_lut, win_size,
205                          sizeof(*s->window_func_lut));
206         if (!s->window_func_lut)
207             return AVERROR(ENOMEM);
208         switch (s->win_func) {
209         case WFUNC_NONE:
210             for (i = 0; i < win_size; i++)
211                 s->window_func_lut[i] = 1.;
212             break;
213         case WFUNC_HANN:
214             for (i = 0; i < win_size; i++)
215                 s->window_func_lut[i] = .5f * (1 - cos(2*M_PI*i / (win_size-1)));
216             break;
217         case WFUNC_HAMMING:
218             for (i = 0; i < win_size; i++)
219                 s->window_func_lut[i] = .54f - .46f * cos(2*M_PI*i / (win_size-1));
220             break;
221         case WFUNC_BLACKMAN: {
222             for (i = 0; i < win_size; i++)
223                 s->window_func_lut[i] = .42f - .5f*cos(2*M_PI*i / (win_size-1)) + .08f*cos(4*M_PI*i / (win_size-1));
224             break;
225         }
226         default:
227             av_assert0(0);
228         }
229
230         /* prepare the initial picref buffer (black frame) */
231         av_frame_free(&s->outpicref);
232         s->outpicref = outpicref =
233             ff_get_video_buffer(outlink, outlink->w, outlink->h);
234         if (!outpicref)
235             return AVERROR(ENOMEM);
236         outlink->sample_aspect_ratio = (AVRational){1,1};
237         for (i = 0; i < outlink->h; i++) {
238             memset(outpicref->data[0] + i * outpicref->linesize[0],   0, outlink->w);
239             memset(outpicref->data[1] + i * outpicref->linesize[1], 128, outlink->w);
240             memset(outpicref->data[2] + i * outpicref->linesize[2], 128, outlink->w);
241         }
242     }
243
244     if (s->xpos >= outlink->w)
245         s->xpos = 0;
246
247     outlink->frame_rate = av_make_q(inlink->sample_rate, win_size);
248     if (s->sliding == FULLFRAME)
249         outlink->frame_rate.den *= outlink->w;
250
251     inlink->min_samples = inlink->max_samples = inlink->partial_buf_size =
252         win_size;
253
254     s->combine_buffer =
255         av_realloc_f(s->combine_buffer, outlink->h * 3,
256                      sizeof(*s->combine_buffer));
257
258     av_log(ctx, AV_LOG_VERBOSE, "s:%dx%d RDFT window size:%d\n",
259            s->w, s->h, win_size);
260     return 0;
261 }
262
263 static int request_frame(AVFilterLink *outlink)
264 {
265     ShowSpectrumContext *s = outlink->src->priv;
266     AVFilterLink *inlink = outlink->src->inputs[0];
267     unsigned i;
268     int ret;
269
270     ret = ff_request_frame(inlink);
271     if (ret == AVERROR_EOF && s->sliding == FULLFRAME && s->xpos > 0 &&
272         s->outpicref) {
273         for (i = 0; i < outlink->h; i++) {
274             memset(s->outpicref->data[0] + i * s->outpicref->linesize[0] + s->xpos,   0, outlink->w - s->xpos);
275             memset(s->outpicref->data[1] + i * s->outpicref->linesize[1] + s->xpos, 128, outlink->w - s->xpos);
276             memset(s->outpicref->data[2] + i * s->outpicref->linesize[2] + s->xpos, 128, outlink->w - s->xpos);
277         }
278         ret = ff_filter_frame(outlink, s->outpicref);
279         s->outpicref = NULL;
280     }
281
282     return ret;
283 }
284
285 static int plot_spectrum_column(AVFilterLink *inlink, AVFrame *insamples)
286 {
287     int ret;
288     AVFilterContext *ctx = inlink->dst;
289     AVFilterLink *outlink = ctx->outputs[0];
290     ShowSpectrumContext *s = ctx->priv;
291     AVFrame *outpicref = s->outpicref;
292
293     /* nb_freq contains the power of two superior or equal to the output image
294      * height (or half the RDFT window size) */
295     const int nb_freq = 1 << (s->rdft_bits - 1);
296     const int win_size = nb_freq << 1;
297     const double w = 1. / (sqrt(nb_freq) * 32768.);
298     int h = s->channel_height;
299
300     int ch, plane, n, y;
301
302     av_assert0(insamples->nb_samples == win_size);
303
304     /* fill RDFT input with the number of samples available */
305     for (ch = 0; ch < s->nb_display_channels; ch++) {
306         const int16_t *p = (int16_t *)insamples->extended_data[ch];
307
308         for (n = 0; n < win_size; n++)
309             s->rdft_data[ch][n] = p[n] * s->window_func_lut[n];
310     }
311
312     /* run RDFT on each samples set */
313     for (ch = 0; ch < s->nb_display_channels; ch++)
314         av_rdft_calc(s->rdft, s->rdft_data[ch]);
315
316     /* fill a new spectrum column */
317 #define RE(y, ch) s->rdft_data[ch][2 * (y) + 0]
318 #define IM(y, ch) s->rdft_data[ch][2 * (y) + 1]
319 #define MAGNITUDE(y, ch) hypot(RE(y, ch), IM(y, ch))
320
321     /* initialize buffer for combining to black */
322     for (y = 0; y < outlink->h; y++) {
323         s->combine_buffer[3 * y    ] = 0;
324         s->combine_buffer[3 * y + 1] = 127.5;
325         s->combine_buffer[3 * y + 2] = 127.5;
326     }
327
328     for (ch = 0; ch < s->nb_display_channels; ch++) {
329         float yf, uf, vf;
330
331         /* decide color range */
332         switch (s->mode) {
333         case COMBINED:
334             // reduce range by channel count
335             yf = 256.0f / s->nb_display_channels;
336             switch (s->color_mode) {
337             case INTENSITY:
338                 uf = yf;
339                 vf = yf;
340                 break;
341             case CHANNEL:
342                 /* adjust saturation for mixed UV coloring */
343                 /* this factor is correct for infinite channels, an approximation otherwise */
344                 uf = yf * M_PI;
345                 vf = yf * M_PI;
346                 break;
347             default:
348                 av_assert0(0);
349             }
350             break;
351         case SEPARATE:
352             // full range
353             yf = 256.0f;
354             uf = 256.0f;
355             vf = 256.0f;
356             break;
357         default:
358             av_assert0(0);
359         }
360
361         if (s->color_mode == CHANNEL) {
362             if (s->nb_display_channels > 1) {
363                 uf *= 0.5 * sin((2 * M_PI * ch) / s->nb_display_channels);
364                 vf *= 0.5 * cos((2 * M_PI * ch) / s->nb_display_channels);
365             } else {
366                 uf = 0.0f;
367                 vf = 0.0f;
368             }
369         }
370         uf *= s->saturation;
371         vf *= s->saturation;
372
373         /* draw the channel */
374         for (y = 0; y < h; y++) {
375             int row = (s->mode == COMBINED) ? y : ch * h + y;
376             float *out = &s->combine_buffer[3 * row];
377
378             /* get magnitude */
379             float a = w * MAGNITUDE(y, ch);
380
381             /* apply scale */
382             switch (s->scale) {
383             case LINEAR:
384                 break;
385             case SQRT:
386                 a = sqrt(a);
387                 break;
388             case CBRT:
389                 a = cbrt(a);
390                 break;
391             case LOG:
392                 a = 1 - log(FFMAX(FFMIN(1, a), 1e-6)) / log(1e-6); // zero = -120dBFS
393                 break;
394             default:
395                 av_assert0(0);
396             }
397
398             if (s->color_mode == INTENSITY) {
399                 float y, u, v;
400                 int i;
401
402                 for (i = 1; i < sizeof(intensity_color_table) / sizeof(*intensity_color_table) - 1; i++)
403                     if (intensity_color_table[i].a >= a)
404                         break;
405                 // i now is the first item >= the color
406                 // now we know to interpolate between item i - 1 and i
407                 if (a <= intensity_color_table[i - 1].a) {
408                     y = intensity_color_table[i - 1].y;
409                     u = intensity_color_table[i - 1].u;
410                     v = intensity_color_table[i - 1].v;
411                 } else if (a >= intensity_color_table[i].a) {
412                     y = intensity_color_table[i].y;
413                     u = intensity_color_table[i].u;
414                     v = intensity_color_table[i].v;
415                 } else {
416                     float start = intensity_color_table[i - 1].a;
417                     float end = intensity_color_table[i].a;
418                     float lerpfrac = (a - start) / (end - start);
419                     y = intensity_color_table[i - 1].y * (1.0f - lerpfrac)
420                       + intensity_color_table[i].y * lerpfrac;
421                     u = intensity_color_table[i - 1].u * (1.0f - lerpfrac)
422                       + intensity_color_table[i].u * lerpfrac;
423                     v = intensity_color_table[i - 1].v * (1.0f - lerpfrac)
424                       + intensity_color_table[i].v * lerpfrac;
425                 }
426
427                 out[0] += y * yf;
428                 out[1] += u * uf;
429                 out[2] += v * vf;
430             } else {
431                 out[0] += a * yf;
432                 out[1] += a * uf;
433                 out[2] += a * vf;
434             }
435         }
436     }
437
438     /* copy to output */
439     if (s->sliding == SCROLL) {
440         for (plane = 0; plane < 3; plane++) {
441             for (y = 0; y < outlink->h; y++) {
442                 uint8_t *p = outpicref->data[plane] +
443                              y * outpicref->linesize[plane];
444                 memmove(p, p + 1, outlink->w - 1);
445             }
446         }
447         s->xpos = outlink->w - 1;
448     }
449     for (plane = 0; plane < 3; plane++) {
450         uint8_t *p = outpicref->data[plane] +
451                      (outlink->h - 1) * outpicref->linesize[plane] +
452                      s->xpos;
453         for (y = 0; y < outlink->h; y++) {
454             *p = rint(FFMAX(0, FFMIN(s->combine_buffer[3 * y + plane], 255)));
455             p -= outpicref->linesize[plane];
456         }
457     }
458
459     if (s->sliding != FULLFRAME || s->xpos == 0)
460         outpicref->pts = insamples->pts;
461
462     s->xpos++;
463     if (s->xpos >= outlink->w)
464         s->xpos = 0;
465     if (s->sliding != FULLFRAME || s->xpos == 0) {
466         ret = ff_filter_frame(outlink, av_frame_clone(s->outpicref));
467         if (ret < 0)
468             return ret;
469     }
470
471     return win_size;
472 }
473
474 static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
475 {
476     AVFilterContext *ctx = inlink->dst;
477     ShowSpectrumContext *s = ctx->priv;
478     unsigned win_size = 1 << s->rdft_bits;
479     int ret = 0;
480
481     av_assert0(insamples->nb_samples <= win_size);
482     if (insamples->nb_samples == win_size)
483         ret = plot_spectrum_column(inlink, insamples);
484
485     av_frame_free(&insamples);
486     return ret;
487 }
488
489 static const AVFilterPad showspectrum_inputs[] = {
490     {
491         .name         = "default",
492         .type         = AVMEDIA_TYPE_AUDIO,
493         .filter_frame = filter_frame,
494     },
495     { NULL }
496 };
497
498 static const AVFilterPad showspectrum_outputs[] = {
499     {
500         .name          = "default",
501         .type          = AVMEDIA_TYPE_VIDEO,
502         .config_props  = config_output,
503         .request_frame = request_frame,
504     },
505     { NULL }
506 };
507
508 AVFilter ff_avf_showspectrum = {
509     .name          = "showspectrum",
510     .description   = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output."),
511     .uninit        = uninit,
512     .query_formats = query_formats,
513     .priv_size     = sizeof(ShowSpectrumContext),
514     .inputs        = showspectrum_inputs,
515     .outputs       = showspectrum_outputs,
516     .priv_class    = &showspectrum_class,
517 };