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.

501 lines
19KB

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