Browse code

lavfi/showspectrum: display multiple channels in separate row

The showspectrum filter gets multiple channel (any count) support.

Signed-off-by: Rudolf Polzer <divverent@xonotic.org>

Rudolf Polzer authored on 2013/02/02 00:33:17
Showing 3 changed files
... ...
@@ -12,6 +12,7 @@ version <next>:
12 12
 - filtering audio with unknown channel layout
13 13
 - allpass, bass, bandpass, bandreject, biquad, equalizer, highpass, lowpass
14 14
   and treble audio filter
15
+- improved showspectrum filter, with multichannel support and sox-like colors
15 16
 
16 17
 
17 18
 version 1.1:
... ...
@@ -6055,6 +6055,34 @@ Specify the video size for the output. Default value is @code{640x512}.
6055 6055
 @item slide
6056 6056
 Specify if the spectrum should slide along the window. Default value is
6057 6057
 @code{0}.
6058
+@item mode
6059
+Specify display mode. Can be either @code{combined}: all channels are
6060
+displayed in the same row, or @code{separate}: all channels are displayed
6061
+in separate rows. Default value is @code{combined}.
6062
+@item color
6063
+Specify display color mode. Can be either @code{channel}: each channel
6064
+is displayed in a separate color, or @code{intensity}: each channel is
6065
+displayed using the same color scheme. Default value is @code{channel}.
6066
+@item scale
6067
+Specify scale used for calculating intensity color values.
6068
+
6069
+It accepts the following values:
6070
+@table @option
6071
+@item{lin}
6072
+linear
6073
+@item{sqrt}
6074
+square root, default
6075
+@item{cbrt}
6076
+cubic root
6077
+@item{log}
6078
+logarithmic
6079
+@end table
6080
+
6081
+@item saturation
6082
+Set saturation modifier for displayed colors. Negative values provide
6083
+alternative color scheme. @code{0} is no saturation at all.
6084
+Saturation must be in [-10.0, 10.0] range.
6085
+Default value is @code{1}.
6058 6086
 @end table
6059 6087
 
6060 6088
 The usage is very similar to the showwaves filter; see the examples in that
... ...
@@ -27,24 +27,36 @@
27 27
 #include <math.h>
28 28
 
29 29
 #include "libavcodec/avfft.h"
30
+#include "libavutil/avassert.h"
30 31
 #include "libavutil/channel_layout.h"
31 32
 #include "libavutil/opt.h"
32 33
 #include "avfilter.h"
33 34
 #include "internal.h"
34 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
+
35 40
 typedef struct {
36 41
     const AVClass *class;
37 42
     int w, h;
38 43
     AVFilterBufferRef *outpicref;
39 44
     int req_fullfilled;
45
+    int nb_display_channels;
46
+    int channel_height;
40 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
41 52
     int xpos;                   ///< x position (current column)
42 53
     RDFTContext *rdft;          ///< Real Discrete Fourier Transform context
43 54
     int rdft_bits;              ///< number of bits (RDFT window size = 1<<rdft_bits)
44
-    FFTSample *rdft_data;       ///< bins holder for each (displayed) channels
55
+    FFTSample **rdft_data;      ///< bins holder for each (displayed) channels
45 56
     int filled;                 ///< number of samples (per channel) filled in current rdft_buffer
46 57
     int consumed;               ///< number of samples (per channel) consumed from the input frame
47 58
     float *window_func_lut;     ///< Window function LUT
59
+    float *combine_buffer;      ///< color combining buffer (3 * h items)
48 60
 } ShowSpectrumContext;
49 61
 
50 62
 #define OFFSET(x) offsetof(ShowSpectrumContext, x)
