aboutsummaryrefslogtreecommitdiffstats
path: root/libavfilter/avf_showspectrum.c
blob: 227aff8d32779cd2561fd07cf03ab760ec8b591f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
/*
 * Copyright (c) 2012-2013 Clément Bœsch
 * Copyright (c) 2013 Rudolf Polzer <divverent@xonotic.org>
 *
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/**
 * @file
 * audio to spectrum (video) transmedia filter, based on ffplay rdft showmode
 * (by Michael Niedermayer) and lavfi/avf_showwaves (by Stefano Sabatini).
 */

#include <math.h>

#include "libavcodec/avfft.h"
#include "libavutil/avassert.h"
#include "libavutil/channel_layout.h"
#include "libavutil/opt.h"
#include "avfilter.h"
#include "internal.h"
#include "window_func.h"

enum DisplayMode  { COMBINED, SEPARATE, NB_MODES };
enum DisplayScale { LINEAR, SQRT, CBRT, LOG, NB_SCALES };
enum ColorMode    { CHANNEL, INTENSITY, RAINBOW, MORELAND, NEBULAE, NB_CLMODES };
enum SlideMode    { REPLACE, SCROLL, FULLFRAME, RSCROLL, NB_SLIDES };
enum Orientation  { VERTICAL, HORIZONTAL, NB_ORIENTATIONS };

typedef struct {
    const AVClass *class;
    int w, h;
    AVFrame *outpicref;
    int nb_display_channels;
    int orientation;
    int channel_width;
    int channel_height;
    int sliding;                ///< 1 if sliding mode, 0 otherwise
    int mode;                   ///< channel display mode
    int color_mode;             ///< display color scheme
    int scale;
    float saturation;           ///< color saturation multiplier
    int xpos;                   ///< x position (current column)
    RDFTContext *rdft;          ///< Real Discrete Fourier Transform context
    int rdft_bits;              ///< number of bits (RDFT window size = 1<<rdft_bits)
    FFTSample **rdft_data;      ///< bins holder for each (displayed) channels
    float *window_func_lut;     ///< Window function LUT
    int win_func;
    double win_scale;
    float overlap;
    float *combine_buffer;      ///< color combining buffer (3 * h items)
} ShowSpectrumContext;

#define OFFSET(x) offsetof(ShowSpectrumContext, x)
#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM

