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.

516 lines
20KB

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