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.

511 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 void 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. 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. AVFilterContext *ctx = inlink->dst;
  236. AVFilterLink *outlink = ctx->outputs[0];
  237. ShowSpectrumContext *showspectrum = ctx->priv;
  238. AVFrame *outpicref = showspectrum->outpicref;
  239. /* nb_freq contains the power of two superior or equal to the output image
  240. * height (or half the RDFT window size) */
  241. const int nb_freq = 1 << (showspectrum->rdft_bits - 1);
  242. const int win_size = nb_freq << 1;
  243. const double w = 1. / (sqrt(nb_freq) * 32768.);
  244. int ch, plane, n, y;
  245. const int start = showspectrum->filled;
  246. const int add_samples = FFMIN(win_size - start, nb_samples);
  247. /* fill RDFT input with the number of samples available */
  248. for (ch = 0; ch < showspectrum->nb_display_channels; ch++) {
  249. const int16_t *p = (int16_t *)insamples->extended_data[ch];
  250. p += showspectrum->consumed;
  251. for (n = 0; n < add_samples; n++)
  252. showspectrum->rdft_data[ch][start + n] = p[n] * showspectrum->window_func_lut[start + n];
  253. }
  254. showspectrum->filled += add_samples;
  255. /* complete RDFT window size? */
  256. if (showspectrum->filled == win_size) {
  257. /* channel height */
  258. int h = showspectrum->channel_height;
  259. /* run RDFT on each samples set */
  260. for (ch = 0; ch < showspectrum->nb_display_channels; ch++)
  261. av_rdft_calc(showspectrum->rdft, showspectrum->rdft_data[ch]);
  262. /* fill a new spectrum column */
  263. #define RE(y, ch) showspectrum->rdft_data[ch][2 * y + 0]
  264. #define IM(y, ch) showspectrum->rdft_data[ch][2 * y + 1]
  265. #define MAGNITUDE(y, ch) hypot(RE(y, ch), IM(y, ch))
  266. /* initialize buffer for combining to black */
  267. for (y = 0; y < outlink->h; y++) {
  268. showspectrum->combine_buffer[3 * y ] = 0;
  269. showspectrum->combine_buffer[3 * y + 1] = 127.5;
  270. showspectrum->combine_buffer[3 * y + 2] = 127.5;
  271. }
  272. for (ch = 0; ch < showspectrum->nb_display_channels; ch++) {
  273. float yf, uf, vf;
  274. /* decide color range */
  275. switch (showspectrum->mode) {
  276. case COMBINED:
  277. // reduce range by channel count
  278. yf = 256.0f / showspectrum->nb_display_channels;
  279. switch (showspectrum->color_mode) {
  280. case INTENSITY:
  281. uf = yf;
  282. vf = yf;
  283. break;
  284. case CHANNEL:
  285. /* adjust saturation for mixed UV coloring */
  286. /* this factor is correct for infinite channels, an approximation otherwise */
  287. uf = yf * M_PI;
  288. vf = yf * M_PI;
  289. break;
  290. default:
  291. av_assert0(0);
  292. }
  293. break;
  294. case SEPARATE:
  295. // full range
  296. yf = 256.0f;
  297. uf = 256.0f;
  298. vf = 256.0f;
  299. break;
  300. default:
  301. av_assert0(0);
  302. }
  303. if (showspectrum->color_mode == CHANNEL) {
  304. if (showspectrum->nb_display_channels > 1) {
  305. uf *= 0.5 * sin((2 * M_PI * ch) / showspectrum->nb_display_channels);
  306. vf *= 0.5 * cos((2 * M_PI * ch) / showspectrum->nb_display_channels);
  307. } else {
  308. uf = 0.0f;
  309. vf = 0.0f;
  310. }
  311. }
  312. uf *= showspectrum->saturation;
  313. vf *= showspectrum->saturation;
  314. /* draw the channel */
  315. for (y = 0; y < h; y++) {
  316. int row = (showspectrum->mode == COMBINED) ? y : ch * h + y;
  317. float *out = &showspectrum->combine_buffer[3 * row];
  318. /* get magnitude */
  319. float a = w * MAGNITUDE(y, ch);
  320. /* apply scale */
  321. switch (showspectrum->scale) {
  322. case LINEAR:
  323. break;
  324. case SQRT:
  325. a = sqrt(a);
  326. break;
  327. case CBRT:
  328. a = cbrt(a);
  329. break;
  330. case LOG:
  331. a = 1 - log(FFMAX(FFMIN(1, a), 1e-6)) / log(1e-6); // zero = -120dBFS
  332. break;
  333. default:
  334. av_assert0(0);
  335. }
  336. if (showspectrum->color_mode == INTENSITY) {
  337. float y, u, v;
  338. int i;
  339. for (i = 1; i < sizeof(intensity_color_table) / sizeof(*intensity_color_table) - 1; i++)
  340. if (intensity_color_table[i].a >= a)
  341. break;
  342. // i now is the first item >= the color
  343. // now we know to interpolate between item i - 1 and i
  344. if (a <= intensity_color_table[i - 1].a) {
  345. y = intensity_color_table[i - 1].y;
  346. u = intensity_color_table[i - 1].u;
  347. v = intensity_color_table[i - 1].v;
  348. } else if (a >= intensity_color_table[i].a) {
  349. y = intensity_color_table[i].y;
  350. u = intensity_color_table[i].u;
  351. v = intensity_color_table[i].v;
  352. } else {
  353. float start = intensity_color_table[i - 1].a;
  354. float end = intensity_color_table[i].a;
  355. float lerpfrac = (a - start) / (end - start);
  356. y = intensity_color_table[i - 1].y * (1.0f - lerpfrac)
  357. + intensity_color_table[i].y * lerpfrac;
  358. u = intensity_color_table[i - 1].u * (1.0f - lerpfrac)
  359. + intensity_color_table[i].u * lerpfrac;
  360. v = intensity_color_table[i - 1].v * (1.0f - lerpfrac)
  361. + intensity_color_table[i].v * lerpfrac;
  362. }
  363. out[0] += y * yf;
  364. out[1] += u * uf;
  365. out[2] += v * vf;
  366. } else {
  367. out[0] += a * yf;
  368. out[1] += a * uf;
  369. out[2] += a * vf;
  370. }
  371. }
  372. }
  373. /* copy to output */
  374. if (showspectrum->sliding) {
  375. for (plane = 0; plane < 3; plane++) {
  376. for (y = 0; y < outlink->h; y++) {
  377. uint8_t *p = outpicref->data[plane] +
  378. y * outpicref->linesize[plane];
  379. memmove(p, p + 1, outlink->w - 1);
  380. }
  381. }
  382. showspectrum->xpos = outlink->w - 1;
  383. }
  384. for (plane = 0; plane < 3; plane++) {
  385. uint8_t *p = outpicref->data[plane] +
  386. (outlink->h - 1) * outpicref->linesize[plane] +
  387. showspectrum->xpos;
  388. for (y = 0; y < outlink->h; y++) {
  389. *p = rint(FFMAX(0, FFMIN(showspectrum->combine_buffer[3 * y + plane], 255)));
  390. p -= outpicref->linesize[plane];
  391. }
  392. }
  393. outpicref->pts = insamples->pts +
  394. av_rescale_q(showspectrum->consumed,
  395. (AVRational){ 1, inlink->sample_rate },
  396. outlink->time_base);
  397. push_frame(outlink);
  398. }
  399. return add_samples;
  400. }
  401. static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
  402. {
  403. AVFilterContext *ctx = inlink->dst;
  404. ShowSpectrumContext *showspectrum = ctx->priv;
  405. int left_samples = insamples->nb_samples;
  406. showspectrum->consumed = 0;
  407. while (left_samples) {
  408. const int added_samples = plot_spectrum_column(inlink, insamples, left_samples);
  409. showspectrum->consumed += added_samples;
  410. left_samples -= added_samples;
  411. }
  412. av_frame_free(&insamples);
  413. return 0;
  414. }
  415. static const AVFilterPad showspectrum_inputs[] = {
  416. {
  417. .name = "default",
  418. .type = AVMEDIA_TYPE_AUDIO,
  419. .filter_frame = filter_frame,
  420. },
  421. { NULL }
  422. };
  423. static const AVFilterPad showspectrum_outputs[] = {
  424. {
  425. .name = "default",
  426. .type = AVMEDIA_TYPE_VIDEO,
  427. .config_props = config_output,
  428. .request_frame = request_frame,
  429. },
  430. { NULL }
  431. };
  432. AVFilter avfilter_avf_showspectrum = {
  433. .name = "showspectrum",
  434. .description = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output."),
  435. .init = init,
  436. .uninit = uninit,
  437. .query_formats = query_formats,
  438. .priv_size = sizeof(ShowSpectrumContext),
  439. .inputs = showspectrum_inputs,
  440. .outputs = showspectrum_outputs,
  441. .priv_class = &showspectrum_class,
  442. };