1 /*
2 * Copyright (c) 2019 Paul B Mahol
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 #include <float.h>
22 #include <math.h>
23
24 #include "libavcodec/avfft.h"
25 #include "libavutil/audio_fifo.h"
26 #include "libavutil/avassert.h"
27 #include "libavutil/channel_layout.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/parseutils.h"
30 #include "audio.h"
31 #include "video.h"
32 #include "avfilter.h"
33 #include "filters.h"
34 #include "internal.h"
35 #include "window_func.h"
36
37 typedef struct ShowSpatialContext {
38 const AVClass *class;
39 int w, h;
40 AVRational frame_rate;
41 FFTContext *fft[2]; ///< Fast Fourier Transform context
42 FFTContext *ifft[2]; ///< Inverse Fast Fourier Transform context
43 int fft_bits; ///< number of bits (FFT window size = 1<<fft_bits)
44 FFTComplex *fft_data[2]; ///< bins holder for each (displayed) channels
45 float *window_func_lut; ///< Window function LUT
46 int win_func;
47 int win_size;
48 int buf_size;
49 float overlap;
50 int consumed;
51 int hop_size;
52 AVAudioFifo *fifo;
53 int64_t pts;
54 } ShowSpatialContext;
55
56 #define OFFSET(x) offsetof(ShowSpatialContext, x)
57 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
58
59 static const AVOption showspatial_options[] = {
60 { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "512x512"}, 0, 0, FLAGS },
61 { "s", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "512x512"}, 0, 0, FLAGS },
62 { "win_size", "set window size", OFFSET(win_size), AV_OPT_TYPE_INT, {.i64 = 4096}, 1024, 65536, FLAGS },
63 WIN_FUNC_OPTION("win_func", OFFSET(win_func), FLAGS, WFUNC_HANNING),
64 { "overlap", "set window overlap", OFFSET(overlap), AV_OPT_TYPE_FLOAT, {.dbl=0.5}, 0, 1, FLAGS },
65 { NULL }
66 };
67
68 AVFILTER_DEFINE_CLASS(showspatial);
69
uninit(AVFilterContext * ctx)70 static av_cold void uninit(AVFilterContext *ctx)
71 {
72 ShowSpatialContext *s = ctx->priv;
73 int i;
74
75 for (i = 0; i < 2; i++)
76 av_fft_end(s->fft[i]);
77 for (i = 0; i < 2; i++)
78 av_fft_end(s->ifft[i]);
79 for (i = 0; i < 2; i++)
80 av_freep(&s->fft_data[i]);
81 av_freep(&s->window_func_lut);
82 av_audio_fifo_free(s->fifo);
83 }
84
query_formats(AVFilterContext * ctx)85 static int query_formats(AVFilterContext *ctx)
86 {
87 AVFilterFormats *formats = NULL;
88 AVFilterChannelLayouts *layout = NULL;
89 AVFilterLink *inlink = ctx->inputs[0];
90 AVFilterLink *outlink = ctx->outputs[0];
91 static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_FLTP, AV_SAMPLE_FMT_NONE };
92 static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_GBRP, AV_PIX_FMT_NONE };
93 int ret;
94
95 formats = ff_make_format_list(sample_fmts);
96 if ((ret = ff_formats_ref (formats, &inlink->outcfg.formats )) < 0 ||
97 (ret = ff_add_channel_layout (&layout, &(AVChannelLayout)AV_CHANNEL_LAYOUT_STEREO)) < 0 ||
98 (ret = ff_channel_layouts_ref (layout , &inlink->outcfg.channel_layouts)) < 0)
99 return ret;
100
101 formats = ff_all_samplerates();
102 if ((ret = ff_formats_ref(formats, &inlink->outcfg.samplerates)) < 0)
103 return ret;
104
105 formats = ff_make_format_list(pix_fmts);
106 if ((ret = ff_formats_ref(formats, &outlink->incfg.formats)) < 0)
107 return ret;
108
109 return 0;
110 }
111
run_channel_fft(AVFilterContext * ctx,void * arg,int jobnr,int nb_jobs)112 static int run_channel_fft(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)
113 {
114 ShowSpatialContext *s = ctx->priv;
115 const float *window_func_lut = s->window_func_lut;
116 AVFrame *fin = arg;
117 const int ch = jobnr;
118 const float *p = (float *)fin->extended_data[ch];
119
120 for (int n = 0; n < fin->nb_samples; n++) {
121 s->fft_data[ch][n].re = p[n] * window_func_lut[n];
122 s->fft_data[ch][n].im = 0;
123 }
124
125 av_fft_permute(s->fft[ch], s->fft_data[ch]);
126 av_fft_calc(s->fft[ch], s->fft_data[ch]);
127
128 return 0;
129 }
130
config_output(AVFilterLink * outlink)131 static int config_output(AVFilterLink *outlink)
132 {
133 AVFilterContext *ctx = outlink->src;
134 AVFilterLink *inlink = ctx->inputs[0];
135 ShowSpatialContext *s = ctx->priv;
136 int i, fft_bits;
137 float overlap;
138
139 outlink->w = s->w;
140 outlink->h = s->h;
141 outlink->sample_aspect_ratio = (AVRational){1,1};
142
143 s->buf_size = 1 << av_log2(s->win_size);
144 s->win_size = s->buf_size;
145 fft_bits = av_log2(s->win_size);
146
147 /* (re-)configuration if the video output changed (or first init) */
148 if (fft_bits != s->fft_bits) {
149 s->fft_bits = fft_bits;
150
151 /* FFT buffers: x2 for each channel buffer.
152 * Note: we use free and malloc instead of a realloc-like function to
153 * make sure the buffer is aligned in memory for the FFT functions. */
154 for (i = 0; i < 2; i++) {
155 av_fft_end(s->fft[i]);
156 av_freep(&s->fft_data[i]);
157 }
158 for (i = 0; i < 2; i++) {
159 s->fft[i] = av_fft_init(fft_bits, 0);
160 if (!s->fft[i]) {
161 av_log(ctx, AV_LOG_ERROR, "Unable to create FFT context. "
162 "The window size might be too high.\n");
163 return AVERROR(EINVAL);
164 }
165 }
166
167 for (i = 0; i < 2; i++) {
168 s->fft_data[i] = av_calloc(s->buf_size, sizeof(**s->fft_data));
169 if (!s->fft_data[i])
170 return AVERROR(ENOMEM);
171 }
172
173 /* pre-calc windowing function */
174 s->window_func_lut =
175 av_realloc_f(s->window_func_lut, s->win_size,
176 sizeof(*s->window_func_lut));
177 if (!s->window_func_lut)
178 return AVERROR(ENOMEM);
179 generate_window_func(s->window_func_lut, s->win_size, s->win_func, &overlap);
180 if (s->overlap == 1)
181 s->overlap = overlap;
182
183 s->hop_size = (1.f - s->overlap) * s->win_size;
184 if (s->hop_size < 1) {
185 av_log(ctx, AV_LOG_ERROR, "overlap %f too big\n", s->overlap);
186 return AVERROR(EINVAL);
187 }
188 }
189
190 outlink->time_base = av_inv_q(outlink->frame_rate);
191
192 av_audio_fifo_free(s->fifo);
193 s->fifo = av_audio_fifo_alloc(inlink->format, inlink->ch_layout.nb_channels, s->win_size);
194 if (!s->fifo)
195 return AVERROR(ENOMEM);
196 return 0;
197 }
198
199 #define RE(y, ch) s->fft_data[ch][y].re
200 #define IM(y, ch) s->fft_data[ch][y].im
201
draw_dot(uint8_t * dst,int linesize,int value)202 static void draw_dot(uint8_t *dst, int linesize, int value)
203 {
204 dst[0] = value;
205 dst[1] = value;
206 dst[-1] = value;
207 dst[linesize] = value;
208 dst[-linesize] = value;
209 }
210
draw_spatial(AVFilterLink * inlink,AVFrame * insamples)211 static int draw_spatial(AVFilterLink *inlink, AVFrame *insamples)
212 {
213 AVFilterContext *ctx = inlink->dst;
214 AVFilterLink *outlink = ctx->outputs[0];
215 ShowSpatialContext *s = ctx->priv;
216 AVFrame *outpicref;
217 int h = s->h - 2;
218 int w = s->w - 2;
219 int z = s->win_size / 2;
220
221 outpicref = ff_get_video_buffer(outlink, outlink->w, outlink->h);
222 if (!outpicref)
223 return AVERROR(ENOMEM);
224
225 outpicref->sample_aspect_ratio = (AVRational){1,1};
226 for (int i = 0; i < outlink->h; i++) {
227 memset(outpicref->data[0] + i * outpicref->linesize[0], 0, outlink->w);
228 memset(outpicref->data[1] + i * outpicref->linesize[1], 0, outlink->w);
229 memset(outpicref->data[2] + i * outpicref->linesize[2], 0, outlink->w);
230 }
231
232 for (int j = 0; j < z; j++) {
233 const int idx = z - 1 - j;
234 float l = hypotf(RE(idx, 0), IM(idx, 0));
235 float r = hypotf(RE(idx, 1), IM(idx, 1));
236 float sum = l + r;
237 float lp = atan2f(IM(idx, 0), RE(idx, 0));
238 float rp = atan2f(IM(idx, 1), RE(idx, 1));
239 float diffp = ((rp - lp) / (2.f * M_PI) + 1.f) * 0.5f;
240 float diff = (sum < 0.000001f ? 0.f : (r - l) / sum) * 0.5f + 0.5f;
241 float cr = av_clipf(cbrtf(l / sum), 0, 1) * 255.f;
242 float cb = av_clipf(cbrtf(r / sum), 0, 1) * 255.f;
243 float cg;
244 int x, y;
245
246 cg = diffp * 255.f;
247 x = av_clip(w * diff, 0, w - 2) + 1;
248 y = av_clip(h * diffp, 0, h - 2) + 1;
249
250 draw_dot(outpicref->data[0] + outpicref->linesize[0] * y + x, outpicref->linesize[0], cg);
251 draw_dot(outpicref->data[1] + outpicref->linesize[1] * y + x, outpicref->linesize[1], cb);
252 draw_dot(outpicref->data[2] + outpicref->linesize[2] * y + x, outpicref->linesize[2], cr);
253 }
254
255 outpicref->pts = av_rescale_q(insamples->pts, inlink->time_base, outlink->time_base);
256
257 return ff_filter_frame(outlink, outpicref);
258 }
259
spatial_activate(AVFilterContext * ctx)260 static int spatial_activate(AVFilterContext *ctx)
261 {
262 AVFilterLink *inlink = ctx->inputs[0];
263 AVFilterLink *outlink = ctx->outputs[0];
264 ShowSpatialContext *s = ctx->priv;
265 int ret;
266
267 FF_FILTER_FORWARD_STATUS_BACK(outlink, inlink);
268
269 if (av_audio_fifo_size(s->fifo) < s->win_size) {
270 AVFrame *frame = NULL;
271
272 ret = ff_inlink_consume_frame(inlink, &frame);
273 if (ret < 0)
274 return ret;
275 if (ret > 0) {
276 s->pts = frame->pts;
277 s->consumed = 0;
278
279 av_audio_fifo_write(s->fifo, (void **)frame->extended_data, frame->nb_samples);
280 av_frame_free(&frame);
281 }
282 }
283
284 if (av_audio_fifo_size(s->fifo) >= s->win_size) {
285 AVFrame *fin = ff_get_audio_buffer(inlink, s->win_size);
286 if (!fin)
287 return AVERROR(ENOMEM);
288
289 fin->pts = s->pts + s->consumed;
290 s->consumed += s->hop_size;
291 ret = av_audio_fifo_peek(s->fifo, (void **)fin->extended_data,
292 FFMIN(s->win_size, av_audio_fifo_size(s->fifo)));
293 if (ret < 0) {
294 av_frame_free(&fin);
295 return ret;
296 }
297
298 av_assert0(fin->nb_samples == s->win_size);
299
300 ff_filter_execute(ctx, run_channel_fft, fin, NULL, 2);
301
302 ret = draw_spatial(inlink, fin);
303
304 av_frame_free(&fin);
305 av_audio_fifo_drain(s->fifo, s->hop_size);
306 if (ret <= 0)
307 return ret;
308 }
309
310 FF_FILTER_FORWARD_STATUS(inlink, outlink);
311 if (ff_outlink_frame_wanted(outlink) && av_audio_fifo_size(s->fifo) < s->win_size) {
312 ff_inlink_request_frame(inlink);
313 return 0;
314 }
315
316 if (av_audio_fifo_size(s->fifo) >= s->win_size) {
317 ff_filter_set_ready(ctx, 10);
318 return 0;
319 }
320 return FFERROR_NOT_READY;
321 }
322
323 static const AVFilterPad showspatial_inputs[] = {
324 {
325 .name = "default",
326 .type = AVMEDIA_TYPE_AUDIO,
327 },
328 };
329
330 static const AVFilterPad showspatial_outputs[] = {
331 {
332 .name = "default",
333 .type = AVMEDIA_TYPE_VIDEO,
334 .config_props = config_output,
335 },
336 };
337
338 const AVFilter ff_avf_showspatial = {
339 .name = "showspatial",
340 .description = NULL_IF_CONFIG_SMALL("Convert input audio to a spatial video output."),
341 .uninit = uninit,
342 .priv_size = sizeof(ShowSpatialContext),
343 FILTER_INPUTS(showspatial_inputs),
344 FILTER_OUTPUTS(showspatial_outputs),
345 FILTER_QUERY_FUNC(query_formats),
346 .activate = spatial_activate,
347 .priv_class = &showspatial_class,
348 .flags = AVFILTER_FLAG_SLICE_THREADS,
349 };
350