static const AVOption showspectrum_options[] = {
    { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
    { "s",    "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
    { "slide", "set sliding mode", OFFSET(sliding), AV_OPT_TYPE_INT, {.i64 = 0}, 0, NB_SLIDES-1, FLAGS, "slide" },
        { "replace", "replace old columns with new", 0, AV_OPT_TYPE_CONST, {.i64=REPLACE}, 0, 0, FLAGS, "slide" },
        { "scroll", "scroll from right to left", 0, AV_OPT_TYPE_CONST, {.i64=SCROLL}, 0, 0, FLAGS, "slide" },
        { "rscroll", "scroll from left to right", 0, AV_OPT_TYPE_CONST, {.i64=RSCROLL}, 0, 0, FLAGS, "slide" },
        { "fullframe", "return full frames", 0, AV_OPT_TYPE_CONST, {.i64=FULLFRAME}, 0, 0, FLAGS, "slide" },
    { "mode", "set channel display mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=COMBINED}, COMBINED, NB_MODES-1, FLAGS, "mode" },
        { "combined", "combined mode", 0, AV_OPT_TYPE_CONST, {.i64=COMBINED}, 0, 0, FLAGS, "mode" },
        { "separate", "separate mode", 0, AV_OPT_TYPE_CONST, {.i64=SEPARATE}, 0, 0, FLAGS, "mode" },
    { "color", "set channel coloring", OFFSET(color_mode), AV_OPT_TYPE_INT, {.i64=CHANNEL}, CHANNEL, NB_CLMODES-1, FLAGS, "color" },
        { "channel",   "separate color for each channel", 0, AV_OPT_TYPE_CONST, {.i64=CHANNEL},   0, 0, FLAGS, "color" },
        { "intensity", "intensity based coloring",        0, AV_OPT_TYPE_CONST, {.i64=INTENSITY}, 0, 0, FLAGS, "color" },
        { "rainbow",   "rainbow based coloring",          0, AV_OPT_TYPE_CONST, {.i64=RAINBOW},   0, 0, FLAGS, "color" },
        { "moreland",  "moreland based coloring",         0, AV_OPT_TYPE_CONST, {.i64=MORELAND},  0, 0, FLAGS, "color" },
        { "nebulae",   "nebulae based coloring",          0, AV_OPT_TYPE_CONST, {.i64=NEBULAE},   0, 0, FLAGS, "color" },
    { "scale", "set display scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64=SQRT}, LINEAR, NB_SCALES-1, FLAGS, "scale" },
        { "sqrt", "square root", 0, AV_OPT_TYPE_CONST, {.i64=SQRT},   0, 0, FLAGS, "scale" },
        { "cbrt", "cubic root",  0, AV_OPT_TYPE_CONST, {.i64=CBRT},   0, 0, FLAGS, "scale" },
        { "log",  "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG},    0, 0, FLAGS, "scale" },
        { "lin",  "linear",      0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, FLAGS, "scale" },
    { "saturation", "color saturation multiplier", OFFSET(saturation), AV_OPT_TYPE_FLOAT, {.dbl = 1}, -10, 10, FLAGS },
    { "win_func", "set window function", OFFSET(win_func), AV_OPT_TYPE_INT, {.i64 = WFUNC_HANNING}, 0, NB_WFUNC-1, FLAGS, "win_func" },
        { "rect",     "Rectangular",      0, AV_OPT_TYPE_CONST, {.i64=WFUNC_RECT},     0, 0, FLAGS, "win_func" },
        { "bartlett", "Bartlett",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BARTLETT}, 0, 0, FLAGS, "win_func" },
        { "hann",     "Hann",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, FLAGS, "win_func" },
        { "hanning",  "Hanning",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HANNING},  0, 0, FLAGS, "win_func" },
        { "hamming",  "Hamming",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_HAMMING},  0, 0, FLAGS, "win_func" },
        { "blackman", "Blackman",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BLACKMAN}, 0, 0, FLAGS, "win_func" },
        { "welch",    "Welch",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_WELCH},    0, 0, FLAGS, "win_func" },
        { "flattop",  "Flat-top",         0, AV_OPT_TYPE_CONST, {.i64=WFUNC_FLATTOP},  0, 0, FLAGS, "win_func" },
        { "bharris",  "Blackman-Harris",  0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BHARRIS},  0, 0, FLAGS, "win_func" },
        { "bnuttall", "Blackman-Nuttall", 0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BNUTTALL}, 0, 0, FLAGS, "win_func" },
        { "bhann",    "Bartlett-Hann",    0, AV_OPT_TYPE_CONST, {.i64=WFUNC_BHANN},    0, 0, FLAGS, "win_func" },
        { "sine",     "Sine",             0, AV_OPT_TYPE_CONST, {.i64=WFUNC_SINE},     0, 0, FLAGS, "win_func" },
        { "nuttall",  "Nuttall",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_NUTTALL},  0, 0, FLAGS, "win_func" },
        { "lanczos",  "Lanczos",          0, AV_OPT_TYPE_CONST, {.i64=WFUNC_LANCZOS},  0, 0, FLAGS, "win_func" },
        { "gauss",    "Gauss",            0, AV_OPT_TYPE_CONST, {.i64=WFUNC_GAUSS},    0, 0, FLAGS, "win_func" },
    { "orientation", "set orientation", OFFSET(orientation), AV_OPT_TYPE_INT, {.i64=VERTICAL}, 0, NB_ORIENTATIONS-1, FLAGS, "orientation" },
        { "vertical",   NULL, 0, AV_OPT_TYPE_CONST, {.i64=VERTICAL},   0, 0, FLAGS, "orientation" },
        { "horizontal", NULL, 0, AV_OPT_TYPE_CONST, {.i64=HORIZONTAL}, 0, 0, FLAGS, "orientation" },
    { NULL }
};

