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