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.

503 lines
18KB

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