AVFILTER_DEFINE_CLASS(showspectrum);

static const struct ColorTable {
    float a, y, u, v;
} color_table[][8] = {
    [INTENSITY] = {
    {    0,                  0,                  0,                   0 },
    { 0.13, .03587126228984074,  .1573300977624594, -.02548747583751842 },
    { 0.30, .18572281794568020,  .1772436246393981,  .17475554840414750 },
    { 0.60, .28184980583656130, -.1593064119945782,  .47132074554608920 },
    { 0.73, .65830621175547810, -.3716070802232764,  .24352759331252930 },
    { 0.78, .76318535758242900, -.4307467689263783,  .16866496622310430 },
    { 0.91, .95336363636363640, -.2045454545454546,  .03313636363636363 },
    {    1,                  1,                  0,                   0 }},
    [RAINBOW] = {
    {    0,                  0,                  0,                   0 },
    { 0.13,            44/256.,     (189-128)/256.,      (138-128)/256. },
    { 0.25,            29/256.,     (186-128)/256.,      (119-128)/256. },
    { 0.38,           119/256.,     (194-128)/256.,       (53-128)/256. },
    { 0.60,           111/256.,      (73-128)/256.,       (59-128)/256. },
    { 0.73,           205/256.,      (19-128)/256.,      (149-128)/256. },
    { 0.86,           135/256.,      (83-128)/256.,      (200-128)/256. },
    {    1,            73/256.,      (95-128)/256.,      (225-128)/256. }},
    [MORELAND] = {
    {    0,            44/256.,     (181-128)/256.,      (112-128)/256. },
    { 0.13,           126/256.,     (177-128)/256.,      (106-128)/256. },
    { 0.25,           164/256.,     (163-128)/256.,      (109-128)/256. },
    { 0.38,           200/256.,     (140-128)/256.,      (120-128)/256. },
    { 0.60,           201/256.,     (117-128)/256.,      (141-128)/256. },
    { 0.73,           177/256.,     (103-128)/256.,      (165-128)/256. },
    { 0.86,           136/256.,     (100-128)/256.,      (183-128)/256. },
    {    1,            68/256.,     (117-128)/256.,      (203-128)/256. }},
    [NEBULAE] = {
    {    0,            10/256.,     (134-128)/256.,      (132-128)/256. },
    { 0.23,            21/256.,     (137-128)/256.,      (130-128)/256. },
    { 0.45,            35/256.,     (134-128)/256.,      (134-128)/256. },
    { 0.57,            51/256.,     (130-128)/256.,      (139-128)/256. },
    { 0.67,           104/256.,     (116-128)/256.,      (162-128)/256. },
    { 0.77,           120/256.,     (105-128)/256.,      (188-128)/256. },
    { 0.87,           140/256.,     (105-128)/256.,      (188-128)/256. },
    {    1,                  1,                  0,                   0 }},
};

static av_cold void uninit(AVFilterContext *ctx)
{
    ShowSpectrumContext *s = ctx->priv;
    int i;

    av_freep(&s->combine_buffer);
    av_rdft_end(s->rdft);
    for (i = 0; i < s->nb_display_channels; i++)
        av_freep(&s->rdft_data[i]);
    av_freep(&s->rdft_data);
    av_freep(&s->window_func_lut);
    av_frame_free(&s->outpicref);
}

static int query_formats(AVFilterContext *ctx)
{
    AVFilterFormats *formats = NULL;
    AVFilterChannelLayouts *layouts = NULL;
    AVFilterLink *inlink = ctx->inputs[0];
    AVFilterLink *outlink = ctx->outputs[0];
    static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE };
    static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_NONE };
    int ret;

    /* set input audio formats */
    formats = ff_make_format_list(sample_fmts);
    if ((ret = ff_formats_ref(formats, &inlink->out_formats)) < 0)
        return ret;

    layouts = ff_all_channel_layouts();
    if ((ret = ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts)) < 0)
        return ret;

    formats = ff_all_samplerates();
    if ((ret = ff_formats_ref(formats, &inlink->out_samplerates)) < 0)
        return ret;

    /* set output video format */
    formats = ff_make_format_list(pix_fmts);
    if ((ret = ff_formats_ref(formats, &outlink->in_formats)) < 0)
        return ret;

    return 0;
}

