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.

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