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