static int config_output(AVFilterLink *outlink)
{
    AVFilterContext *ctx = outlink->src;
    AVFilterLink *inlink = ctx->inputs[0];
    ShowSpectrumContext *s = ctx->priv;
    int i, rdft_bits, win_size, h, w;

    outlink->w = s->w;
    outlink->h = s->h;

    h = (s->mode == COMBINED || s->orientation == HORIZONTAL) ? outlink->h : outlink->h / inlink->channels;
    w = (s->mode == COMBINED || s->orientation == VERTICAL)   ? outlink->w : outlink->w / inlink->channels;
    s->channel_height = h;
    s->channel_width  = w;

    if (s->orientation == VERTICAL) {
        /* RDFT window size (precision) according to the requested output frame height */
        for (rdft_bits = 1; 1 << rdft_bits < 2 * h; rdft_bits++);
    } else {
        /* RDFT window size (precision) according to the requested output frame width */
        for (rdft_bits = 1; 1 << rdft_bits < 2 * w; rdft_bits++);
    }
    win_size = 1 << rdft_bits;

    /* (re-)configuration if the video output changed (or first init) */
    if (rdft_bits != s->rdft_bits) {
        AVFrame *outpicref;

        av_rdft_end(s->rdft);
        s->rdft = av_rdft_init(rdft_bits, DFT_R2C);
        if (!s->rdft) {
            av_log(ctx, AV_LOG_ERROR, "Unable to create RDFT context. "
                   "The window size might be too high.\n");
            return AVERROR(EINVAL);
        }
        s->rdft_bits = rdft_bits;

        /* RDFT buffers: x2 for each (display) channel buffer.
         * Note: we use free and malloc instead of a realloc-like function to
         * make sure the buffer is aligned in memory for the FFT functions. */
        for (i = 0; i < s->nb_display_channels; i++)
            av_freep(&s->rdft_data[i]);
        av_freep(&s->rdft_data);
        s->nb_display_channels = inlink->channels;

        s->rdft_data = av_calloc(s->nb_display_channels, sizeof(*s->rdft_data));
        if (!s->rdft_data)
            return AVERROR(ENOMEM);
        for (i = 0; i < s->nb_display_channels; i++) {
            s->rdft_data[i] = av_calloc(win_size, sizeof(**s->rdft_data));
            if (!s->rdft_data[i])
                return AVERROR(ENOMEM);
        }

        /* pre-calc windowing function */
        s->window_func_lut =
            av_realloc_f(s->window_func_lut, win_size,
                         sizeof(*s->window_func_lut));
        if (!s->window_func_lut)
            return AVERROR(ENOMEM);
        ff_generate_window_func(s->window_func_lut, win_size, s->win_func, &s->overlap);

        for (s->win_scale = 0, i = 0; i < win_size; i++) {
            s->win_scale += s->window_func_lut[i] * s->window_func_lut[i];
        }
        s->win_scale = 1. / (sqrt(s->win_scale) * 32768.);

        /* prepare the initial picref buffer (black frame) */
        av_frame_free(&s->outpicref);
        s->outpicref = outpicref =
            ff_get_video_buffer(outlink, outlink->w, outlink->h);
        if (!outpicref)
            return AVERROR(ENOMEM);
        outlink->sample_aspect_ratio = (AVRational){1,1};
        for (i = 0; i < outlink->h; i++) {
            memset(outpicref->data[0] + i * outpicref->linesize[0],   0, outlink->w);
            memset(outpicref->data[1] + i * outpicref->linesize[1], 128, outlink->w);
            memset(outpicref->data[2] + i * outpicref->linesize[2], 128, outlink->w);
        }
    }

    if ((s->orientation == VERTICAL   && s->xpos >= outlink->w) ||
        (s->orientation == HORIZONTAL && s->xpos >= outlink->h))
        s->xpos = 0;

    outlink->frame_rate = av_make_q(inlink->sample_rate, win_size);
    if (s->orientation == VERTICAL && s->sliding == FULLFRAME)
        outlink->frame_rate.den *= outlink->w;
    if (s->orientation == HORIZONTAL && s->sliding == FULLFRAME)
        outlink->frame_rate.den *= outlink->h;

    inlink->min_samples = inlink->max_samples = inlink->partial_buf_size =
        win_size;

    if (s->orientation == VERTICAL) {
        s->combine_buffer =
            av_realloc_f(s->combine_buffer, outlink->h * 3,
                         sizeof(*s->combine_buffer));
    } else {
        s->combine_buffer =
            av_realloc_f(s->combine_buffer, outlink->w * 3,
                         sizeof(*s->combine_buffer));
    }

    av_log(ctx, AV_LOG_VERBOSE, "s:%dx%d RDFT window size:%d\n",
           s->w, s->h, win_size);
    return 0;
}

