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