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