static int request_frame(AVFilterLink *outlink)
{
    ShowSpectrumContext *s = outlink->src->priv;
    AVFilterLink *inlink = outlink->src->inputs[0];
    unsigned i;
    int ret;

    ret = ff_request_frame(inlink);
    if (ret == AVERROR_EOF && s->sliding == FULLFRAME && s->xpos > 0 &&
        s->outpicref) {
        if (s->orientation == VERTICAL) {
            for (i = 0; i < outlink->h; i++) {
                memset(s->outpicref->data[0] + i * s->outpicref->linesize[0] + s->xpos,   0, outlink->w - s->xpos);
                memset(s->outpicref->data[1] + i * s->outpicref->linesize[1] + s->xpos, 128, outlink->w - s->xpos);
                memset(s->outpicref->data[2] + i * s->outpicref->linesize[2] + s->xpos, 128, outlink->w - s->xpos);
            }
        } else {
            for (i = s->xpos; i < outlink->h; i++) {
                memset(s->outpicref->data[0] + i * s->outpicref->linesize[0],   0, outlink->w);
                memset(s->outpicref->data[1] + i * s->outpicref->linesize[1], 128, outlink->w);
                memset(s->outpicref->data[2] + i * s->outpicref->linesize[2], 128, outlink->w);
            }
        }
        ret = ff_filter_frame(outlink, s->outpicref);
        s->outpicref = NULL;
    }

    return ret;
}

