avf_showspectrum.c 11 KB

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