FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
avf_showspectrum.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2012-2013 Clément Bœsch
3  * Copyright (c) 2013 Rudolf Polzer <divverent@xonotic.org>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 /**
23  * @file
24  * audio to spectrum (video) transmedia filter, based on ffplay rdft showmode
25  * (by Michael Niedermayer) and lavfi/avf_showwaves (by Stefano Sabatini).
26  */
27 
28 #include <math.h>
29 
30 #include "libavcodec/avfft.h"
31 #include "libavutil/avassert.h"
33 #include "libavutil/opt.h"
34 #include "avfilter.h"
35 #include "internal.h"
36 
41 
42 typedef struct {
43  const AVClass *class;
44  int w, h;
49  int sliding; ///< 1 if sliding mode, 0 otherwise
50  enum DisplayMode mode; ///< channel display mode
51  enum ColorMode color_mode; ///< display color scheme
53  float saturation; ///< color saturation multiplier
54  int xpos; ///< x position (current column)
55  RDFTContext *rdft; ///< Real Discrete Fourier Transform context
56  int rdft_bits; ///< number of bits (RDFT window size = 1<<rdft_bits)
57  FFTSample **rdft_data; ///< bins holder for each (displayed) channels
58  int filled; ///< number of samples (per channel) filled in current rdft_buffer
59  int consumed; ///< number of samples (per channel) consumed from the input frame
60  float *window_func_lut; ///< Window function LUT
62  float *combine_buffer; ///< color combining buffer (3 * h items)
64 
65 #define OFFSET(x) offsetof(ShowSpectrumContext, x)
66 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
67 
68 static const AVOption showspectrum_options[] = {
69  { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
70  { "s", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
71  { "slide", "set sliding mode", OFFSET(sliding), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, FLAGS },
72  { "mode", "set channel display mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=COMBINED}, COMBINED, NB_MODES-1, FLAGS, "mode" },
73  { "combined", "combined mode", 0, AV_OPT_TYPE_CONST, {.i64=COMBINED}, 0, 0, FLAGS, "mode" },
74  { "separate", "separate mode", 0, AV_OPT_TYPE_CONST, {.i64=SEPARATE}, 0, 0, FLAGS, "mode" },
75  { "color", "set channel coloring", OFFSET(color_mode), AV_OPT_TYPE_INT, {.i64=CHANNEL}, CHANNEL, NB_CLMODES-1, FLAGS, "color" },
76  { "channel", "separate color for each channel", 0, AV_OPT_TYPE_CONST, {.i64=CHANNEL}, 0, 0, FLAGS, "color" },
77  { "intensity", "intensity based coloring", 0, AV_OPT_TYPE_CONST, {.i64=INTENSITY}, 0, 0, FLAGS, "color" },
78  { "scale", "set display scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64=SQRT}, LINEAR, NB_SCALES-1, FLAGS, "scale" },
79  { "sqrt", "square root", 0, AV_OPT_TYPE_CONST, {.i64=SQRT}, 0, 0, FLAGS, "scale" },
80  { "cbrt", "cubic root", 0, AV_OPT_TYPE_CONST, {.i64=CBRT}, 0, 0, FLAGS, "scale" },
81  { "log", "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG}, 0, 0, FLAGS, "scale" },
82  { "lin", "linear", 0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, FLAGS, "scale" },
83  { "saturation", "color saturation multiplier", OFFSET(saturation), AV_OPT_TYPE_FLOAT, {.dbl = 1}, -10, 10, FLAGS },
84  { "win_func", "set window function", OFFSET(win_func), AV_OPT_TYPE_INT, {.i64 = WFUNC_HANN}, 0, NB_WFUNC-1, FLAGS, "win_func" },
85  { "hann", "Hann window", 0, AV_OPT_TYPE_CONST, {.i64 = WFUNC_HANN}, 0, 0, FLAGS, "win_func" },
86  { "hamming", "Hamming window", 0, AV_OPT_TYPE_CONST, {.i64 = WFUNC_HAMMING}, 0, 0, FLAGS, "win_func" },
87  { "blackman", "Blackman window", 0, AV_OPT_TYPE_CONST, {.i64 = WFUNC_BLACKMAN}, 0, 0, FLAGS, "win_func" },
88  { NULL }
89 };
90 
91 AVFILTER_DEFINE_CLASS(showspectrum);
92 
93 static const struct {
94  float a, y, u, v;
96  { 0, 0, 0, 0 },
97  { 0.13, .03587126228984074, .1573300977624594, -.02548747583751842 },
98  { 0.30, .18572281794568020, .1772436246393981, .17475554840414750 },
99  { 0.60, .28184980583656130, -.1593064119945782, .47132074554608920 },
100  { 0.73, .65830621175547810, -.3716070802232764, .24352759331252930 },
101  { 0.78, .76318535758242900, -.4307467689263783, .16866496622310430 },
102  { 0.91, .95336363636363640, -.2045454545454546, .03313636363636363 },
103  { 1, 1, 0, 0 }
104 };
105 
106 static av_cold void uninit(AVFilterContext *ctx)
107 {
108  ShowSpectrumContext *s = ctx->priv;
109  int i;
110 
112  av_rdft_end(s->rdft);
113  for (i = 0; i < s->nb_display_channels; i++)
114  av_freep(&s->rdft_data[i]);
115  av_freep(&s->rdft_data);
118 }
119 
121 {
122  AVFilterFormats *formats = NULL;
124  AVFilterLink *inlink = ctx->inputs[0];
125  AVFilterLink *outlink = ctx->outputs[0];
127  static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_NONE };
128 
129  /* set input audio formats */
130  formats = ff_make_format_list(sample_fmts);
131  if (!formats)
132  return AVERROR(ENOMEM);
133  ff_formats_ref(formats, &inlink->out_formats);
134 
135  layouts = ff_all_channel_layouts();
136  if (!layouts)
137  return AVERROR(ENOMEM);
138  ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts);
139 
140  formats = ff_all_samplerates();
141  if (!formats)
142  return AVERROR(ENOMEM);
143  ff_formats_ref(formats, &inlink->out_samplerates);
144 
145  /* set output video format */
146  formats = ff_make_format_list(pix_fmts);
147  if (!formats)
148  return AVERROR(ENOMEM);
149  ff_formats_ref(formats, &outlink->in_formats);
150 
151  return 0;
152 }
153 
154 static int config_output(AVFilterLink *outlink)
155 {
156  AVFilterContext *ctx = outlink->src;
157  AVFilterLink *inlink = ctx->inputs[0];
158  ShowSpectrumContext *s = ctx->priv;
159  int i, rdft_bits, win_size, h;
160 
161  outlink->w = s->w;
162  outlink->h = s->h;
163 
164  h = (s->mode == COMBINED) ? outlink->h : outlink->h / inlink->channels;
165  s->channel_height = h;
166 
167  /* RDFT window size (precision) according to the requested output frame height */
168  for (rdft_bits = 1; 1 << rdft_bits < 2 * h; rdft_bits++);
169  win_size = 1 << rdft_bits;
170 
171  /* (re-)configuration if the video output changed (or first init) */
172  if (rdft_bits != s->rdft_bits) {
173  size_t rdft_size, rdft_listsize;
174  AVFrame *outpicref;
175 
176  av_rdft_end(s->rdft);
177  s->rdft = av_rdft_init(rdft_bits, DFT_R2C);
178  s->rdft_bits = rdft_bits;
179 
180  /* RDFT buffers: x2 for each (display) channel buffer.
181  * Note: we use free and malloc instead of a realloc-like function to
182  * make sure the buffer is aligned in memory for the FFT functions. */
183  for (i = 0; i < s->nb_display_channels; i++)
184  av_freep(&s->rdft_data[i]);
185  av_freep(&s->rdft_data);
186  s->nb_display_channels = inlink->channels;
187 
188  if (av_size_mult(sizeof(*s->rdft_data),
189  s->nb_display_channels, &rdft_listsize) < 0)
190  return AVERROR(EINVAL);
191  if (av_size_mult(sizeof(**s->rdft_data),
192  win_size, &rdft_size) < 0)
193  return AVERROR(EINVAL);
194  s->rdft_data = av_malloc(rdft_listsize);
195  if (!s->rdft_data)
196  return AVERROR(ENOMEM);
197  for (i = 0; i < s->nb_display_channels; i++) {
198  s->rdft_data[i] = av_malloc(rdft_size);
199  if (!s->rdft_data[i])
200  return AVERROR(ENOMEM);
201  }
202  s->filled = 0;
203 
204  /* pre-calc windowing function */
205  s->window_func_lut =
206  av_realloc_f(s->window_func_lut, win_size,
207  sizeof(*s->window_func_lut));
208  if (!s->window_func_lut)
209  return AVERROR(ENOMEM);
210  switch (s->win_func) {
211  case WFUNC_NONE:
212  for (i = 0; i < win_size; i++)
213  s->window_func_lut[i] = 1.;
214  break;
215  case WFUNC_HANN:
216  for (i = 0; i < win_size; i++)
217  s->window_func_lut[i] = .5f * (1 - cos(2*M_PI*i / (win_size-1)));
218  break;
219  case WFUNC_HAMMING:
220  for (i = 0; i < win_size; i++)
221  s->window_func_lut[i] = .54f - .46f * cos(2*M_PI*i / (win_size-1));
222  break;
223  case WFUNC_BLACKMAN: {
224  for (i = 0; i < win_size; i++)
225  s->window_func_lut[i] = .42f - .5f*cos(2*M_PI*i / (win_size-1)) + .08f*cos(4*M_PI*i / (win_size-1));
226  break;
227  }
228  default:
229  av_assert0(0);
230  }
231 
232  /* prepare the initial picref buffer (black frame) */
234  s->outpicref = outpicref =
235  ff_get_video_buffer(outlink, outlink->w, outlink->h);
236  if (!outpicref)
237  return AVERROR(ENOMEM);
238  outlink->sample_aspect_ratio = (AVRational){1,1};
239  for (i = 0; i < outlink->h; i++) {
240  memset(outpicref->data[0] + i * outpicref->linesize[0], 0, outlink->w);
241  memset(outpicref->data[1] + i * outpicref->linesize[1], 128, outlink->w);
242  memset(outpicref->data[2] + i * outpicref->linesize[2], 128, outlink->w);
243  }
244  }
245 
246  if (s->xpos >= outlink->w)
247  s->xpos = 0;
248 
249  s->combine_buffer =
250  av_realloc_f(s->combine_buffer, outlink->h * 3,
251  sizeof(*s->combine_buffer));
252 
253  av_log(ctx, AV_LOG_VERBOSE, "s:%dx%d RDFT window size:%d\n",
254  s->w, s->h, win_size);
255  return 0;
256 }
257 
258 inline static int push_frame(AVFilterLink *outlink)
259 {
260  ShowSpectrumContext *s = outlink->src->priv;
261 
262  s->xpos++;
263  if (s->xpos >= outlink->w)
264  s->xpos = 0;
265  s->filled = 0;
266  s->req_fullfilled = 1;
267 
268  return ff_filter_frame(outlink, av_frame_clone(s->outpicref));
269 }
270 
271 static int request_frame(AVFilterLink *outlink)
272 {
273  ShowSpectrumContext *s = outlink->src->priv;
274  AVFilterLink *inlink = outlink->src->inputs[0];
275  int ret;
276 
277  s->req_fullfilled = 0;
278  do {
279  ret = ff_request_frame(inlink);
280  } while (!s->req_fullfilled && ret >= 0);
281 
282  if (ret == AVERROR_EOF && s->outpicref)
283  push_frame(outlink);
284  return ret;
285 }
286 
287 static int plot_spectrum_column(AVFilterLink *inlink, AVFrame *insamples, int nb_samples)
288 {
289  int ret;
290  AVFilterContext *ctx = inlink->dst;
291  AVFilterLink *outlink = ctx->outputs[0];
292  ShowSpectrumContext *s = ctx->priv;
293  AVFrame *outpicref = s->outpicref;
294 
295  /* nb_freq contains the power of two superior or equal to the output image
296  * height (or half the RDFT window size) */
297  const int nb_freq = 1 << (s->rdft_bits - 1);
298  const int win_size = nb_freq << 1;
299  const double w = 1. / (sqrt(nb_freq) * 32768.);
300 
301  int ch, plane, n, y;
302  const int start = s->filled;
303  const int add_samples = FFMIN(win_size - start, nb_samples);
304 
305  /* fill RDFT input with the number of samples available */
306  for (ch = 0; ch < s->nb_display_channels; ch++) {
307  const int16_t *p = (int16_t *)insamples->extended_data[ch];
308 
309  p += s->consumed;
310  for (n = 0; n < add_samples; n++)
311  s->rdft_data[ch][start + n] = p[n] * s->window_func_lut[start + n];
312  }
313  s->filled += add_samples;
314 
315  /* complete RDFT window size? */
316  if (s->filled == win_size) {
317 
318  /* channel height */
319  int h = s->channel_height;
320 
321  /* run RDFT on each samples set */
322  for (ch = 0; ch < s->nb_display_channels; ch++)
323  av_rdft_calc(s->rdft, s->rdft_data[ch]);
324 
325  /* fill a new spectrum column */
326 #define RE(y, ch) s->rdft_data[ch][2 * (y) + 0]
327 #define IM(y, ch) s->rdft_data[ch][2 * (y) + 1]
328 #define MAGNITUDE(y, ch) hypot(RE(y, ch), IM(y, ch))
329 
330  /* initialize buffer for combining to black */
331  for (y = 0; y < outlink->h; y++) {
332  s->combine_buffer[3 * y ] = 0;
333  s->combine_buffer[3 * y + 1] = 127.5;
334  s->combine_buffer[3 * y + 2] = 127.5;
335  }
336 
337  for (ch = 0; ch < s->nb_display_channels; ch++) {
338  float yf, uf, vf;
339 
340  /* decide color range */
341  switch (s->mode) {
342  case COMBINED:
343  // reduce range by channel count
344  yf = 256.0f / s->nb_display_channels;
345  switch (s->color_mode) {
346  case INTENSITY:
347  uf = yf;
348  vf = yf;
349  break;
350  case CHANNEL:
351  /* adjust saturation for mixed UV coloring */
352  /* this factor is correct for infinite channels, an approximation otherwise */
353  uf = yf * M_PI;
354  vf = yf * M_PI;
355  break;
356  default:
357  av_assert0(0);
358  }
359  break;
360  case SEPARATE:
361  // full range
362  yf = 256.0f;
363  uf = 256.0f;
364  vf = 256.0f;
365  break;
366  default:
367  av_assert0(0);
368  }
369 
370  if (s->color_mode == CHANNEL) {
371  if (s->nb_display_channels > 1) {
372  uf *= 0.5 * sin((2 * M_PI * ch) / s->nb_display_channels);
373  vf *= 0.5 * cos((2 * M_PI * ch) / s->nb_display_channels);
374  } else {
375  uf = 0.0f;
376  vf = 0.0f;
377  }
378  }
379  uf *= s->saturation;
380  vf *= s->saturation;
381 
382  /* draw the channel */
383  for (y = 0; y < h; y++) {
384  int row = (s->mode == COMBINED) ? y : ch * h + y;
385  float *out = &s->combine_buffer[3 * row];
386 
387  /* get magnitude */
388  float a = w * MAGNITUDE(y, ch);
389 
390  /* apply scale */
391  switch (s->scale) {
392  case LINEAR:
393  break;
394  case SQRT:
395  a = sqrt(a);
396  break;
397  case CBRT:
398  a = cbrt(a);
399  break;
400  case LOG:
401  a = 1 - log(FFMAX(FFMIN(1, a), 1e-6)) / log(1e-6); // zero = -120dBFS
402  break;
403  default:
404  av_assert0(0);
405  }
406 
407  if (s->color_mode == INTENSITY) {
408  float y, u, v;
409  int i;
410 
411  for (i = 1; i < sizeof(intensity_color_table) / sizeof(*intensity_color_table) - 1; i++)
412  if (intensity_color_table[i].a >= a)
413  break;
414  // i now is the first item >= the color
415  // now we know to interpolate between item i - 1 and i
416  if (a <= intensity_color_table[i - 1].a) {
417  y = intensity_color_table[i - 1].y;
418  u = intensity_color_table[i - 1].u;
419  v = intensity_color_table[i - 1].v;
420  } else if (a >= intensity_color_table[i].a) {
421  y = intensity_color_table[i].y;
422  u = intensity_color_table[i].u;
423  v = intensity_color_table[i].v;
424  } else {
425  float start = intensity_color_table[i - 1].a;
426  float end = intensity_color_table[i].a;
427  float lerpfrac = (a - start) / (end - start);
428  y = intensity_color_table[i - 1].y * (1.0f - lerpfrac)
429  + intensity_color_table[i].y * lerpfrac;
430  u = intensity_color_table[i - 1].u * (1.0f - lerpfrac)
431  + intensity_color_table[i].u * lerpfrac;
432  v = intensity_color_table[i - 1].v * (1.0f - lerpfrac)
433  + intensity_color_table[i].v * lerpfrac;
434  }
435 
436  out[0] += y * yf;
437  out[1] += u * uf;
438  out[2] += v * vf;
439  } else {
440  out[0] += a * yf;
441  out[1] += a * uf;
442  out[2] += a * vf;
443  }
444  }
445  }
446 
447  /* copy to output */
448  if (s->sliding) {
449  for (plane = 0; plane < 3; plane++) {
450  for (y = 0; y < outlink->h; y++) {
451  uint8_t *p = outpicref->data[plane] +
452  y * outpicref->linesize[plane];
453  memmove(p, p + 1, outlink->w - 1);
454  }
455  }
456  s->xpos = outlink->w - 1;
457  }
458  for (plane = 0; plane < 3; plane++) {
459  uint8_t *p = outpicref->data[plane] +
460  (outlink->h - 1) * outpicref->linesize[plane] +
461  s->xpos;
462  for (y = 0; y < outlink->h; y++) {
463  *p = rint(FFMAX(0, FFMIN(s->combine_buffer[3 * y + plane], 255)));
464  p -= outpicref->linesize[plane];
465  }
466  }
467 
468  outpicref->pts = insamples->pts +
470  (AVRational){ 1, inlink->sample_rate },
471  outlink->time_base);
472  ret = push_frame(outlink);
473  if (ret < 0)
474  return ret;
475  }
476 
477  return add_samples;
478 }
479 
480 static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
481 {
482  AVFilterContext *ctx = inlink->dst;
483  ShowSpectrumContext *s = ctx->priv;
484  int ret = 0, left_samples = insamples->nb_samples;
485 
486  s->consumed = 0;
487  while (left_samples) {
488  int ret = plot_spectrum_column(inlink, insamples, left_samples);
489  if (ret < 0)
490  break;
491  s->consumed += ret;
492  left_samples -= ret;
493  }
494 
495  av_frame_free(&insamples);
496  return ret;
497 }
498 
500  {
501  .name = "default",
502  .type = AVMEDIA_TYPE_AUDIO,
503  .filter_frame = filter_frame,
504  },
505  { NULL }
506 };
507 
509  {
510  .name = "default",
511  .type = AVMEDIA_TYPE_VIDEO,
512  .config_props = config_output,
513  .request_frame = request_frame,
514  },
515  { NULL }
516 };
517 
519  .name = "showspectrum",
520  .description = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output."),
521  .uninit = uninit,
522  .query_formats = query_formats,
523  .priv_size = sizeof(ShowSpectrumContext),
524  .inputs = showspectrum_inputs,
525  .outputs = showspectrum_outputs,
526  .priv_class = &showspectrum_class,
527 };