avf_showspectrum.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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/channel_layout.h"
  28. #include "libavutil/opt.h"
  29. #include "avfilter.h"
  30. #include "internal.h"
  31. typedef struct {
  32. const AVClass *class;
  33. int w, h;
  34. AVFilterBufferRef *outpicref;
  35. int req_fullfilled;
  36. int sliding; ///< 1 if sliding mode, 0 otherwise
  37. int xpos; ///< x position (current column)
  38. RDFTContext *rdft; ///< Real Discrete Fourier Transform context
  39. int rdft_bits; ///< number of bits (RDFT window size = 1<<rdft_bits)
  40. FFTSample *rdft_data; ///< bins holder for each (displayed) channels
  41. int filled; ///< number of samples (per channel) filled in current rdft_buffer
  42. int consumed; ///< number of samples (per channel) consumed from the input frame
  43. float *window_func_lut; ///< Window function LUT
  44. } ShowSpectrumContext;
  45. #define OFFSET(x) offsetof(ShowSpectrumContext, x)
  46. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  47. static const AVOption showspectrum_options[] = {
  48. { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x480"}, 0, 0, FLAGS },
  49. { "s", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "640x480"}, 0, 0, FLAGS },
  50. { "slide", "set sliding mode", OFFSET(sliding), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, FLAGS },
  51. { NULL },
  52. };
  53. AVFILTER_DEFINE_CLASS(showspectrum);
  54. static av_cold int init(AVFilterContext *ctx, const char *args)
  55. {
  56. ShowSpectrumContext *showspectrum = ctx->priv;
  57. int err;
  58. showspectrum->class = &showspectrum_class;
  59. av_opt_set_defaults(showspectrum);
  60. if ((err = av_set_options_string(showspectrum, args, "=", ":")) < 0)
  61. return err;
  62. return 0;
  63. }
  64. static av_cold void uninit(AVFilterContext *ctx)
  65. {
  66. ShowSpectrumContext *showspectrum = ctx->priv;
  67. av_rdft_end(showspectrum->rdft);
  68. av_freep(&showspectrum->rdft_data);
  69. av_freep(&showspectrum->window_func_lut);
  70. avfilter_unref_bufferp(&showspectrum->outpicref);
  71. }
  72. static int query_formats(AVFilterContext *ctx)
  73. {
  74. AVFilterFormats *formats = NULL;
  75. AVFilterChannelLayouts *layouts = NULL;
  76. AVFilterLink *inlink = ctx->inputs[0];
  77. AVFilterLink *outlink = ctx->outputs[0];
  78. static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE };
  79. static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_RGB24, AV_PIX_FMT_NONE };
  80. /* set input audio formats */
  81. formats = ff_make_format_list(sample_fmts);
  82. if (!formats)
  83. return AVERROR(ENOMEM);
  84. ff_formats_ref(formats, &inlink->out_formats);
  85. layouts = ff_all_channel_layouts();
  86. if (!layouts)
  87. return AVERROR(ENOMEM);
  88. ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts);
  89. formats = ff_all_samplerates();
  90. if (!formats)
  91. return AVERROR(ENOMEM);
  92. ff_formats_ref(formats, &inlink->out_samplerates);
  93. /* set output video format */
  94. formats = ff_make_format_list(pix_fmts);
  95. if (!formats)
  96. return AVERROR(ENOMEM);
  97. ff_formats_ref(formats, &outlink->in_formats);
  98. return 0;
  99. }
  100. static int config_output(AVFilterLink *outlink)
  101. {
  102. AVFilterContext *ctx = outlink->src;
  103. ShowSpectrumContext *showspectrum = ctx->priv;
  104. int i, rdft_bits, win_size;
  105. outlink->w = showspectrum->w;
  106. outlink->h = showspectrum->h;
  107. /* RDFT window size (precision) according to the requested output frame height */
  108. for (rdft_bits = 1; 1<<rdft_bits < 2*outlink->h; rdft_bits++);
  109. win_size = 1 << rdft_bits;
  110. /* (re-)configuration if the video output changed (or first init) */
  111. if (rdft_bits != showspectrum->rdft_bits) {
  112. size_t rdft_size;
  113. AVFilterBufferRef *outpicref;
  114. av_rdft_end(showspectrum->rdft);
  115. showspectrum->rdft = av_rdft_init(rdft_bits, DFT_R2C);
  116. showspectrum->rdft_bits = rdft_bits;
  117. /* RDFT buffers: x2 for each (display) channel buffer.
  118. * Note: we use free and malloc instead of a realloc-like function to
  119. * make sure the buffer is aligned in memory for the FFT functions. */
  120. av_freep(&showspectrum->rdft_data);
  121. if (av_size_mult(sizeof(*showspectrum->rdft_data), 2 * win_size, &rdft_size) < 0)
  122. return AVERROR(EINVAL);
  123. showspectrum->rdft_data = av_malloc(rdft_size);
  124. if (!showspectrum->rdft_data)
  125. return AVERROR(ENOMEM);
  126. showspectrum->filled = 0;
  127. /* pre-calc windowing function (hann here) */
  128. showspectrum->window_func_lut =
  129. av_realloc_f(showspectrum->window_func_lut, win_size,
  130. sizeof(*showspectrum->window_func_lut));
  131. if (!showspectrum->window_func_lut)
  132. return AVERROR(ENOMEM);
  133. for (i = 0; i < win_size; i++)
  134. showspectrum->window_func_lut[i] = .5f * (1 - cos(2*M_PI*i / (win_size-1)));
  135. /* prepare the initial picref buffer (black frame) */
  136. avfilter_unref_bufferp(&showspectrum->outpicref);
  137. showspectrum->outpicref = outpicref =
  138. ff_get_video_buffer(outlink, AV_PERM_WRITE|AV_PERM_PRESERVE|AV_PERM_REUSE2,
  139. outlink->w, outlink->h);
  140. if (!outpicref)
  141. return AVERROR(ENOMEM);
  142. outlink->sample_aspect_ratio = (AVRational){1,1};
  143. memset(outpicref->data[0], 0, outlink->h * outpicref->linesize[0]);
  144. }
  145. if (showspectrum->xpos >= outlink->w)
  146. showspectrum->xpos = 0;
  147. av_log(ctx, AV_LOG_VERBOSE, "s:%dx%d RDFT window size:%d\n",
  148. showspectrum->w, showspectrum->h, win_size);
  149. return 0;
  150. }
  151. inline static void push_frame(AVFilterLink *outlink)
  152. {
  153. ShowSpectrumContext *showspectrum = outlink->src->priv;
  154. showspectrum->xpos++;
  155. if (showspectrum->xpos >= outlink->w)
  156. showspectrum->xpos = 0;
  157. showspectrum->filled = 0;
  158. showspectrum->req_fullfilled = 1;
  159. ff_filter_frame(outlink, avfilter_ref_buffer(showspectrum->outpicref, ~AV_PERM_WRITE));
  160. }
  161. static int request_frame(AVFilterLink *outlink)
  162. {
  163. ShowSpectrumContext *showspectrum = outlink->src->priv;
  164. AVFilterLink *inlink = outlink->src->inputs[0];
  165. int ret;
  166. showspectrum->req_fullfilled = 0;
  167. do {
  168. ret = ff_request_frame(inlink);
  169. } while (!showspectrum->req_fullfilled && ret >= 0);
  170. if (ret == AVERROR_EOF && showspectrum->outpicref)
  171. push_frame(outlink);
  172. return ret;
  173. }
  174. static int plot_spectrum_column(AVFilterLink *inlink, AVFilterBufferRef *insamples, int nb_samples)
  175. {
  176. AVFilterContext *ctx = inlink->dst;
  177. AVFilterLink *outlink = ctx->outputs[0];
  178. ShowSpectrumContext *showspectrum = ctx->priv;
  179. AVFilterBufferRef *outpicref = showspectrum->outpicref;
  180. const int nb_channels = av_get_channel_layout_nb_channels(insamples->audio->channel_layout);
  181. /* nb_freq contains the power of two superior or equal to the output image
  182. * height (or half the RDFT window size) */
  183. const int nb_freq = 1 << (showspectrum->rdft_bits - 1);
  184. const int win_size = nb_freq << 1;
  185. int ch, n, y;
  186. FFTSample *data[2];
  187. const int nb_display_channels = FFMIN(nb_channels, 2);
  188. const int start = showspectrum->filled;
  189. const int add_samples = FFMIN(win_size - start, nb_samples);
  190. /* fill RDFT input with the number of samples available */
  191. for (ch = 0; ch < nb_display_channels; ch++) {
  192. const int16_t *p = (int16_t *)insamples->extended_data[ch];
  193. p += showspectrum->consumed;
  194. data[ch] = showspectrum->rdft_data + win_size * ch; // select channel buffer
  195. for (n = 0; n < add_samples; n++)
  196. data[ch][start + n] = p[n] * showspectrum->window_func_lut[start + n];
  197. }
  198. showspectrum->filled += add_samples;
  199. /* complete RDFT window size? */
  200. if (showspectrum->filled == win_size) {
  201. /* run RDFT on each samples set */
  202. for (ch = 0; ch < nb_display_channels; ch++)
  203. av_rdft_calc(showspectrum->rdft, data[ch]);
  204. /* fill a new spectrum column */
  205. #define RE(ch) data[ch][2*y + 0]
  206. #define IM(ch) data[ch][2*y + 1]
  207. #define MAGNITUDE(re, im) sqrt((re)*(re) + (im)*(im))
  208. for (y = 0; y < outlink->h; y++) {
  209. // FIXME: bin[0] contains first and last bins
  210. uint8_t *p = outpicref->data[0] + (outlink->h - y - 1) * outpicref->linesize[0];
  211. const double w = 1. / sqrt(nb_freq);
  212. int a = sqrt(w * MAGNITUDE(RE(0), IM(0)));
  213. int b = nb_display_channels > 1 ? sqrt(w * MAGNITUDE(RE(1), IM(1))) : a;
  214. if (showspectrum->sliding) {
  215. memmove(p, p + 3, (outlink->w - 1) * 3);
  216. p += (outlink->w - 1) * 3;
  217. } else {
  218. p += showspectrum->xpos * 3;
  219. }
  220. a = FFMIN(a, 255);
  221. b = FFMIN(b, 255);
  222. p[0] = a;
  223. p[1] = b;
  224. p[2] = (a + b) / 2;
  225. }
  226. outpicref->pts = insamples->pts +
  227. av_rescale_q(showspectrum->consumed,
  228. (AVRational){ 1, inlink->sample_rate },
  229. outlink->time_base);
  230. push_frame(outlink);
  231. }
  232. return add_samples;
  233. }
  234. static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *insamples)
  235. {
  236. AVFilterContext *ctx = inlink->dst;
  237. ShowSpectrumContext *showspectrum = ctx->priv;
  238. int left_samples = insamples->audio->nb_samples;
  239. showspectrum->consumed = 0;
  240. while (left_samples) {
  241. const int added_samples = plot_spectrum_column(inlink, insamples, left_samples);
  242. showspectrum->consumed += added_samples;
  243. left_samples -= added_samples;
  244. }
  245. avfilter_unref_buffer(insamples);
  246. return 0;
  247. }
  248. static const AVFilterPad showspectrum_inputs[] = {
  249. {
  250. .name = "default",
  251. .type = AVMEDIA_TYPE_AUDIO,
  252. .filter_frame = filter_frame,
  253. .min_perms = AV_PERM_READ,
  254. },
  255. { NULL }
  256. };
  257. static const AVFilterPad showspectrum_outputs[] = {
  258. {
  259. .name = "default",
  260. .type = AVMEDIA_TYPE_VIDEO,
  261. .config_props = config_output,
  262. .request_frame = request_frame,
  263. },
  264. { NULL }
  265. };
  266. AVFilter avfilter_avf_showspectrum = {
  267. .name = "showspectrum",
  268. .description = NULL_IF_CONFIG_SMALL("Convert input audio to a spectrum video output."),
  269. .init = init,
  270. .uninit = uninit,
  271. .query_formats = query_formats,
  272. .priv_size = sizeof(ShowSpectrumContext),
  273. .inputs = showspectrum_inputs,
  274. .outputs = showspectrum_outputs,
  275. .priv_class = &showspectrum_class,
  276. };