... ...
@@ -54,11 +66,38 @@ static const AVOption showspectrum_options[] = {
54 54
     { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
55 55
     { "s",    "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
56 56
     { "slide", "set sliding mode", OFFSET(sliding), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, FLAGS },
57
+    { "mode", "set channel display mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=COMBINED}, COMBINED, NB_MODES-1, FLAGS, "mode" },
58
+    { "combined", "combined mode", 0, AV_OPT_TYPE_CONST, {.i64=COMBINED}, 0, 0, FLAGS, "mode" },
59
+    { "separate", "separate mode", 0, AV_OPT_TYPE_CONST, {.i64=SEPARATE}, 0, 0, FLAGS, "mode" },
60
+    { "color", "set channel coloring", OFFSET(color_mode), AV_OPT_TYPE_INT, {.i64=CHANNEL}, CHANNEL, NB_CLMODES-1, FLAGS, "color" },
61
+    { "channel",   "separate color for each channel", 0, AV_OPT_TYPE_CONST, {.i64=CHANNEL},   0, 0, FLAGS, "color" },
62
+    { "intensity", "intensity based coloring",        0, AV_OPT_TYPE_CONST, {.i64=INTENSITY}, 0, 0, FLAGS, "color" },
63
+    { "scale", "set display scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64=SQRT}, LINEAR, NB_SCALES-1, FLAGS, "scale" },
64
+    { "sqrt", "square root", 0, AV_OPT_TYPE_CONST, {.i64=SQRT},   0, 0, FLAGS, "scale" },
65
+    { "cbrt", "cubic root",  0, AV_OPT_TYPE_CONST, {.i64=CBRT},   0, 0, FLAGS, "scale" },
66
+    { "log",  "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG},    0, 0, FLAGS, "scale" },
67
+    { "lin",  "linear",      0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, FLAGS, "scale" },
68
+    { "saturation", "color saturation multiplier", OFFSET(saturation), AV_OPT_TYPE_FLOAT, {.dbl = 1}, -10, 10, FLAGS },
57 69
     { NULL },
58 70
 };
59 71
 
60 72
 AVFILTER_DEFINE_CLASS(showspectrum);
61 73
 
74
+typedef struct {
75
+    float a, y, u, v;
76
+} intensity_color_table_item;
77
+static const intensity_color_table_item intensity_color_table[] =
78
+{
79
+    { 0, 0, 0, 0 },
80
+    { 0.13, .03587126228984074, .1573300977624594, -.02548747583751842 },
81
+    { 0.3, .1857228179456802, .1772436246393981, .1747555484041475 },
82
+    { 0.6, .2818498058365613, -.1593064119945782, .4713207455460892 },
83
+    { 0.73, .6583062117554781, -.3716070802232764, .2435275933125293 },
84
+    { 0.78, 0.763185357582429, -.4307467689263783, .1686649662231043 },
85
+    { 0.91, .9533636363636364, -.2045454545454546, .03313636363636363 },
86
+    { 1, 1, 0, 0 }
87
+};
88
+
62 89
 static av_cold int init(AVFilterContext *ctx, const char *args)
63 90
 {
64 91
     ShowSpectrumContext *showspectrum = ctx->priv;
... ...
@@ -76,8 +115,12 @@ static av_cold int init(AVFilterContext *ctx, const char *args)
76 76
 static av_cold void uninit(AVFilterContext *ctx)
77 77
 {
78 78
     ShowSpectrumContext *showspectrum = ctx->priv;
79
+    int i;
79 80
 
81
+    av_freep(&showspectrum->combine_buffer);
80 82
     av_rdft_end(showspectrum->rdft);
83
+    for (i = 0; i < showspectrum->nb_display_channels; i++)
84
+        av_freep(&showspectrum->rdft_data[i]);
81 85
     av_freep(&showspectrum->rdft_data);
82 86
     av_freep(&showspectrum->window_func_lut);
83 87
     avfilter_unref_bufferp(&showspectrum->outpicref);
... ...
@@ -90,7 +133,7 @@ static int query_formats(AVFilterContext *ctx)
90 90
     AVFilterLink *inlink = ctx->inputs[0];
91 91
     AVFilterLink *outlink = ctx->outputs[0];
92 92
     static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE };
93
-    static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_RGB24, AV_PIX_FMT_NONE };
93
+    static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_NONE };
94 94
 
95 95
     /* set input audio formats */
96 96
     formats = ff_make_format_list(sample_fmts);
... ...
@@ -120,19 +163,23 @@ static int query_formats(AVFilterContext *ctx)
120 120
 static int config_output(AVFilterLink *outlink)
121 121
 {
122 122
     AVFilterContext *ctx = outlink->src;
123
+    AVFilterLink *inlink = ctx->inputs[0];
123 124
     ShowSpectrumContext *showspectrum = ctx->priv;
124
-    int i, rdft_bits, win_size;
125
+    int i, rdft_bits, win_size, h;
125 126
 
126 127
     outlink->w = showspectrum->w;
127 128
     outlink->h = showspectrum->h;
128 129
 
130
+    h = (showspectrum->mode == COMBINED) ? outlink->h : outlink->h / inlink->channels;
131
+    showspectrum->channel_height = h;
132
+
129 133
     /* RDFT window size (precision) according to the requested output frame height */
130
-    for (rdft_bits = 1; 1<<rdft_bits < 2*outlink->h; rdft_bits++);
134
+    for (rdft_bits = 1; 1 << rdft_bits < 2 * h; rdft_bits++);
131 135
     win_size = 1 << rdft_bits;
132 136
 
133 137
     /* (re-)configuration if the video output changed (or first init) */
134 138
     if (rdft_bits != showspectrum->rdft_bits) {
135
-        size_t rdft_size;
139
+        size_t rdft_size, rdft_listsize;
136 140
         AVFilterBufferRef *outpicref;
137 141
 
138 142
         av_rdft_end(showspectrum->rdft);
... ...
@@ -142,12 +189,25 @@ static int config_output(AVFilterLink *outlink)
142 142
         /* RDFT buffers: x2 for each (display) channel buffer.
143 143
          * Note: we use free and malloc instead of a realloc-like function to
144 144
          * make sure the buffer is aligned in memory for the FFT functions. */
145
+        for (i = 0; i < showspectrum->nb_display_channels; i++)
146
+            av_freep(&showspectrum->rdft_data[i]);
145 147
         av_freep(&showspectrum->rdft_data);
146
-        if (av_size_mult(sizeof(*showspectrum->rdft_data), 2 * win_size, &rdft_size) < 0)
148
+        showspectrum->nb_display_channels = inlink->channels;
149
+
150
+        if (av_size_mult(sizeof(*showspectrum->rdft_data),
151
+                         showspectrum->nb_display_channels, &rdft_listsize) < 0)
152
+            return AVERROR(EINVAL);
153
+        if (av_size_mult(sizeof(**showspectrum->rdft_data),
154
+                         win_size, &rdft_size) < 0)
147 155
             return AVERROR(EINVAL);
148
-        showspectrum->rdft_data = av_malloc(rdft_size);
156
+        showspectrum->rdft_data = av_malloc(rdft_listsize);
149 157
         if (!showspectrum->rdft_data)
150 158
             return AVERROR(ENOMEM);
159
+        for (i = 0; i < showspectrum->nb_display_channels; i++) {
160
+            showspectrum->rdft_data[i] = av_malloc(rdft_size);
161
+            if (!showspectrum->rdft_data[i])
162
+                return AVERROR(ENOMEM);
163
+        }
151 164
         showspectrum->filled = 0;
152 165
 
153 166
         /* pre-calc windowing function (hann here) */
... ...
@@ -173,6 +233,10 @@ static int config_output(AVFilterLink *outlink)
173 173
     if (showspectrum->xpos >= outlink->w)
174 174
         showspectrum->xpos = 0;
175 175
 
176
+    showspectrum->combine_buffer =
177
+        av_realloc_f(showspectrum->combine_buffer, outlink->h * 3,
178
+                     sizeof(*showspectrum->combine_buffer));
179
+
176 180
     av_log(ctx, AV_LOG_VERBOSE, "s:%dx%d RDFT window size:%d\n",
177 181
            showspectrum->w, showspectrum->h, win_size);
178 182
     return 0;
... ...
@@ -213,62 +277,180 @@ static int plot_spectrum_column(AVFilterLink *inlink, AVFilterBufferRef *insampl
213 213
     AVFilterLink *outlink = ctx->outputs[0];
214 214
     ShowSpectrumContext *showspectrum = ctx->priv;
215 215
     AVFilterBufferRef *outpicref = showspectrum->outpicref;
216
-    const int nb_channels = av_get_channel_layout_nb_channels(insamples->audio->channel_layout);
217 216
 
218 217
     /* nb_freq contains the power of two superior or equal to the output image
219 218
      * height (or half the RDFT window size) */
220 219
     const int nb_freq = 1 << (showspectrum->rdft_bits - 1);
221 220
     const int win_size = nb_freq << 1;
221
+    const double w = 1. / (sqrt(nb_freq) * 32768.);
222 222
 
223
-    int ch, n, y;
224
-    FFTSample *data[2];
225
-    const int nb_display_channels = FFMIN(nb_channels, 2);
223
+    int ch, plane, n, y;
226 224
     const int start = showspectrum->filled;
227 225
     const int add_samples = FFMIN(win_size - start, nb_samples);
228 226
 
229 227
     /* fill RDFT input with the number of samples available */
230
-    for (ch = 0; ch < nb_display_channels; ch++) {
228
+    for (ch = 0; ch < showspectrum->nb_display_channels; ch++) {
231 229
         const int16_t *p = (int16_t *)insamples->extended_data[ch];
232 230
 
233 231
         p += showspectrum->consumed;
234
-        data[ch] = showspectrum->rdft_data + win_size * ch; // select channel buffer
235 232
         for (n = 0; n < add_samples; n++)
236
-            data[ch][start + n] = p[n] * showspectrum->window_func_lut[start + n];
233
+            showspectrum->rdft_data[ch][start + n] = p[n] * showspectrum->window_func_lut[start + n];
237 234
     }
238 235
     showspectrum->filled += add_samples;
239 236
 
240 237
     /* complete RDFT window size? */
241 238
     if (showspectrum->filled == win_size) {
242 239
 
240
+        /* channel height */
241
+        int h = showspectrum->channel_height;
242
+
243 243
         /* run RDFT on each samples set */
244
-        for (ch = 0; ch < nb_display_channels; ch++)
245
-            av_rdft_calc(showspectrum->rdft, data[ch]);
244
+        for (ch = 0; ch < showspectrum->nb_display_channels; ch++)
245
+            av_rdft_calc(showspectrum->rdft, showspectrum->rdft_data[ch]);
246 246
 
247 247
         /* fill a new spectrum column */
248
-#define RE(ch) data[ch][2*y + 0]
249
-#define IM(ch) data[ch][2*y + 1]
250
-#define MAGNITUDE(re, im) sqrt((re)*(re) + (im)*(im))
248
+#define RE(y, ch) showspectrum->rdft_data[ch][2 * y + 0]
249
+#define IM(y, ch) showspectrum->rdft_data[ch][2 * y + 1]
250
+#define MAGNITUDE(y, ch) hypot(RE(y, ch), IM(y, ch))
251 251
 
252
+        /* initialize buffer for combining to black */
252 253
         for (y = 0; y < outlink->h; y++) {
253
-            // FIXME: bin[0] contains first and last bins
254
-            uint8_t *p = outpicref->data[0] + (outlink->h - y - 1) * outpicref->linesize[0];
255
-            const double w = 1. / sqrt(nb_freq);
256
-            int a =                           sqrt(w * MAGNITUDE(RE(0), IM(0)));
257
-            int b = nb_display_channels > 1 ? sqrt(w * MAGNITUDE(RE(1), IM(1))) : a;
258
-
259
-            if (showspectrum->sliding) {
260
-                memmove(p, p + 3, (outlink->w - 1) * 3);
261
-                p += (outlink->w - 1) * 3;
262
-            } else {
263
-                p += showspectrum->xpos * 3;
254
+            showspectrum->combine_buffer[3 * y    ] = 0;
255
+            showspectrum->combine_buffer[3 * y + 1] = 127.5;
256
+            showspectrum->combine_buffer[3 * y + 2] = 127.5;
257
+        }
258
+
259
+        for (ch = 0; ch < showspectrum->nb_display_channels; ch++) {
260
+            float yf, uf, vf;
261
+
262
+            /* decide color range */
263
+            switch (showspectrum->mode) {
264
+            case COMBINED:
265
+                // reduce range by channel count
266
+                yf = 256.0f / showspectrum->nb_display_channels;
267
+                switch (showspectrum->color_mode) {
268
+                case INTENSITY:
269
+                    uf = yf;
270
+                    vf = yf;
271
+                    break;
272
+                case CHANNEL:
273
+                    /* adjust saturation for mixed UV coloring */
274
+                    /* this factor is correct for infinite channels, an approximation otherwise */
275
+                    uf = yf * M_PI;
276
+                    vf = yf * M_PI;
277
+                    break;
278
+                default:
279
+                    av_assert0(0);
280
+                }
281
+                break;
282
+            case SEPARATE:
283
+                // full range
284
+                yf = 256.0f;
285
+                uf = 256.0f;
286
+                vf = 256.0f;
287
+                break;
288
+            default:
289
+                av_assert0(0);
264 290
             }
265 291
 
266
-            a = FFMIN(a, 255);
267
-            b = FFMIN(b, 255);
268
-            p[0] = a;
269
-            p[1] = b;
270
-            p[2] = (a + b) / 2;
292
+            if (showspectrum->color_mode == CHANNEL) {
293
+                if (showspectrum->nb_display_channels > 1) {
294
+                    uf *= 0.5 * sin((2 * M_PI * ch) / showspectrum->nb_display_channels);
295
+                    vf *= 0.5 * cos((2 * M_PI * ch) / showspectrum->nb_display_channels);
296
+                } else {
297
+                    uf = 0.0f;
298
+                    vf = 0.0f;
299
+                }
300
+            }
301
+            uf *= showspectrum->saturation;
302
+            vf *= showspectrum->saturation;
303
+
304
+            /* draw the channel */
305
+            for (y = 0; y < h; y++) {
306
+                int row = (showspectrum->mode == COMBINED) ? y : ch * h + y;
307
+                float *out = &showspectrum->combine_buffer[3 * row];
308
+
309
+                /* get magnitude */
310
+                float a = w * MAGNITUDE(y, ch);
311
+
312
+                /* apply scale */
313
+                switch (showspectrum->scale) {
314
+                case LINEAR:
315
+                    break;
316
+                case SQRT:
317
+                    a = sqrt(a);
318
+                    break;
319
+                case CBRT:
320
+                    a = cbrt(a);
321
+                    break;
322
+                case LOG:
323
+                    a = 1 - log(FFMAX(FFMIN(1, a), 1e-6)) / log(1e-6); // zero = -120dBFS
324
+                    break;
325
+                default:
326
+                    av_assert0(0);
327
+                }
328
+
329
+                if (showspectrum->color_mode == INTENSITY) {
330
+                    float y, u, v;
331
+                    int i;
332
+
333
+                    for (i = 1; i < sizeof(intensity_color_table) / sizeof(*intensity_color_table) - 1; i++)
334
+                        if (intensity_color_table[i].a >= a)
335
+                            break;
336
+                    // i now is the first item >= the color
337
+                    // now we know to interpolate between item i - 1 and i
338
+                    if (a <= intensity_color_table[i - 1].a) {
339
+                        y = intensity_color_table[i - 1].y;
340
+                        u = intensity_color_table[i - 1].u;
341
+                        v = intensity_color_table[i - 1].v;
342
+                    } else if (a >= intensity_color_table[i].a) {
343
+                        y = intensity_color_table[i].y;
344
+                        u = intensity_color_table[i].u;
345
+                        v = intensity_color_table[i].v;
346
+                    } else {
347
+                        float start = intensity_color_table[i - 1].a;
348
+                        float end = intensity_color_table[i].a;
349
+                        float lerpfrac = (a - start) / (end - start);
350
+                        y = intensity_color_table[i - 1].y * (1.0f - lerpfrac)
351
+                          + intensity_color_table[i].y * lerpfrac;
352
+                        u = intensity_color_table[i - 1].u * (1.0f - lerpfrac)
353
+                          + intensity_color_table[i].u * lerpfrac;
354
+                        v = intensity_color_table[i - 1].v * (1.0f - lerpfrac)
355
+                          + intensity_color_table[i].v * lerpfrac;
356
+                    }
357
+
358
+                    out[0] += y * yf;
359
+                    out[1] += u * uf;
360
+                    out[2] += v * vf;
361
+                } else {
362
+                    out[0] += a * yf;
363
+                    out[1] += a * uf;
364
+                    out[2] += a * vf;
365
+                }
366
+            }
271 367
         }
368
+
369
+        /* copy to output */
370
+        if (showspectrum->sliding) {
371
+            for (plane = 0; plane < 3; plane++) {
372
+                for (y = 0; y < outlink->h; y++) {
373
+                    uint8_t *p = outpicref->data[plane] +
374
+                                 y * outpicref->linesize[plane];
375
+                    memmove(p, p + 1, outlink->w - 1);
376
+                }
377
+            }
378
+            showspectrum->xpos = outlink->w - 1;
379
+        }
380
+        for (plane = 0; plane < 3; plane++) {
381
+            uint8_t *p = outpicref->data[plane] +
382
+                         (outlink->h - 1) * outpicref->linesize[plane] +
383
+                         showspectrum->xpos;
384
+            for (y = 0; y < outlink->h; y++) {
385
+                *p = rint(FFMAX(0, FFMIN(showspectrum->combine_buffer[3 * y + plane], 255)));
386
+                p -= outpicref->linesize[plane];
387
+            }
388
+        }
389
+
272 390
         outpicref->pts = insamples->pts +
273 391
             av_rescale_q(showspectrum->consumed,
274 392
                          (AVRational){ 1, inlink->sample_rate },