static int plot_spectrum_column(AVFilterLink *inlink, AVFrame *insamples)
{
    int ret;
    AVFilterContext *ctx = inlink->dst;
    AVFilterLink *outlink = ctx->outputs[0];
    ShowSpectrumContext *s = ctx->priv;
    AVFrame *outpicref = s->outpicref;

    /* nb_freq contains the power of two superior or equal to the output image
     * height (or half the RDFT window size) */
    const int nb_freq = 1 << (s->rdft_bits - 1);
    const int win_size = nb_freq << 1;
    const double w = s->win_scale;
    int h = s->orientation == VERTICAL ? s->channel_height : s->channel_width;

    int ch, plane, n, x, y;

    av_assert0(insamples->nb_samples == win_size);

    /* fill RDFT input with the number of samples available */
    for (ch = 0; ch < s->nb_display_channels; ch++) {
        const int16_t *p = (int16_t *)insamples->extended_data[ch];

        for (n = 0; n < win_size; n++)
            s->rdft_data[ch][n] = p[n] * s->window_func_lut[n];
    }

    /* run RDFT on each samples set */
    for (ch = 0; ch < s->nb_display_channels; ch++)
        av_rdft_calc(s->rdft, s->rdft_data[ch]);

    /* fill a new spectrum column */
#define RE(y, ch) s->rdft_data[ch][2 * (y) + 0]
#define IM(y, ch) s->rdft_data[ch][2 * (y) + 1]
#define MAGNITUDE(y, ch) hypot(RE(y, ch), IM(y, ch))

    /* initialize buffer for combining to black */
    if (s->orientation == VERTICAL) {
        for (y = 0; y < outlink->h; y++) {
            s->combine_buffer[3 * y    ] = 0;
            s->combine_buffer[3 * y + 1] = 127.5;
            s->combine_buffer[3 * y + 2] = 127.5;
        }
    } else {
        for (y = 0; y < outlink->w; y++) {
            s->combine_buffer[3 * y    ] = 0;
            s->combine_buffer[3 * y + 1] = 127.5;
            s->combine_buffer[3 * y + 2] = 127.5;
        }
    }

    for (ch = 0; ch < s->nb_display_channels; ch++) {
        float yf, uf, vf;

        /* decide color range */
        switch (s->mode) {
        case COMBINED:
            // reduce range by channel count
            yf = 256.0f / s->nb_display_channels;
            switch (s->color_mode) {
            case RAINBOW:
            case MORELAND:
            case NEBULAE:
            case INTENSITY:
                uf = yf;
                vf = yf;
                break;
            case CHANNEL:
                /* adjust saturation for mixed UV coloring */
                /* this factor is correct for infinite channels, an approximation otherwise */
                uf = yf * M_PI;
                vf = yf * M_PI;
                break;
            default:
                av_assert0(0);
            }
            break;
        case SEPARATE:
            // full range
            yf = 256.0f;
            uf = 256.0f;
            vf = 256.0f;
            break;
        default:
            av_assert0(0);
        }

        if (s->color_mode == CHANNEL) {
            if (s->nb_display_channels > 1) {
                uf *= 0.5 * sin((2 * M_PI * ch) / s->nb_display_channels);
                vf *= 0.5 * cos((2 * M_PI * ch) / s->nb_display_channels);
            } else {
                uf = 0.0f;
                vf = 0.0f;
            }
        }
        uf *= s->saturation;
        vf *= s->saturation;

        /* draw the channel */
        for (y = 0; y < h; y++) {
            int row = (s->mode == COMBINED) ? y : ch * h + y;
            float *out = &s->combine_buffer[3 * row];

            /* get magnitude */
            float a = w * MAGNITUDE(y, ch);

            /* apply scale */
            switch (s->scale) {
            case LINEAR:
                break;
            case SQRT:
                a = sqrt(a);
                break;
            case CBRT:
                a = cbrt(a);
                break;
            case LOG:
                a = 1 + log10(FFMAX(FFMIN(1, a), 1e-6)) / 5; // zero = -120dBFS
                break;
            default:
                av_assert0(0);
            }

            if (s->color_mode > CHANNEL) {
                const int cm = s->color_mode;
                float y, u, v;
                int i;

                for (i = 1; i < FF_ARRAY_ELEMS(color_table[cm]) - 1; i++)
                    if (color_table[cm][i].a >= a)
                        break;
                // i now is the first item >= the color
                // now we know to interpolate between item i - 1 and i
                if (a <= color_table[cm][i - 1].a) {
                    y = color_table[cm][i - 1].y;
                    u = color_table[cm][i - 1].u;
                    v = color_table[cm][i - 1].v;
                } else if (a >= color_table[cm][i].a) {
                    y = color_table[cm][i].y;
                    u = color_table[cm][i].u;
                    v = color_table[cm][i].v;
                } else {
                    float start = color_table[cm][i - 1].a;
                    float end = color_table[cm][i].a;
                    float lerpfrac = (a - start) / (end - start);
                    y = color_table[cm][i - 1].y * (1.0f - lerpfrac)
                      + color_table[cm][i].y * lerpfrac;
                    u = color_table[cm][i - 1].u * (1.0f - lerpfrac)
                      + color_table[cm][i].u * lerpfrac;
                    v = color_table[cm][i - 1].v * (1.0f - lerpfrac)
                      + color_table[cm][i].v * lerpfrac;
                }

                out[0] += y * yf;
                out[1] += u * uf;
                out[2] += v * vf;
            } else {
                out[0] += a * yf;
                out[1] += a * uf;
                out[2] += a * vf;
            }
        }
    }

    /* copy to output */
    if (s->orientation == VERTICAL) {
        if (s->sliding == SCROLL) {
            for (plane = 0; plane < 3; plane++) {
                for (y = 0; y < outlink->h; y++) {
                    uint8_t *p = outpicref->data[plane] +
                                 y * outpicref->linesize[plane];
                    memmove(p, p + 1, outlink->w - 1);
                }
            }
            s->xpos = outlink->w - 1;
        } else if (s->sliding == RSCROLL) {
            for (plane = 0; plane < 3; plane++) {
                for (y = 0; y < outlink->h; y++) {
                    uint8_t *p = outpicref->data[plane] +
                                 y * outpicref->linesize[plane];
                    memmove(p + 1, p, outlink->w - 1);
                }
            }
            s->xpos = 0;
        }
        for (plane = 0; plane < 3; plane++) {
            uint8_t *p = outpicref->data[plane] +
                         (outlink->h - 1) * outpicref->linesize[plane] +
                         s->xpos;
            for (y = 0; y < outlink->h; y++) {
                *p = lrint(FFMAX(0, FFMIN(s->combine_buffer[3 * y + plane], 255)));
                p -= outpicref->linesize[plane];
            }
        }
    } else {
        if (s->sliding == SCROLL) {
            for (plane = 0; plane < 3; plane++) {
                for (y = 1; y < outlink->h; y++) {
                    memmove(outpicref->data[plane] + (y-1) * outpicref->linesize[plane],
                            outpicref->data[plane] + (y  ) * outpicref->linesize[plane],
                            outlink->w);
                }
            }
            s->xpos = outlink->h - 1;
        } else if (s->sliding == RSCROLL) {
            for (plane = 0; plane < 3; plane++) {
                for (y = outlink->h - 1; y >= 1; y--) {
                    memmove(outpicref->data[plane] + (y  ) * outpicref->linesize[plane],
                            outpicref->data[plane] + (y-1) * outpicref->linesize[plane],
                            outlink->w);
                }
            }
            s->xpos = 0;
        }
        for (plane = 0; plane < 3; plane++) {
            uint8_t *p = outpicref->data[plane] +
                         s->xpos * outpicref->linesize[plane];
            for (x = 0; x < outlink->w; x++) {
                *p = lrint(FFMAX(0, FFMIN(s->combine_buffer[3 * x + plane], 255)));
                p++;
            }
        }
    }

    if (s->sliding != FULLFRAME || s->xpos == 0)
        outpicref->pts = insamples->pts;

    s->xpos++;
    if (s->orientation == VERTICAL && s->xpos >= outlink->w)
        s->xpos = 0;
    if (s->orientation == HORIZONTAL && s->xpos >= outlink->h)
        s->xpos = 0;
    if (s->sliding != FULLFRAME || s->xpos == 0) {
        ret = ff_filter_frame(outlink, av_frame_clone(s->outpicref));
        if (ret < 0)
            return ret;
    }

    return win_size;
}

static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
{
    AVFilterContext *ctx = inlink->dst;
    ShowSpectrumContext *s = ctx->priv;
    unsigned win_size = 1 << s->rdft_bits;
    int ret = 0;

    av_assert0(insamples->nb_samples <= win_size);
    if (insamples->nb_samples == win_size)
        ret = plot_spectrum_column(inlink, insamples);

    av_frame_free(&insamples);
    return ret;
}

static const AVFilterPad showspectrum_inputs[] = {
    {
        .name         = "default",
        .type         = AVMEDIA_TYPE_AUDIO,
        .filter_frame = filter_frame,
    },
    { NULL }
};

static const AVFilterPad showspectrum_outputs[] = {
    {
        .name          = "default",
        .type          = AVMEDIA_TYPE_VIDEO,
        .config_props  = config_output,
        .request_frame = request_frame,
    },
    { NULL }
};

AVFilter ff_avf_showspectrum = {
    .name          = "showspectrum",
    .description   = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output."),
    .uninit        = uninit,
    .query_formats = query_formats,
    .priv_size     = sizeof(ShowSpectrumContext),
    .inputs        = showspectrum_inputs,
    .outputs       = showspectrum_outputs,
    .priv_class    = &showspectrum_class,
};