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.

510 lines
20KB

  1. /*
  2. * Copyright (c) 2012 Clément Bœsch
  3. *
  4. * This file is part of FFmpeg.
  5. *
  6. * FFmpeg is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * FFmpeg is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with FFmpeg; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. /**
  21. * @file
  22. * audio to spectrum (video) transmedia filter, based on ffplay rdft showmode
  23. * (by Michael Niedermayer) and lavfi/avf_showwaves (by Stefano Sabatini).
  24. */
  25. #include <math.h>
  26. #include "libavcodec/avfft.h"
  27. #include "libavutil/avassert.h"
  28. #include "libavutil/channel_layout.h"
  29. #include "libavutil/opt.h"
  30. #include "avfilter.h"
  31. #include "internal.h"
  32. enum DisplayMode { COMBINED, SEPARATE, NB_MODES };
  33. enum DisplayScale { LINEAR, SQRT, CBRT, LOG, NB_SCALES };
  34. enum ColorMode { CHANNEL, INTENSITY, NB_CLMODES };
  35. typedef struct {
  36. const AVClass *class;
  37. int w, h;
  38. AVFilterBufferRef *outpicref;
  39. int req_fullfilled;
  40. int nb_display_channels;
  41. int channel_height;
  42. int sliding; ///< 1 if sliding mode, 0 otherwise
  43. enum DisplayMode mode; ///< channel display mode
  44. enum ColorMode color_mode; ///< display color scheme
  45. enum DisplayScale scale;
  46. float saturation; ///< color saturation multiplier
  47. int xpos; ///< x position (current column)
  48. RDFTContext *rdft; ///< Real Discrete Fourier Transform context
  49. int rdft_bits; ///< number of bits (RDFT window size = 1<<rdft_bits)
  50. FFTSample **rdft_data; ///< bins holder for each (displayed) channels
  51. int filled; ///< number of samples (per channel) filled in current rdft_buffer
  52. int consumed; ///< number of samples (per channel) consumed from the input frame
  53. float *window_func_lut; ///< Window function LUT
  54. float *combine_buffer; ///< color combining buffer (3 * h items)
  55. } ShowSpectrumContext;
  56. #define OFFSET(x) offsetof(ShowSpectrumContext, x)
  57. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  58. static const AVOption showspectrum_options[] = {
  59. { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
  60. { "s", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x512"}, 0, 0, FLAGS },
  61. { "slide", "set sliding mode", OFFSET(sliding), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, FLAGS },
  62. { "mode", "set channel display mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=COMBINED}, COMBINED, NB_MODES-1, FLAGS, "mode" },
  63. { "combined", "combined mode", 0, AV_OPT_TYPE_CONST, {.i64=COMBINED}, 0, 0, FLAGS, "mode" },
  64. { "separate", "separate mode", 0, AV_OPT_TYPE_CONST, {.i64=SEPARATE}, 0, 0, FLAGS, "mode" },
  65. { "color", "set channel coloring", OFFSET(color_mode), AV_OPT_TYPE_INT, {.i64=CHANNEL}, CHANNEL, NB_CLMODES-1, FLAGS, "color" },
  66. { "channel", "separate color for each channel", 0, AV_OPT_TYPE_CONST, {.i64=CHANNEL}, 0, 0, FLAGS, "color" },
  67. { "intensity", "intensity based coloring", 0, AV_OPT_TYPE_CONST, {.i64=INTENSITY}, 0, 0, FLAGS, "color" },
  68. { "scale", "set display scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64=SQRT}, LINEAR, NB_SCALES-1, FLAGS, "scale" },
  69. { "sqrt", "square root", 0, AV_OPT_TYPE_CONST, {.i64=SQRT}, 0, 0, FLAGS, "scale" },
  70. { "cbrt", "cubic root", 0, AV_OPT_TYPE_CONST, {.i64=CBRT}, 0, 0, FLAGS, "scale" },
  71. { "log", "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG}, 0, 0, FLAGS, "scale" },
  72. { "lin", "linear", 0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, FLAGS, "scale" },
  73. { "saturation", "color saturation multiplier", OFFSET(saturation), AV_OPT_TYPE_FLOAT, {.dbl = 1}, -10, 10, FLAGS },
  74. { NULL },
  75. };
  76. AVFILTER_DEFINE_CLASS(showspectrum);
  77. static const struct {
  78. float a, y, u, v;
  79. } intensity_color_table[] = {
  80. { 0, 0, 0, 0 },
  81. { 0.13, .03587126228984074, .1573300977624594, -.02548747583751842 },
  82. { 0.30, .18572281794568020, .1772436246393981, .17475554840414750 },
  83. { 0.60, .28184980583656130, -.1593064119945782, .47132074554608920 },
  84. { 0.73, .65830621175547810, -.3716070802232764, .24352759331252930 },
  85. { 0.78, .76318535758242900, -.4307467689263783, .16866496622310430 },
  86. { 0.91, .95336363636363640, -.2045454545454546, .03313636363636363 },
  87. { 1, 1, 0, 0 }
  88. };
  89. static av_cold int init(AVFilterContext *ctx, const char *args)
  90. {
  91. ShowSpectrumContext *showspectrum = ctx->priv;
  92. int err;
  93. showspectrum->class = &showspectrum_class;
  94. av_opt_set_defaults(showspectrum);
  95. if ((err = av_set_options_string(showspectrum, args, "=", ":")) < 0)
  96. return err;
  97. return 0;
  98. }
  99. static av_cold void uninit(AVFilterContext *ctx)
  100. {
  101. ShowSpectrumContext *showspectrum = ctx->priv;
  102. int i;
  103. av_freep(&showspectrum->combine_buffer);
  104. av_rdft_end(showspectrum->rdft);
  105. for (i = 0; i < showspectrum->nb_display_channels; i++)
  106. av_freep(&showspectrum->rdft_data[i]);
  107. av_freep(&showspectrum->rdft_data);
  108. av_freep(&showspectrum->window_func_lut);
  109. avfilter_unref_bufferp(&showspectrum->outpicref);
  110. }
  111. static int query_formats(AVFilterContext *ctx)
  112. {
  113. AVFilterFormats *formats = NULL;
  114. AVFilterChannelLayouts *layouts = NULL;
  115. AVFilterLink *inlink = ctx->inputs[0];
  116. AVFilterLink *outlink = ctx->outputs[0];
  117. static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE };
  118. static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_NONE };
  119. /* set input audio formats */
  120. formats = ff_make_format_list(sample_fmts);
  121. if (!formats)
  122. return AVERROR(ENOMEM);
  123. ff_formats_ref(formats, &inlink->out_formats);
  124. layouts = ff_all_channel_layouts();
  125. if (!layouts)
  126. return AVERROR(ENOMEM);
  127. ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts);
  128. formats = ff_all_samplerates();
  129. if (!formats)
  130. return AVERROR(ENOMEM);
  131. ff_formats_ref(formats, &inlink->out_samplerates);
  132. /* set output video format */
  133. formats = ff_make_format_list(pix_fmts);
  134. if (!formats)
  135. return AVERROR(ENOMEM);
  136. ff_formats_ref(formats, &outlink->in_formats);
  137. return 0;
  138. }
  139. static int config_output(AVFilterLink *outlink)
  140. {
  141. AVFilterContext *ctx = outlink->src;
  142. AVFilterLink *inlink = ctx->inputs[0];
  143. ShowSpectrumContext *showspectrum = ctx->priv;
  144. int i, rdft_bits, win_size, h;
  145. outlink->w = showspectrum->w;
  146. outlink->h = showspectrum->h;
  147. h = (showspectrum->mode == COMBINED) ? outlink->h : outlink->h / inlink->channels;
  148. showspectrum->channel_height = h;
  149. /* RDFT window size (precision) according to the requested output frame height */
  150. for (rdft_bits = 1; 1 << rdft_bits < 2 * h; rdft_bits++);
  151. win_size = 1 << rdft_bits;
  152. /* (re-)configuration if the video output changed (or first init) */
  153. if (rdft_bits != showspectrum->rdft_bits) {
  154. size_t rdft_size, rdft_listsize;
  155. AVFilterBufferRef *outpicref;
  156. av_rdft_end(showspectrum->rdft);
  157. showspectrum->rdft = av_rdft_init(rdft_bits, DFT_R2C);
  158. showspectrum->rdft_bits = rdft_bits;
  159. /* RDFT buffers: x2 for each (display) channel buffer.
  160. * Note: we use free and malloc instead of a realloc-like function to
  161. * make sure the buffer is aligned in memory for the FFT functions. */
  162. for (i = 0; i < showspectrum->nb_display_channels; i++)
  163. av_freep(&showspectrum->rdft_data[i]);
  164. av_freep(&showspectrum->rdft_data);
  165. showspectrum->nb_display_channels = inlink->channels;
  166. if (av_size_mult(sizeof(*showspectrum->rdft_data),
  167. showspectrum->nb_display_channels, &rdft_listsize) < 0)
  168. return AVERROR(EINVAL);
  169. if (av_size_mult(sizeof(**showspectrum->rdft_data),
  170. win_size, &rdft_size) < 0)
  171. return AVERROR(EINVAL);
  172. showspectrum->rdft_data = av_malloc(rdft_listsize);
  173. if (!showspectrum->rdft_data)
  174. return AVERROR(ENOMEM);
  175. for (i = 0; i < showspectrum->nb_display_channels; i++) {
  176. showspectrum->rdft_data[i] = av_malloc(rdft_size);
  177. if (!showspectrum->rdft_data[i])
  178. return AVERROR(ENOMEM);
  179. }
  180. showspectrum->filled = 0;
  181. /* pre-calc windowing function (hann here) */
  182. showspectrum->window_func_lut =
  183. av_realloc_f(showspectrum->window_func_lut, win_size,
  184. sizeof(*showspectrum->window_func_lut));
  185. if (!showspectrum->window_func_lut)
  186. return AVERROR(ENOMEM);
  187. for (i = 0; i < win_size; i++)
  188. showspectrum->window_func_lut[i] = .5f * (1 - cos(2*M_PI*i / (win_size-1)));
  189. /* prepare the initial picref buffer (black frame) */
  190. avfilter_unref_bufferp(&showspectrum->outpicref);
  191. showspectrum->outpicref = outpicref =
  192. ff_get_video_buffer(outlink, AV_PERM_WRITE|AV_PERM_PRESERVE|AV_PERM_REUSE2,
  193. 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. }
  199. if (showspectrum->xpos >= outlink->w)
  200. showspectrum->xpos = 0;
  201. showspectrum->combine_buffer =
  202. av_realloc_f(showspectrum->combine_buffer, outlink->h * 3,
  203. sizeof(*showspectrum->combine_buffer));
  204. av_log(ctx, AV_LOG_VERBOSE, "s:%dx%d RDFT window size:%d\n",
  205. showspectrum->w, showspectrum->h, win_size);
  206. return 0;
  207. }
  208. inline static void push_frame(AVFilterLink *outlink)
  209. {
  210. ShowSpectrumContext *showspectrum = outlink->src->priv;
  211. showspectrum->xpos++;
  212. if (showspectrum->xpos >= outlink->w)
  213. showspectrum->xpos = 0;
  214. showspectrum->filled = 0;
  215. showspectrum->req_fullfilled = 1;
  216. ff_filter_frame(outlink, avfilter_ref_buffer(showspectrum->outpicref, ~AV_PERM_WRITE));
  217. }
  218. static int request_frame(AVFilterLink *outlink)
  219. {
  220. ShowSpectrumContext *showspectrum = outlink->src->priv;
  221. AVFilterLink *inlink = outlink->src->inputs[0];
  222. int ret;
  223. showspectrum->req_fullfilled = 0;
  224. do {
  225. ret = ff_request_frame(inlink);
  226. } while (!showspectrum->req_fullfilled && ret >= 0);
  227. if (ret == AVERROR_EOF && showspectrum->outpicref)
  228. push_frame(outlink);
  229. return ret;
  230. }
  231. static int plot_spectrum_column(AVFilterLink *inlink, AVFilterBufferRef *insamples, int nb_samples)
  232. {
  233. AVFilterContext *ctx = inlink->dst;
  234. AVFilterLink *outlink = ctx->outputs[0];
  235. ShowSpectrumContext *showspectrum = ctx->priv;
  236. AVFilterBufferRef *outpicref = showspectrum->outpicref;
  237. /* nb_freq contains the power of two superior or equal to the output image
  238. * height (or half the RDFT window size) */
  239. const int nb_freq = 1 << (showspectrum->rdft_bits - 1);
  240. const int win_size = nb_freq << 1;
  241. const double w = 1. / (sqrt(nb_freq) * 32768.);
  242. int ch, plane, n, y;
  243. const int start = showspectrum->filled;
  244. const int add_samples = FFMIN(win_size - start, nb_samples);
  245. /* fill RDFT input with the number of samples available */
  246. for (ch = 0; ch < showspectrum->nb_display_channels; ch++) {
  247. const int16_t *p = (int16_t *)insamples->extended_data[ch];
  248. p += showspectrum->consumed;
  249. for (n = 0; n < add_samples; n++)
  250. showspectrum->rdft_data[ch][start + n] = p[n] * showspectrum->window_func_lut[start + n];
  251. }
  252. showspectrum->filled += add_samples;
  253. /* complete RDFT window size? */
  254. if (showspectrum->filled == win_size) {
  255. /* channel height */
  256. int h = showspectrum->channel_height;
  257. /* run RDFT on each samples set */
  258. for (ch = 0; ch < showspectrum->nb_display_channels; ch++)
  259. av_rdft_calc(showspectrum->rdft, showspectrum->rdft_data[ch]);
  260. /* fill a new spectrum column */
  261. #define RE(y, ch) showspectrum->rdft_data[ch][2 * y + 0]
  262. #define IM(y, ch) showspectrum->rdft_data[ch][2 * y + 1]
  263. #define MAGNITUDE(y, ch) hypot(RE(y, ch), IM(y, ch))
  264. /* initialize buffer for combining to black */
  265. for (y = 0; y < outlink->h; y++) {
  266. showspectrum->combine_buffer[3 * y ] = 0;
  267. showspectrum->combine_buffer[3 * y + 1] = 127.5;
  268. showspectrum->combine_buffer[3 * y + 2] = 127.5;
  269. }
  270. for (ch = 0; ch < showspectrum->nb_display_channels; ch++) {
  271. float yf, uf, vf;
  272. /* decide color range */
  273. switch (showspectrum->mode) {
  274. case COMBINED:
  275. // reduce range by channel count
  276. yf = 256.0f / showspectrum->nb_display_channels;
  277. switch (showspectrum->color_mode) {
  278. case INTENSITY:
  279. uf = yf;
  280. vf = yf;
  281. break;
  282. case CHANNEL:
  283. /* adjust saturation for mixed UV coloring */
  284. /* this factor is correct for infinite channels, an approximation otherwise */
  285. uf = yf * M_PI;
  286. vf = yf * M_PI;
  287. break;
  288. default:
  289. av_assert0(0);
  290. }
  291. break;
  292. case SEPARATE:
  293. // full range
  294. yf = 256.0f;
  295. uf = 256.0f;
  296. vf = 256.0f;
  297. break;
  298. default:
  299. av_assert0(0);
  300. }
  301. if (showspectrum->color_mode == CHANNEL) {
  302. if (showspectrum->nb_display_channels > 1) {
  303. uf *= 0.5 * sin((2 * M_PI * ch) / showspectrum->nb_display_channels);
  304. vf *= 0.5 * cos((2 * M_PI * ch) / showspectrum->nb_display_channels);
  305. } else {
  306. uf = 0.0f;
  307. vf = 0.0f;
  308. }
  309. }
  310. uf *= showspectrum->saturation;
  311. vf *= showspectrum->saturation;
  312. /* draw the channel */
  313. for (y = 0; y < h; y++) {
  314. int row = (showspectrum->mode == COMBINED) ? y : ch * h + y;
  315. float *out = &showspectrum->combine_buffer[3 * row];
  316. /* get magnitude */
  317. float a = w * MAGNITUDE(y, ch);
  318. /* apply scale */
  319. switch (showspectrum->scale) {
  320. case LINEAR:
  321. break;
  322. case SQRT:
  323. a = sqrt(a);
  324. break;
  325. case CBRT:
  326. a = cbrt(a);
  327. break;
  328. case LOG:
  329. a = 1 - log(FFMAX(FFMIN(1, a), 1e-6)) / log(1e-6); // zero = -120dBFS
  330. break;
  331. default:
  332. av_assert0(0);
  333. }
  334. if (showspectrum->color_mode == INTENSITY) {
  335. float y, u, v;
  336. int i;
  337. for (i = 1; i < sizeof(intensity_color_table) / sizeof(*intensity_color_table) - 1; i++)
  338. if (intensity_color_table[i].a >= a)
  339. break;
  340. // i now is the first item >= the color
  341. // now we know to interpolate between item i - 1 and i
  342. if (a <= intensity_color_table[i - 1].a) {
  343. y = intensity_color_table[i - 1].y;
  344. u = intensity_color_table[i - 1].u;
  345. v = intensity_color_table[i - 1].v;
  346. } else if (a >= intensity_color_table[i].a) {
  347. y = intensity_color_table[i].y;
  348. u = intensity_color_table[i].u;
  349. v = intensity_color_table[i].v;
  350. } else {
  351. float start = intensity_color_table[i - 1].a;
  352. float end = intensity_color_table[i].a;
  353. float lerpfrac = (a - start) / (end - start);
  354. y = intensity_color_table[i - 1].y * (1.0f - lerpfrac)
  355. + intensity_color_table[i].y * lerpfrac;
  356. u = intensity_color_table[i - 1].u * (1.0f - lerpfrac)
  357. + intensity_color_table[i].u * lerpfrac;
  358. v = intensity_color_table[i - 1].v * (1.0f - lerpfrac)
  359. + intensity_color_table[i].v * lerpfrac;
  360. }
  361. out[0] += y * yf;
  362. out[1] += u * uf;
  363. out[2] += v * vf;
  364. } else {
  365. out[0] += a * yf;
  366. out[1] += a * uf;
  367. out[2] += a * vf;
  368. }
  369. }
  370. }
  371. /* copy to output */
  372. if (showspectrum->sliding) {
  373. for (plane = 0; plane < 3; plane++) {
  374. for (y = 0; y < outlink->h; y++) {
  375. uint8_t *p = outpicref->data[plane] +
  376. y * outpicref->linesize[plane];
  377. memmove(p, p + 1, outlink->w - 1);
  378. }
  379. }
  380. showspectrum->xpos = outlink->w - 1;
  381. }
  382. for (plane = 0; plane < 3; plane++) {
  383. uint8_t *p = outpicref->data[plane] +
  384. (outlink->h - 1) * outpicref->linesize[plane] +
  385. showspectrum->xpos;
  386. for (y = 0; y < outlink->h; y++) {
  387. *p = rint(FFMAX(0, FFMIN(showspectrum->combine_buffer[3 * y + plane], 255)));
  388. p -= outpicref->linesize[plane];
  389. }
  390. }
  391. outpicref->pts = insamples->pts +
  392. av_rescale_q(showspectrum->consumed,
  393. (AVRational){ 1, inlink->sample_rate },
  394. outlink->time_base);
  395. push_frame(outlink);
  396. }
  397. return add_samples;
  398. }
  399. static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *insamples)
  400. {
  401. AVFilterContext *ctx = inlink->dst;
  402. ShowSpectrumContext *showspectrum = ctx->priv;
  403. int left_samples = insamples->audio->nb_samples;
  404. showspectrum->consumed = 0;
  405. while (left_samples) {
  406. const int added_samples = plot_spectrum_column(inlink, insamples, left_samples);
  407. showspectrum->consumed += added_samples;
  408. left_samples -= added_samples;
  409. }
  410. avfilter_unref_buffer(insamples);
  411. return 0;
  412. }
  413. static const AVFilterPad showspectrum_inputs[] = {
  414. {
  415. .name = "default",
  416. .type = AVMEDIA_TYPE_AUDIO,
  417. .filter_frame = filter_frame,
  418. .min_perms = AV_PERM_READ,
  419. },
  420. { NULL }
  421. };
  422. static const AVFilterPad showspectrum_outputs[] = {
  423. {
  424. .name = "default",
  425. .type = AVMEDIA_TYPE_VIDEO,
  426. .config_props = config_output,
  427. .request_frame = request_frame,
  428. },
  429. { NULL }
  430. };
  431. AVFilter avfilter_avf_showspectrum = {
  432. .name = "showspectrum",
  433. .description = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output."),
  434. .init = init,
  435. .uninit = uninit,
  436. .query_formats = query_formats,
  437. .priv_size = sizeof(ShowSpectrumContext),
  438. .inputs = showspectrum_inputs,
  439. .outputs = showspectrum_outputs,
  440. .priv_class = &showspectrum_class,
  441. };