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.

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