You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

518 lines
19KB

  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. * @file
  23. * audio to spectrum (video) transmedia filter, based on ffplay rdft showmode
  24. * (by Michael Niedermayer) and lavfi/avf_showwaves (by Stefano Sabatini).
  25. */
  26. #include <math.h>
  27. #include "libavcodec/avfft.h"
  28. #include "libavutil/avassert.h"
  29. #include "libavutil/channel_layout.h"
  30. #include "libavutil/opt.h"
  31. #include "avfilter.h"
  32. #include "internal.h"
  33. enum DisplayMode { COMBINED, SEPARATE, NB_MODES };
  34. enum DisplayScale { LINEAR, SQRT, CBRT, LOG, NB_SCALES };
  35. enum ColorMode { CHANNEL, INTENSITY, NB_CLMODES };
  36. enum WindowFunc { WFUNC_NONE, WFUNC_HANN, WFUNC_HAMMING, WFUNC_BLACKMAN, NB_WFUNC };
  37. enum SlideMode { REPLACE, SCROLL, FULLFRAME, NB_SLIDES };
  38. typedef struct {
  39. const AVClass *class;
  40. int w, h;
  41. AVFrame *outpicref;
  42. int nb_display_channels;
  43. int channel_height;
  44. int sliding; ///< 1 if sliding mode, 0 otherwise
  45. int mode; ///< channel display mode
  46. int color_mode; ///< display color scheme
  47. int scale;
  48. float saturation; ///< color saturation multiplier
  49. int xpos; ///< x position (current column)
  50. RDFTContext *rdft; ///< Real Discrete Fourier Transform context
  51. int rdft_bits; ///< number of bits (RDFT window size = 1<<rdft_bits)
  52. FFTSample **rdft_data; ///< bins holder for each (displayed) channels
  53. float *window_func_lut; ///< Window function LUT
  54. int win_func;
  55. float *combine_buffer; ///< color combining buffer (3 * h items)
  56. } ShowSpectrumContext;
  57. #define OFFSET(x) offsetof(ShowSpectrumContext, x)
  58. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  59. static const AVOption showspectrum_options[] = {
  60. { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
  61. { "s", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
  62. { "slide", "set sliding mode", OFFSET(sliding), AV_OPT_TYPE_INT, {.i64 = 0}, 0, NB_SLIDES, FLAGS, "slide" },
  63. { "replace", "replace old columns with new", 0, AV_OPT_TYPE_CONST, {.i64=REPLACE}, 0, 0, FLAGS, "slide" },
  64. { "scroll", "scroll from right to left", 0, AV_OPT_TYPE_CONST, {.i64=SCROLL}, 0, 0, FLAGS, "slide" },
  65. { "fullframe", "return full frames", 0, AV_OPT_TYPE_CONST, {.i64=FULLFRAME}, 0, 0, FLAGS, "slide" },
  66. { "mode", "set channel display mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=COMBINED}, COMBINED, NB_MODES-1, FLAGS, "mode" },
  67. { "combined", "combined mode", 0, AV_OPT_TYPE_CONST, {.i64=COMBINED}, 0, 0, FLAGS, "mode" },
  68. { "separate", "separate mode", 0, AV_OPT_TYPE_CONST, {.i64=SEPARATE}, 0, 0, FLAGS, "mode" },
  69. { "color", "set channel coloring", OFFSET(color_mode), AV_OPT_TYPE_INT, {.i64=CHANNEL}, CHANNEL, NB_CLMODES-1, FLAGS, "color" },
  70. { "channel", "separate color for each channel", 0, AV_OPT_TYPE_CONST, {.i64=CHANNEL}, 0, 0, FLAGS, "color" },
  71. { "intensity", "intensity based coloring", 0, AV_OPT_TYPE_CONST, {.i64=INTENSITY}, 0, 0, FLAGS, "color" },
  72. { "scale", "set display scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64=SQRT}, LINEAR, NB_SCALES-1, FLAGS, "scale" },
  73. { "sqrt", "square root", 0, AV_OPT_TYPE_CONST, {.i64=SQRT}, 0, 0, FLAGS, "scale" },
  74. { "cbrt", "cubic root", 0, AV_OPT_TYPE_CONST, {.i64=CBRT}, 0, 0, FLAGS, "scale" },
  75. { "log", "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG}, 0, 0, FLAGS, "scale" },
  76. { "lin", "linear", 0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, FLAGS, "scale" },
  77. { "saturation", "color saturation multiplier", OFFSET(saturation), AV_OPT_TYPE_FLOAT, {.dbl = 1}, -10, 10, FLAGS },
  78. { "win_func", "set window function", OFFSET(win_func), AV_OPT_TYPE_INT, {.i64 = WFUNC_HANN}, 0, NB_WFUNC-1, FLAGS, "win_func" },
  79. { "hann", "Hann window", 0, AV_OPT_TYPE_CONST, {.i64 = WFUNC_HANN}, 0, 0, FLAGS, "win_func" },
  80. { "hamming", "Hamming window", 0, AV_OPT_TYPE_CONST, {.i64 = WFUNC_HAMMING}, 0, 0, FLAGS, "win_func" },
  81. { "blackman", "Blackman window", 0, AV_OPT_TYPE_CONST, {.i64 = WFUNC_BLACKMAN}, 0, 0, FLAGS, "win_func" },
  82. { NULL }
  83. };
  84. AVFILTER_DEFINE_CLASS(showspectrum);
  85. static const struct {
  86. float a, y, u, v;
  87. } intensity_color_table[] = {
  88. { 0, 0, 0, 0 },
  89. { 0.13, .03587126228984074, .1573300977624594, -.02548747583751842 },
  90. { 0.30, .18572281794568020, .1772436246393981, .17475554840414750 },
  91. { 0.60, .28184980583656130, -.1593064119945782, .47132074554608920 },
  92. { 0.73, .65830621175547810, -.3716070802232764, .24352759331252930 },
  93. { 0.78, .76318535758242900, -.4307467689263783, .16866496622310430 },
  94. { 0.91, .95336363636363640, -.2045454545454546, .03313636363636363 },
  95. { 1, 1, 0, 0 }
  96. };
  97. static av_cold void uninit(AVFilterContext *ctx)
  98. {
  99. ShowSpectrumContext *s = ctx->priv;
  100. int i;
  101. av_freep(&s->combine_buffer);
  102. av_rdft_end(s->rdft);
  103. for (i = 0; i < s->nb_display_channels; i++)
  104. av_freep(&s->rdft_data[i]);
  105. av_freep(&s->rdft_data);
  106. av_freep(&s->window_func_lut);
  107. av_frame_free(&s->outpicref);
  108. }
  109. static int query_formats(AVFilterContext *ctx)
  110. {
  111. AVFilterFormats *formats = NULL;
  112. AVFilterChannelLayouts *layouts = NULL;
  113. AVFilterLink *inlink = ctx->inputs[0];
  114. AVFilterLink *outlink = ctx->outputs[0];
  115. static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE };
  116. static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_NONE };
  117. /* set input audio formats */
  118. formats = ff_make_format_list(sample_fmts);
  119. if (!formats)
  120. return AVERROR(ENOMEM);
  121. ff_formats_ref(formats, &inlink->out_formats);
  122. layouts = ff_all_channel_layouts();
  123. if (!layouts)
  124. return AVERROR(ENOMEM);
  125. ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts);
  126. formats = ff_all_samplerates();
  127. if (!formats)
  128. return AVERROR(ENOMEM);
  129. ff_formats_ref(formats, &inlink->out_samplerates);
  130. /* set output video format */
  131. formats = ff_make_format_list(pix_fmts);
  132. if (!formats)
  133. return AVERROR(ENOMEM);
  134. ff_formats_ref(formats, &outlink->in_formats);
  135. return 0;
  136. }
  137. static int config_output(AVFilterLink *outlink)
  138. {
  139. AVFilterContext *ctx = outlink->src;
  140. AVFilterLink *inlink = ctx->inputs[0];
  141. ShowSpectrumContext *s = ctx->priv;
  142. int i, rdft_bits, win_size, h;
  143. outlink->w = s->w;
  144. outlink->h = s->h;
  145. h = (s->mode == COMBINED) ? outlink->h : outlink->h / inlink->channels;
  146. s->channel_height = h;
  147. /* RDFT window size (precision) according to the requested output frame height */
  148. for (rdft_bits = 1; 1 << rdft_bits < 2 * h; rdft_bits++);
  149. win_size = 1 << rdft_bits;
  150. /* (re-)configuration if the video output changed (or first init) */
  151. if (rdft_bits != s->rdft_bits) {
  152. AVFrame *outpicref;
  153. av_rdft_end(s->rdft);
  154. s->rdft = av_rdft_init(rdft_bits, DFT_R2C);
  155. if (!s->rdft) {
  156. av_log(ctx, AV_LOG_ERROR, "Unable to create RDFT context. "
  157. "The window size might be too high.\n");
  158. return AVERROR(EINVAL);
  159. }
  160. s->rdft_bits = rdft_bits;
  161. /* RDFT buffers: x2 for each (display) channel buffer.
  162. * Note: we use free and malloc instead of a realloc-like function to
  163. * make sure the buffer is aligned in memory for the FFT functions. */
  164. for (i = 0; i < s->nb_display_channels; i++)
  165. av_freep(&s->rdft_data[i]);
  166. av_freep(&s->rdft_data);
  167. s->nb_display_channels = inlink->channels;
  168. s->rdft_data = av_calloc(s->nb_display_channels, sizeof(*s->rdft_data));
  169. if (!s->rdft_data)
  170. return AVERROR(ENOMEM);
  171. for (i = 0; i < s->nb_display_channels; i++) {
  172. s->rdft_data[i] = av_calloc(win_size, sizeof(**s->rdft_data));
  173. if (!s->rdft_data[i])
  174. return AVERROR(ENOMEM);
  175. }
  176. /* pre-calc windowing function */
  177. s->window_func_lut =
  178. av_realloc_f(s->window_func_lut, win_size,
  179. sizeof(*s->window_func_lut));
  180. if (!s->window_func_lut)
  181. return AVERROR(ENOMEM);
  182. switch (s->win_func) {
  183. case WFUNC_NONE:
  184. for (i = 0; i < win_size; i++)
  185. s->window_func_lut[i] = 1.;
  186. break;
  187. case WFUNC_HANN:
  188. for (i = 0; i < win_size; i++)
  189. s->window_func_lut[i] = .5f * (1 - cos(2*M_PI*i / (win_size-1)));
  190. break;
  191. case WFUNC_HAMMING:
  192. for (i = 0; i < win_size; i++)
  193. s->window_func_lut[i] = .54f - .46f * cos(2*M_PI*i / (win_size-1));
  194. break;
  195. case WFUNC_BLACKMAN: {
  196. for (i = 0; i < win_size; i++)
  197. s->window_func_lut[i] = .42f - .5f*cos(2*M_PI*i / (win_size-1)) + .08f*cos(4*M_PI*i / (win_size-1));
  198. break;
  199. }
  200. default:
  201. av_assert0(0);
  202. }
  203. /* prepare the initial picref buffer (black frame) */
  204. av_frame_free(&s->outpicref);
  205. s->outpicref = outpicref =
  206. ff_get_video_buffer(outlink, outlink->w, outlink->h);
  207. if (!outpicref)
  208. return AVERROR(ENOMEM);
  209. outlink->sample_aspect_ratio = (AVRational){1,1};
  210. for (i = 0; i < outlink->h; i++) {
  211. memset(outpicref->data[0] + i * outpicref->linesize[0], 0, outlink->w);
  212. memset(outpicref->data[1] + i * outpicref->linesize[1], 128, outlink->w);
  213. memset(outpicref->data[2] + i * outpicref->linesize[2], 128, outlink->w);
  214. }
  215. }
  216. if (s->xpos >= outlink->w)
  217. s->xpos = 0;
  218. outlink->frame_rate = av_make_q(inlink->sample_rate, win_size);
  219. if (s->sliding == FULLFRAME)
  220. outlink->frame_rate.den *= outlink->w;
  221. inlink->min_samples = inlink->max_samples = inlink->partial_buf_size =
  222. win_size;
  223. s->combine_buffer =
  224. av_realloc_f(s->combine_buffer, outlink->h * 3,
  225. sizeof(*s->combine_buffer));
  226. av_log(ctx, AV_LOG_VERBOSE, "s:%dx%d RDFT window size:%d\n",
  227. s->w, s->h, win_size);
  228. return 0;
  229. }
  230. static int request_frame(AVFilterLink *outlink)
  231. {
  232. ShowSpectrumContext *s = outlink->src->priv;
  233. AVFilterLink *inlink = outlink->src->inputs[0];
  234. unsigned i;
  235. int ret;
  236. ret = ff_request_frame(inlink);
  237. if (ret == AVERROR_EOF && s->sliding == FULLFRAME && s->xpos > 0 &&
  238. s->outpicref) {
  239. for (i = 0; i < outlink->h; i++) {
  240. memset(s->outpicref->data[0] + i * s->outpicref->linesize[0] + s->xpos, 0, outlink->w - s->xpos);
  241. memset(s->outpicref->data[1] + i * s->outpicref->linesize[1] + s->xpos, 128, outlink->w - s->xpos);
  242. memset(s->outpicref->data[2] + i * s->outpicref->linesize[2] + s->xpos, 128, outlink->w - s->xpos);
  243. }
  244. ret = ff_filter_frame(outlink, s->outpicref);
  245. s->outpicref = NULL;
  246. }
  247. return ret;
  248. }
  249. static int plot_spectrum_column(AVFilterLink *inlink, AVFrame *insamples)
  250. {
  251. int ret;
  252. AVFilterContext *ctx = inlink->dst;
  253. AVFilterLink *outlink = ctx->outputs[0];
  254. ShowSpectrumContext *s = ctx->priv;
  255. AVFrame *outpicref = s->outpicref;
  256. /* nb_freq contains the power of two superior or equal to the output image
  257. * height (or half the RDFT window size) */
  258. const int nb_freq = 1 << (s->rdft_bits - 1);
  259. const int win_size = nb_freq << 1;
  260. const double w = 1. / (sqrt(nb_freq) * 32768.);
  261. int h = s->channel_height;
  262. int ch, plane, n, y;
  263. av_assert0(insamples->nb_samples == win_size);
  264. /* fill RDFT input with the number of samples available */
  265. for (ch = 0; ch < s->nb_display_channels; ch++) {
  266. const int16_t *p = (int16_t *)insamples->extended_data[ch];
  267. for (n = 0; n < win_size; n++)
  268. s->rdft_data[ch][n] = p[n] * s->window_func_lut[n];
  269. }
  270. /* run RDFT on each samples set */
  271. for (ch = 0; ch < s->nb_display_channels; ch++)
  272. av_rdft_calc(s->rdft, s->rdft_data[ch]);
  273. /* fill a new spectrum column */
  274. #define RE(y, ch) s->rdft_data[ch][2 * (y) + 0]
  275. #define IM(y, ch) s->rdft_data[ch][2 * (y) + 1]
  276. #define MAGNITUDE(y, ch) hypot(RE(y, ch), IM(y, ch))
  277. /* initialize buffer for combining to black */
  278. for (y = 0; y < outlink->h; y++) {
  279. s->combine_buffer[3 * y ] = 0;
  280. s->combine_buffer[3 * y + 1] = 127.5;
  281. s->combine_buffer[3 * y + 2] = 127.5;
  282. }
  283. for (ch = 0; ch < s->nb_display_channels; ch++) {
  284. float yf, uf, vf;
  285. /* decide color range */
  286. switch (s->mode) {
  287. case COMBINED:
  288. // reduce range by channel count
  289. yf = 256.0f / s->nb_display_channels;
  290. switch (s->color_mode) {
  291. case INTENSITY:
  292. uf = yf;
  293. vf = yf;
  294. break;
  295. case CHANNEL:
  296. /* adjust saturation for mixed UV coloring */
  297. /* this factor is correct for infinite channels, an approximation otherwise */
  298. uf = yf * M_PI;
  299. vf = yf * M_PI;
  300. break;
  301. default:
  302. av_assert0(0);
  303. }
  304. break;
  305. case SEPARATE:
  306. // full range
  307. yf = 256.0f;
  308. uf = 256.0f;
  309. vf = 256.0f;
  310. break;
  311. default:
  312. av_assert0(0);
  313. }
  314. if (s->color_mode == CHANNEL) {
  315. if (s->nb_display_channels > 1) {
  316. uf *= 0.5 * sin((2 * M_PI * ch) / s->nb_display_channels);
  317. vf *= 0.5 * cos((2 * M_PI * ch) / s->nb_display_channels);
  318. } else {
  319. uf = 0.0f;
  320. vf = 0.0f;
  321. }
  322. }
  323. uf *= s->saturation;
  324. vf *= s->saturation;
  325. /* draw the channel */
  326. for (y = 0; y < h; y++) {
  327. int row = (s->mode == COMBINED) ? y : ch * h + y;
  328. float *out = &s->combine_buffer[3 * row];
  329. /* get magnitude */
  330. float a = w * MAGNITUDE(y, ch);
  331. /* apply scale */
  332. switch (s->scale) {
  333. case LINEAR:
  334. break;
  335. case SQRT:
  336. a = sqrt(a);
  337. break;
  338. case CBRT:
  339. a = cbrt(a);
  340. break;
  341. case LOG:
  342. a = 1 - log(FFMAX(FFMIN(1, a), 1e-6)) / log(1e-6); // zero = -120dBFS
  343. break;
  344. default:
  345. av_assert0(0);
  346. }
  347. if (s->color_mode == INTENSITY) {
  348. float y, u, v;
  349. int i;
  350. for (i = 1; i < sizeof(intensity_color_table) / sizeof(*intensity_color_table) - 1; i++)
  351. if (intensity_color_table[i].a >= a)
  352. break;
  353. // i now is the first item >= the color
  354. // now we know to interpolate between item i - 1 and i
  355. if (a <= intensity_color_table[i - 1].a) {
  356. y = intensity_color_table[i - 1].y;
  357. u = intensity_color_table[i - 1].u;
  358. v = intensity_color_table[i - 1].v;
  359. } else if (a >= intensity_color_table[i].a) {
  360. y = intensity_color_table[i].y;
  361. u = intensity_color_table[i].u;
  362. v = intensity_color_table[i].v;
  363. } else {
  364. float start = intensity_color_table[i - 1].a;
  365. float end = intensity_color_table[i].a;
  366. float lerpfrac = (a - start) / (end - start);
  367. y = intensity_color_table[i - 1].y * (1.0f - lerpfrac)
  368. + intensity_color_table[i].y * lerpfrac;
  369. u = intensity_color_table[i - 1].u * (1.0f - lerpfrac)
  370. + intensity_color_table[i].u * lerpfrac;
  371. v = intensity_color_table[i - 1].v * (1.0f - lerpfrac)
  372. + intensity_color_table[i].v * lerpfrac;
  373. }
  374. out[0] += y * yf;
  375. out[1] += u * uf;
  376. out[2] += v * vf;
  377. } else {
  378. out[0] += a * yf;
  379. out[1] += a * uf;
  380. out[2] += a * vf;
  381. }
  382. }
  383. }
  384. /* copy to output */
  385. if (s->sliding == SCROLL) {
  386. for (plane = 0; plane < 3; plane++) {
  387. for (y = 0; y < outlink->h; y++) {
  388. uint8_t *p = outpicref->data[plane] +
  389. y * outpicref->linesize[plane];
  390. memmove(p, p + 1, outlink->w - 1);
  391. }
  392. }
  393. s->xpos = outlink->w - 1;
  394. }
  395. for (plane = 0; plane < 3; plane++) {
  396. uint8_t *p = outpicref->data[plane] +
  397. (outlink->h - 1) * outpicref->linesize[plane] +
  398. s->xpos;
  399. for (y = 0; y < outlink->h; y++) {
  400. *p = rint(FFMAX(0, FFMIN(s->combine_buffer[3 * y + plane], 255)));
  401. p -= outpicref->linesize[plane];
  402. }
  403. }
  404. if (s->sliding != FULLFRAME || s->xpos == 0)
  405. outpicref->pts = insamples->pts;
  406. s->xpos++;
  407. if (s->xpos >= outlink->w)
  408. s->xpos = 0;
  409. if (s->sliding != FULLFRAME || s->xpos == 0) {
  410. ret = ff_filter_frame(outlink, av_frame_clone(s->outpicref));
  411. if (ret < 0)
  412. return ret;
  413. }
  414. return win_size;
  415. }
  416. static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
  417. {
  418. AVFilterContext *ctx = inlink->dst;
  419. ShowSpectrumContext *s = ctx->priv;
  420. unsigned win_size = 1 << s->rdft_bits;
  421. int ret = 0;
  422. av_assert0(insamples->nb_samples <= win_size);
  423. if (insamples->nb_samples == win_size)
  424. ret = plot_spectrum_column(inlink, insamples);
  425. av_frame_free(&insamples);
  426. return ret;
  427. }
  428. static const AVFilterPad showspectrum_inputs[] = {
  429. {
  430. .name = "default",
  431. .type = AVMEDIA_TYPE_AUDIO,
  432. .filter_frame = filter_frame,
  433. },
  434. { NULL }
  435. };
  436. static const AVFilterPad showspectrum_outputs[] = {
  437. {
  438. .name = "default",
  439. .type = AVMEDIA_TYPE_VIDEO,
  440. .config_props = config_output,
  441. .request_frame = request_frame,
  442. },
  443. { NULL }
  444. };
  445. AVFilter ff_avf_showspectrum = {
  446. .name = "showspectrum",
  447. .description = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output."),
  448. .uninit = uninit,
  449. .query_formats = query_formats,
  450. .priv_size = sizeof(ShowSpectrumContext),
  451. .inputs = showspectrum_inputs,
  452. .outputs = showspectrum_outputs,
  453. .priv_class = &showspectrum_class,
  454. };