avf_showspectrum.c 20 KB

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