]> git.sesse.net Git - ffmpeg/blob - libavfilter/avf_showcqt.c
Merge commit 'a001ce31bc2bcf875a39b5fb22dae49120293b42'
[ffmpeg] / libavfilter / avf_showcqt.c
1 /*
2  * Copyright (c) 2014-2015 Muhammad Faiz <mfcc64@gmail.com>
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 <math.h>
22 #include <stdlib.h>
23
24 #include "config.h"
25 #include "libavcodec/avfft.h"
26 #include "libavutil/avassert.h"
27 #include "libavutil/opt.h"
28 #include "libavutil/xga_font_data.h"
29 #include "libavutil/eval.h"
30 #include "libavutil/pixdesc.h"
31 #include "avfilter.h"
32 #include "internal.h"
33 #include "lavfutils.h"
34 #include "lswsutils.h"
35
36 #if CONFIG_LIBFREETYPE
37 #include <ft2build.h>
38 #include FT_FREETYPE_H
39 #endif
40
41 #include "avf_showcqt.h"
42
43 #define BASEFREQ        20.01523126408007475
44 #define ENDFREQ         20495.59681441799654
45 #define TLENGTH         "384*tc/(384+tc*f)"
46 #define TLENGTH_MIN     0.001
47 #define VOLUME_MAX      100.0
48 #define FONTCOLOR       "st(0, (midi(f)-59.5)/12);" \
49     "st(1, if(between(ld(0),0,1), 0.5-0.5*cos(2*PI*ld(0)), 0));" \
50     "r(1-ld(1)) + b(ld(1))"
51 #define PTS_STEP 10
52 #define PTS_TOLERANCE 1
53
54 #define OFFSET(x) offsetof(ShowCQTContext, x)
55 #define FLAGS (AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM)
56
57 static const AVOption showcqt_options[] = {
58     { "size",         "set video size", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, { .str = "1920x1080" },      0, 0,        FLAGS },
59     { "s",            "set video size", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, { .str = "1920x1080" },      0, 0,        FLAGS },
60     { "fps",          "set video rate", OFFSET(rate),  AV_OPT_TYPE_VIDEO_RATE, { .str = "25" },             0, 0,        FLAGS },
61     { "rate",         "set video rate", OFFSET(rate),  AV_OPT_TYPE_VIDEO_RATE, { .str = "25" },             0, 0,        FLAGS },
62     { "r",            "set video rate", OFFSET(rate),  AV_OPT_TYPE_VIDEO_RATE, { .str = "25" },             0, 0,        FLAGS },
63     { "bar_h",   "set bargraph height", OFFSET(bar_h),        AV_OPT_TYPE_INT, { .i64 = -1 },              -1, INT_MAX,  FLAGS },
64     { "axis_h",      "set axis height", OFFSET(axis_h),       AV_OPT_TYPE_INT, { .i64 = -1 },              -1, INT_MAX,  FLAGS },
65     { "sono_h",  "set sonogram height", OFFSET(sono_h),       AV_OPT_TYPE_INT, { .i64 = -1 },              -1, INT_MAX,  FLAGS },
66     { "fullhd",      "set fullhd size", OFFSET(fullhd),      AV_OPT_TYPE_BOOL, { .i64 = 1 },                0, 1,        FLAGS },
67     { "sono_v",  "set sonogram volume", OFFSET(sono_v),    AV_OPT_TYPE_STRING, { .str = "16" },      CHAR_MIN, CHAR_MAX, FLAGS },
68     { "volume",  "set sonogram volume", OFFSET(sono_v),    AV_OPT_TYPE_STRING, { .str = "16" },      CHAR_MIN, CHAR_MAX, FLAGS },
69     { "bar_v",   "set bargraph volume", OFFSET(bar_v),     AV_OPT_TYPE_STRING, { .str = "sono_v" },  CHAR_MIN, CHAR_MAX, FLAGS },
70     { "volume2", "set bargraph volume", OFFSET(bar_v),     AV_OPT_TYPE_STRING, { .str = "sono_v" },  CHAR_MIN, CHAR_MAX, FLAGS },
71     { "sono_g",   "set sonogram gamma", OFFSET(sono_g),     AV_OPT_TYPE_FLOAT, { .dbl = 3.0 },            1.0, 7.0,      FLAGS },
72     { "gamma",    "set sonogram gamma", OFFSET(sono_g),     AV_OPT_TYPE_FLOAT, { .dbl = 3.0 },            1.0, 7.0,      FLAGS },
73     { "bar_g",    "set bargraph gamma", OFFSET(bar_g),      AV_OPT_TYPE_FLOAT, { .dbl = 1.0 },            1.0, 7.0,      FLAGS },
74     { "gamma2",   "set bargraph gamma", OFFSET(bar_g),      AV_OPT_TYPE_FLOAT, { .dbl = 1.0 },            1.0, 7.0,      FLAGS },
75     { "timeclamp",     "set timeclamp", OFFSET(timeclamp), AV_OPT_TYPE_DOUBLE, { .dbl = 0.17 },           0.1, 1.0,      FLAGS },
76     { "tc",            "set timeclamp", OFFSET(timeclamp), AV_OPT_TYPE_DOUBLE, { .dbl = 0.17 },           0.1, 1.0,      FLAGS },
77     { "basefreq", "set base frequency", OFFSET(basefreq),  AV_OPT_TYPE_DOUBLE, { .dbl = BASEFREQ },      10.0, 100000.0, FLAGS },
78     { "endfreq",   "set end frequency", OFFSET(endfreq),   AV_OPT_TYPE_DOUBLE, { .dbl = ENDFREQ },       10.0, 100000.0, FLAGS },
79     { "coeffclamp",   "set coeffclamp", OFFSET(coeffclamp), AV_OPT_TYPE_FLOAT, { .dbl = 1.0 },            0.1, 10.0,     FLAGS },
80     { "tlength",         "set tlength", OFFSET(tlength),   AV_OPT_TYPE_STRING, { .str = TLENGTH },   CHAR_MIN, CHAR_MAX, FLAGS },
81     { "count",   "set transform count", OFFSET(count),        AV_OPT_TYPE_INT, { .i64 = 6 },                1, 30,       FLAGS },
82     { "fcount",  "set frequency count", OFFSET(fcount),       AV_OPT_TYPE_INT, { .i64 = 0 },                0, 10,       FLAGS },
83     { "fontfile",      "set axis font", OFFSET(fontfile),  AV_OPT_TYPE_STRING, { .str = NULL },      CHAR_MIN, CHAR_MAX, FLAGS },
84     { "fontcolor",    "set font color", OFFSET(fontcolor), AV_OPT_TYPE_STRING, { .str = FONTCOLOR }, CHAR_MIN, CHAR_MAX, FLAGS },
85     { "axisfile",     "set axis image", OFFSET(axisfile),  AV_OPT_TYPE_STRING, { .str = NULL },      CHAR_MIN, CHAR_MAX, FLAGS },
86     { "axis",              "draw axis", OFFSET(axis),        AV_OPT_TYPE_BOOL, { .i64 = 1 },                0, 1,        FLAGS },
87     { "text",              "draw axis", OFFSET(axis),        AV_OPT_TYPE_BOOL, { .i64 = 1 },                0, 1,        FLAGS },
88     { NULL }
89 };
90
91 AVFILTER_DEFINE_CLASS(showcqt);
92
93 static void common_uninit(ShowCQTContext *s)
94 {
95     int k;
96
97     /* axis_frame may be non reference counted frame */
98     if (s->axis_frame && !s->axis_frame->buf[0]) {
99         av_freep(s->axis_frame->data);
100         for (k = 0; k < 4; k++)
101             s->axis_frame->data[k] = NULL;
102     }
103
104     av_frame_free(&s->axis_frame);
105     av_frame_free(&s->sono_frame);
106     av_fft_end(s->fft_ctx);
107     s->fft_ctx = NULL;
108     if (s->coeffs)
109         for (k = 0; k < s->cqt_len * 2; k++)
110             av_freep(&s->coeffs[k].val);
111     av_freep(&s->coeffs);
112     av_freep(&s->fft_data);
113     av_freep(&s->fft_result);
114     av_freep(&s->cqt_result);
115     av_freep(&s->c_buf);
116     av_freep(&s->h_buf);
117     av_freep(&s->rcp_h_buf);
118     av_freep(&s->freq);
119     av_freep(&s->sono_v_buf);
120     av_freep(&s->bar_v_buf);
121 }
122
123 static double *create_freq_table(double base, double end, int n)
124 {
125     double log_base, log_end;
126     double rcp_n = 1.0 / n;
127     double *freq;
128     int x;
129
130     freq = av_malloc_array(n, sizeof(*freq));
131     if (!freq)
132         return NULL;
133
134     log_base = log(base);
135     log_end  = log(end);
136     for (x = 0; x < n; x++) {
137         double log_freq = log_base + (x + 0.5) * (log_end - log_base) * rcp_n;
138         freq[x] = exp(log_freq);
139     }
140     return freq;
141 }
142
143 static double clip_with_log(void *log_ctx, const char *name,
144                             double val, double min, double max,
145                             double nan_replace, int idx)
146 {
147     int level = AV_LOG_WARNING;
148     if (isnan(val)) {
149         av_log(log_ctx, level, "[%d] %s is nan, setting it to %g.\n",
150                idx, name, nan_replace);
151         val = nan_replace;
152     } else if (val < min) {
153         av_log(log_ctx, level, "[%d] %s is too low (%g), setting it to %g.\n",
154                idx, name, val, min);
155         val = min;
156     } else if (val > max) {
157         av_log(log_ctx, level, "[%d] %s it too high (%g), setting it to %g.\n",
158                idx, name, val, max);
159         val = max;
160     }
161     return val;
162 }
163
164 static double a_weighting(void *p, double f)
165 {
166     double ret = 12200.0*12200.0 * (f*f*f*f);
167     ret /= (f*f + 20.6*20.6) * (f*f + 12200.0*12200.0) *
168            sqrt((f*f + 107.7*107.7) * (f*f + 737.9*737.9));
169     return ret;
170 }
171
172 static double b_weighting(void *p, double f)
173 {
174     double ret = 12200.0*12200.0 * (f*f*f);
175     ret /= (f*f + 20.6*20.6) * (f*f + 12200.0*12200.0) * sqrt(f*f + 158.5*158.5);
176     return ret;
177 }
178
179 static double c_weighting(void *p, double f)
180 {
181     double ret = 12200.0*12200.0 * (f*f);
182     ret /= (f*f + 20.6*20.6) * (f*f + 12200.0*12200.0);
183     return ret;
184 }
185
186 static int init_volume(ShowCQTContext *s)
187 {
188     const char *func_names[] = { "a_weighting", "b_weighting", "c_weighting", NULL };
189     const char *sono_names[] = { "timeclamp", "tc", "frequency", "freq", "f", "bar_v", NULL };
190     const char *bar_names[] = { "timeclamp", "tc", "frequency", "freq", "f", "sono_v", NULL };
191     double (*funcs[])(void *, double) = { a_weighting, b_weighting, c_weighting };
192     AVExpr *sono = NULL, *bar = NULL;
193     int x, ret = AVERROR(ENOMEM);
194
195     s->sono_v_buf = av_malloc_array(s->cqt_len, sizeof(*s->sono_v_buf));
196     s->bar_v_buf = av_malloc_array(s->cqt_len, sizeof(*s->bar_v_buf));
197     if (!s->sono_v_buf || !s->bar_v_buf)
198         goto error;
199
200     if ((ret = av_expr_parse(&sono, s->sono_v, sono_names, func_names, funcs, NULL, NULL, 0, s->ctx)) < 0)
201         goto error;
202
203     if ((ret = av_expr_parse(&bar, s->bar_v, bar_names, func_names, funcs, NULL, NULL, 0, s->ctx)) < 0)
204         goto error;
205
206     for (x = 0; x < s->cqt_len; x++) {
207         double vars[] = { s->timeclamp, s->timeclamp, s->freq[x], s->freq[x], s->freq[x], 0.0 };
208         double vol = clip_with_log(s->ctx, "sono_v", av_expr_eval(sono, vars, NULL), 0.0, VOLUME_MAX, 0.0, x);
209         vars[5] = vol;
210         vol = clip_with_log(s->ctx, "bar_v", av_expr_eval(bar, vars, NULL), 0.0, VOLUME_MAX, 0.0, x);
211         s->bar_v_buf[x] = vol * vol;
212         vars[5] = vol;
213         vol = clip_with_log(s->ctx, "sono_v", av_expr_eval(sono, vars, NULL), 0.0, VOLUME_MAX, 0.0, x);
214         s->sono_v_buf[x] = vol * vol;
215     }
216     av_expr_free(sono);
217     av_expr_free(bar);
218     return 0;
219
220 error:
221     av_freep(&s->sono_v_buf);
222     av_freep(&s->bar_v_buf);
223     av_expr_free(sono);
224     av_expr_free(bar);
225     return ret;
226 }
227
228 static void cqt_calc(FFTComplex *dst, const FFTComplex *src, const Coeffs *coeffs,
229                      int len, int fft_len)
230 {
231     int k, x, i, j;
232     for (k = 0; k < len; k++) {
233         FFTComplex l, r, a = {0,0}, b = {0,0};
234
235         for (x = 0; x < coeffs[k].len; x++) {
236             FFTSample u = coeffs[k].val[x];
237             i = coeffs[k].start + x;
238             j = fft_len - i;
239             a.re += u * src[i].re;
240             a.im += u * src[i].im;
241             b.re += u * src[j].re;
242             b.im += u * src[j].im;
243         }
244
245         /* separate left and right, (and multiply by 2.0) */
246         l.re = a.re + b.re;
247         l.im = a.im - b.im;
248         r.re = b.im + a.im;
249         r.im = b.re - a.re;
250         dst[k].re = l.re * l.re + l.im * l.im;
251         dst[k].im = r.re * r.re + r.im * r.im;
252     }
253 }
254
255 #if 0
256 static void cqt_calc_interleave(FFTComplex *dst, const FFTComplex *src, const Coeffs *coeffs,
257                                 int len, int fft_len)
258 {
259     int k, x, i, m;
260
261     for (k = 0; k < len; k++) {
262         FFTComplex l, r, a = {0,0}, b = {0,0};
263
264         m = 2 * k;
265         for (x = 0; x < coeffs[m].len; x++) {
266             FFTSample u = coeffs[m].val[x];
267             i = coeffs[m].start + x;
268             a.re += u * src[i].re;
269             a.im += u * src[i].im;
270         }
271
272         m++;
273         for (x = 0; x < coeffs[m].len; x++) {
274             FFTSample u = coeffs[m].val[x];
275             i = coeffs[m].start + x;
276             b.re += u * src[i].re;
277             b.im += u * src[i].im;
278         }
279
280         /* separate left and right, (and multiply by 2.0) */
281         l.re = a.re + b.re;
282         l.im = a.im - b.im;
283         r.re = b.im + a.im;
284         r.im = b.re - a.re;
285         dst[k].re = l.re * l.re + l.im * l.im;
286         dst[k].im = r.re * r.re + r.im * r.im;
287     }
288 }
289 #endif
290
291 static int init_cqt(ShowCQTContext *s)
292 {
293     const char *var_names[] = { "timeclamp", "tc", "frequency", "freq", "f", NULL };
294     AVExpr *expr = NULL;
295     int rate = s->ctx->inputs[0]->sample_rate;
296     int nb_cqt_coeffs = 0, nb_cqt_coeffs_r = 0;
297     int k, x, ret;
298
299     if ((ret = av_expr_parse(&expr, s->tlength, var_names, NULL, NULL, NULL, NULL, 0, s->ctx)) < 0)
300         goto error;
301
302     ret = AVERROR(ENOMEM);
303     if (!(s->coeffs = av_calloc(s->cqt_len * 2, sizeof(*s->coeffs))))
304         goto error;
305
306     for (k = 0; k < s->cqt_len; k++) {
307         double vars[] = { s->timeclamp, s->timeclamp, s->freq[k], s->freq[k], s->freq[k] };
308         double flen, center, tlength;
309         int start, end, m = (s->cqt_coeffs_type == COEFFS_TYPE_INTERLEAVE) ? (2 * k) : k;
310
311         if (s->freq[k] > 0.5 * rate)
312             continue;
313         tlength = clip_with_log(s->ctx, "tlength", av_expr_eval(expr, vars, NULL),
314                                 TLENGTH_MIN, s->timeclamp, s->timeclamp, k);
315
316         flen = 8.0 * s->fft_len / (tlength * rate);
317         center = s->freq[k] * s->fft_len / rate;
318         start = FFMAX(0, ceil(center - 0.5 * flen));
319         end = FFMIN(s->fft_len, floor(center + 0.5 * flen));
320
321         s->coeffs[m].start = start & ~(s->cqt_align - 1);
322         s->coeffs[m].len = (end | (s->cqt_align - 1)) + 1 - s->coeffs[m].start;
323         nb_cqt_coeffs += s->coeffs[m].len;
324         if (!(s->coeffs[m].val = av_calloc(s->coeffs[m].len, sizeof(*s->coeffs[m].val))))
325             goto error;
326
327         if (s->cqt_coeffs_type == COEFFS_TYPE_INTERLEAVE) {
328             s->coeffs[m+1].start = (s->fft_len - end) & ~(s->cqt_align - 1);
329             s->coeffs[m+1].len = ((s->fft_len - start) | (s->cqt_align - 1)) + 1 - s->coeffs[m+1].start;
330             nb_cqt_coeffs_r += s->coeffs[m+1].len;
331             if (!(s->coeffs[m+1].val = av_calloc(s->coeffs[m+1].len, sizeof(*s->coeffs[m+1].val))))
332                 goto error;
333         }
334
335         for (x = start; x <= end; x++) {
336             int sign = (x & 1) ? (-1) : 1;
337             double y = 2.0 * M_PI * (x - center) * (1.0 / flen);
338             /* nuttall window */
339             double w = 0.355768 + 0.487396 * cos(y) + 0.144232 * cos(2*y) + 0.012604 * cos(3*y);
340             w *= sign * (1.0 / s->fft_len);
341             s->coeffs[m].val[x - s->coeffs[m].start] = w;
342             if (s->cqt_coeffs_type == COEFFS_TYPE_INTERLEAVE)
343                 s->coeffs[m+1].val[(s->fft_len - x) - s->coeffs[m+1].start] = w;
344         }
345     }
346
347     av_expr_free(expr);
348     if (s->cqt_coeffs_type == COEFFS_TYPE_DEFAULT)
349         av_log(s->ctx, AV_LOG_INFO, "nb_cqt_coeffs = %d.\n", nb_cqt_coeffs);
350     else
351         av_log(s->ctx, AV_LOG_INFO, "nb_cqt_coeffs = {%d,%d}.\n", nb_cqt_coeffs, nb_cqt_coeffs_r);
352     return 0;
353
354 error:
355     av_expr_free(expr);
356     if (s->coeffs)
357         for (k = 0; k < s->cqt_len * 2; k++)
358             av_freep(&s->coeffs[k].val);
359     av_freep(&s->coeffs);
360     return ret;
361 }
362
363 static AVFrame *alloc_frame_empty(enum AVPixelFormat format, int w, int h)
364 {
365     AVFrame *out;
366     out = av_frame_alloc();
367     if (!out)
368         return NULL;
369     out->format = format;
370     out->width = w;
371     out->height = h;
372     if (av_frame_get_buffer(out, 32) < 0) {
373         av_frame_free(&out);
374         return NULL;
375     }
376     if (format == AV_PIX_FMT_RGB24 || format == AV_PIX_FMT_RGBA) {
377         memset(out->data[0], 0, out->linesize[0] * h);
378     } else {
379         int hh = (format == AV_PIX_FMT_YUV420P || format == AV_PIX_FMT_YUVA420P) ? h / 2 : h;
380         memset(out->data[0], 16, out->linesize[0] * h);
381         memset(out->data[1], 128, out->linesize[1] * hh);
382         memset(out->data[2], 128, out->linesize[2] * hh);
383         if (out->data[3])
384             memset(out->data[3], 0, out->linesize[3] * h);
385     }
386     return out;
387 }
388
389 static enum AVPixelFormat convert_axis_pixel_format(enum AVPixelFormat format)
390 {
391     switch (format) {
392         case AV_PIX_FMT_RGB24:   format = AV_PIX_FMT_RGBA; break;
393         case AV_PIX_FMT_YUV444P: format = AV_PIX_FMT_YUVA444P; break;
394         case AV_PIX_FMT_YUV422P: format = AV_PIX_FMT_YUVA422P; break;
395         case AV_PIX_FMT_YUV420P: format = AV_PIX_FMT_YUVA420P; break;
396     }
397     return format;
398 }
399
400 static int init_axis_empty(ShowCQTContext *s)
401 {
402     if (!(s->axis_frame = alloc_frame_empty(convert_axis_pixel_format(s->format), s->width, s->axis_h)))
403         return AVERROR(ENOMEM);
404     return 0;
405 }
406
407 static int init_axis_from_file(ShowCQTContext *s)
408 {
409     uint8_t *tmp_data[4] = { NULL };
410     int tmp_linesize[4];
411     enum AVPixelFormat tmp_format;
412     int tmp_w, tmp_h, ret;
413
414     if ((ret = ff_load_image(tmp_data, tmp_linesize, &tmp_w, &tmp_h, &tmp_format,
415                              s->axisfile, s->ctx)) < 0)
416         goto error;
417
418     ret = AVERROR(ENOMEM);
419     if (!(s->axis_frame = av_frame_alloc()))
420         goto error;
421
422     if ((ret = ff_scale_image(s->axis_frame->data, s->axis_frame->linesize, s->width, s->axis_h,
423                               convert_axis_pixel_format(s->format), tmp_data, tmp_linesize, tmp_w, tmp_h,
424                               tmp_format, s->ctx)) < 0)
425         goto error;
426
427     s->axis_frame->width = s->width;
428     s->axis_frame->height = s->axis_h;
429     s->axis_frame->format = convert_axis_pixel_format(s->format);
430     av_freep(tmp_data);
431     return 0;
432
433 error:
434     av_frame_free(&s->axis_frame);
435     av_freep(tmp_data);
436     return ret;
437 }
438
439 static double midi(void *p, double f)
440 {
441     return log2(f/440.0) * 12.0 + 69.0;
442 }
443
444 static double r_func(void *p, double x)
445 {
446     x = av_clipd(x, 0.0, 1.0);
447     return (int)(x*255.0+0.5) << 16;
448 }
449
450 static double g_func(void *p, double x)
451 {
452     x = av_clipd(x, 0.0, 1.0);
453     return (int)(x*255.0+0.5) << 8;
454 }
455
456 static double b_func(void *p, double x)
457 {
458     x = av_clipd(x, 0.0, 1.0);
459     return (int)(x*255.0+0.5);
460 }
461
462 static int init_axis_color(ShowCQTContext *s, AVFrame *tmp)
463 {
464     const char *var_names[] = { "timeclamp", "tc", "frequency", "freq", "f", NULL };
465     const char *func_names[] = { "midi", "r", "g", "b", NULL };
466     double (*funcs[])(void *, double) = { midi, r_func, g_func, b_func };
467     AVExpr *expr = NULL;
468     double *freq = NULL;
469     int x, y, ret;
470
471     if (s->basefreq != (double) BASEFREQ || s->endfreq != (double) ENDFREQ) {
472         av_log(s->ctx, AV_LOG_WARNING, "font axis rendering is not implemented in non-default frequency range,"
473                " please use axisfile option instead.\n");
474         return AVERROR(EINVAL);
475     }
476
477     if (s->cqt_len == 1920)
478         freq = s->freq;
479     else if (!(freq = create_freq_table(s->basefreq, s->endfreq, 1920)))
480         return AVERROR(ENOMEM);
481
482     if ((ret = av_expr_parse(&expr, s->fontcolor, var_names, func_names, funcs, NULL, NULL, 0, s->ctx)) < 0) {
483         if (freq != s->freq)
484             av_freep(&freq);
485         return ret;
486     }
487
488     for (x = 0; x < 1920; x++) {
489         double vars[] = { s->timeclamp, s->timeclamp, freq[x], freq[x], freq[x] };
490         int color = (int) av_expr_eval(expr, vars, NULL);
491         uint8_t r = (color >> 16) & 0xFF, g = (color >> 8) & 0xFF, b = color & 0xFF;
492         uint8_t *data = tmp->data[0];
493         int linesize = tmp->linesize[0];
494         for (y = 0; y < 32; y++) {
495             data[linesize * y + 4 * x] = r;
496             data[linesize * y + 4 * x + 1] = g;
497             data[linesize * y + 4 * x + 2] = b;
498             data[linesize * y + 4 * x + 3] = 0;
499         }
500     }
501
502     av_expr_free(expr);
503     if (freq != s->freq)
504         av_freep(&freq);
505     return 0;
506 }
507
508 static int render_freetype(ShowCQTContext *s, AVFrame *tmp)
509 {
510 #if CONFIG_LIBFREETYPE
511     const char *str = "EF G A BC D ";
512     uint8_t *data = tmp->data[0];
513     int linesize = tmp->linesize[0];
514     FT_Library lib = NULL;
515     FT_Face face = NULL;
516     int font_width = 16, font_height = 32;
517     int font_repeat = font_width * 12;
518     int linear_hori_advance = font_width * 65536;
519     int non_monospace_warning = 0;
520     int x;
521
522     if (!s->fontfile)
523         return AVERROR(EINVAL);
524
525     if (FT_Init_FreeType(&lib))
526         goto fail;
527
528     if (FT_New_Face(lib, s->fontfile, 0, &face))
529         goto fail;
530
531     if (FT_Set_Char_Size(face, 16*64, 0, 0, 0))
532         goto fail;
533
534     if (FT_Load_Char(face, 'A', FT_LOAD_RENDER))
535         goto fail;
536
537     if (FT_Set_Char_Size(face, 16*64 * linear_hori_advance / face->glyph->linearHoriAdvance, 0, 0, 0))
538         goto fail;
539
540     for (x = 0; x < 12; x++) {
541         int sx, sy, rx, bx, by, dx, dy;
542
543         if (str[x] == ' ')
544             continue;
545
546         if (FT_Load_Char(face, str[x], FT_LOAD_RENDER))
547             goto fail;
548
549         if (face->glyph->advance.x != font_width*64 && !non_monospace_warning) {
550             av_log(s->ctx, AV_LOG_WARNING, "font is not monospace.\n");
551             non_monospace_warning = 1;
552         }
553
554         sy = font_height - 8 - face->glyph->bitmap_top;
555         for (rx = 0; rx < 10; rx++) {
556             sx = rx * font_repeat + x * font_width + face->glyph->bitmap_left;
557             for (by = 0; by < face->glyph->bitmap.rows; by++) {
558                 dy = by + sy;
559                 if (dy < 0)
560                     continue;
561                 if (dy >= font_height)
562                     break;
563
564                 for (bx = 0; bx < face->glyph->bitmap.width; bx++) {
565                     dx = bx + sx;
566                     if (dx < 0)
567                         continue;
568                     if (dx >= 1920)
569                         break;
570                     data[dy*linesize+4*dx+3] = face->glyph->bitmap.buffer[by*face->glyph->bitmap.width+bx];
571                 }
572             }
573         }
574     }
575
576     FT_Done_Face(face);
577     FT_Done_FreeType(lib);
578     return 0;
579
580 fail:
581     av_log(s->ctx, AV_LOG_WARNING, "error while loading freetype font, using default font instead.\n");
582     FT_Done_Face(face);
583     FT_Done_FreeType(lib);
584     return AVERROR(EINVAL);
585 #else
586     if (s->fontfile)
587         av_log(s->ctx, AV_LOG_WARNING, "freetype is not available, ignoring fontfile option.\n");
588     return AVERROR(EINVAL);
589 #endif
590 }
591
592 static int render_default_font(AVFrame *tmp)
593 {
594     const char *str = "EF G A BC D ";
595     int x, u, v, mask;
596     uint8_t *data = tmp->data[0];
597     int linesize = tmp->linesize[0];
598
599     for (x = 0; x < 1920; x += 192) {
600         uint8_t *startptr = data + 4 * x;
601         for (u = 0; u < 12; u++) {
602             for (v = 0; v < 16; v++) {
603                 uint8_t *p = startptr + 2 * v * linesize + 16 * 4 * u;
604                 for (mask = 0x80; mask; mask >>= 1, p += 8) {
605                     if (mask & avpriv_vga16_font[str[u] * 16 + v]) {
606                         p[3] = 255;
607                         p[7] = 255;
608                         p[linesize+3] = 255;
609                         p[linesize+7] = 255;
610                     }
611                 }
612             }
613         }
614     }
615
616     return 0;
617 }
618
619 static int init_axis_from_font(ShowCQTContext *s)
620 {
621     AVFrame *tmp = NULL;
622     int ret = AVERROR(ENOMEM);
623
624     if (!(tmp = alloc_frame_empty(AV_PIX_FMT_RGBA, 1920, 32)))
625         goto fail;
626
627     if (!(s->axis_frame = av_frame_alloc()))
628         goto fail;
629
630     if ((ret = init_axis_color(s, tmp)) < 0)
631         goto fail;
632
633     if (render_freetype(s, tmp) < 0 && (ret = render_default_font(tmp)) < 0)
634         goto fail;
635
636     if ((ret = ff_scale_image(s->axis_frame->data, s->axis_frame->linesize, s->width, s->axis_h,
637                               convert_axis_pixel_format(s->format), tmp->data, tmp->linesize,
638                               1920, 32, AV_PIX_FMT_RGBA, s->ctx)) < 0)
639         goto fail;
640
641     av_frame_free(&tmp);
642     s->axis_frame->width = s->width;
643     s->axis_frame->height = s->axis_h;
644     s->axis_frame->format = convert_axis_pixel_format(s->format);
645     return 0;
646
647 fail:
648     av_frame_free(&tmp);
649     av_frame_free(&s->axis_frame);
650     return ret;
651 }
652
653 static float calculate_gamma(float v, float g)
654 {
655     if (g == 1.0f)
656         return v;
657     if (g == 2.0f)
658         return sqrtf(v);
659     if (g == 3.0f)
660         return cbrtf(v);
661     if (g == 4.0f)
662         return sqrtf(sqrtf(v));
663     return expf(logf(v) / g);
664 }
665
666 static void rgb_from_cqt(ColorFloat *c, const FFTComplex *v, float g, int len)
667 {
668     int x;
669     for (x = 0; x < len; x++) {
670         c[x].rgb.r = 255.0f * calculate_gamma(FFMIN(1.0f, v[x].re), g);
671         c[x].rgb.g = 255.0f * calculate_gamma(FFMIN(1.0f, 0.5f * (v[x].re + v[x].im)), g);
672         c[x].rgb.b = 255.0f * calculate_gamma(FFMIN(1.0f, v[x].im), g);
673     }
674 }
675
676 static void yuv_from_cqt(ColorFloat *c, const FFTComplex *v, float gamma, int len)
677 {
678     int x;
679     for (x = 0; x < len; x++) {
680         float r, g, b;
681         r = calculate_gamma(FFMIN(1.0f, v[x].re), gamma);
682         g = calculate_gamma(FFMIN(1.0f, 0.5f * (v[x].re + v[x].im)), gamma);
683         b = calculate_gamma(FFMIN(1.0f, v[x].im), gamma);
684         c[x].yuv.y = 65.481f * r + 128.553f * g + 24.966f * b;
685         c[x].yuv.u = -37.797f * r - 74.203f * g + 112.0f * b;
686         c[x].yuv.v = 112.0f * r - 93.786f * g - 18.214 * b;
687     }
688 }
689
690 static void draw_bar_rgb(AVFrame *out, const float *h, const float *rcp_h,
691                          const ColorFloat *c, int bar_h)
692 {
693     int x, y, w = out->width;
694     float mul, ht, rcp_bar_h = 1.0f / bar_h;
695     uint8_t *v = out->data[0], *lp;
696     int ls = out->linesize[0];
697
698     for (y = 0; y < bar_h; y++) {
699         ht = (bar_h - y) * rcp_bar_h;
700         lp = v + y * ls;
701         for (x = 0; x < w; x++) {
702             if (h[x] <= ht) {
703                 *lp++ = 0;
704                 *lp++ = 0;
705                 *lp++ = 0;
706             } else {
707                 mul = (h[x] - ht) * rcp_h[x];
708                 *lp++ = mul * c[x].rgb.r + 0.5f;
709                 *lp++ = mul * c[x].rgb.g + 0.5f;
710                 *lp++ = mul * c[x].rgb.b + 0.5f;
711             }
712         }
713     }
714 }
715
716 static void draw_bar_yuv(AVFrame *out, const float *h, const float *rcp_h,
717                          const ColorFloat *c, int bar_h)
718 {
719     int x, y, yh, w = out->width;
720     float mul, ht, rcp_bar_h = 1.0f / bar_h;
721     uint8_t *vy = out->data[0], *vu = out->data[1], *vv = out->data[2];
722     uint8_t *lpy, *lpu, *lpv;
723     int lsy = out->linesize[0], lsu = out->linesize[1], lsv = out->linesize[2];
724     int fmt = out->format;
725
726     for (y = 0; y < bar_h; y += 2) {
727         yh = (fmt == AV_PIX_FMT_YUV420P) ? y / 2 : y;
728         ht = (bar_h - y) * rcp_bar_h;
729         lpy = vy + y * lsy;
730         lpu = vu + yh * lsu;
731         lpv = vv + yh * lsv;
732         for (x = 0; x < w; x += 2) {
733             if (h[x] <= ht) {
734                 *lpy++ = 16;
735                 *lpu++ = 128;
736                 *lpv++ = 128;
737             } else {
738                 mul = (h[x] - ht) * rcp_h[x];
739                 *lpy++ = mul * c[x].yuv.y + 16.5f;
740                 *lpu++ = mul * c[x].yuv.u + 128.5f;
741                 *lpv++ = mul * c[x].yuv.v + 128.5f;
742             }
743             /* u and v are skipped on yuv422p and yuv420p */
744             if (fmt == AV_PIX_FMT_YUV444P) {
745                 if (h[x+1] <= ht) {
746                     *lpy++ = 16;
747                     *lpu++ = 128;
748                     *lpv++ = 128;
749                 } else {
750                     mul = (h[x+1] - ht) * rcp_h[x+1];
751                     *lpy++ = mul * c[x+1].yuv.y + 16.5f;
752                     *lpu++ = mul * c[x+1].yuv.u + 128.5f;
753                     *lpv++ = mul * c[x+1].yuv.v + 128.5f;
754                 }
755             } else {
756                 if (h[x+1] <= ht) {
757                     *lpy++ = 16;
758                 } else {
759                     mul = (h[x+1] - ht) * rcp_h[x+1];
760                     *lpy++ = mul * c[x+1].yuv.y + 16.5f;
761                 }
762             }
763         }
764
765         ht = (bar_h - (y+1)) * rcp_bar_h;
766         lpy = vy + (y+1) * lsy;
767         lpu = vu + (y+1) * lsu;
768         lpv = vv + (y+1) * lsv;
769         for (x = 0; x < w; x += 2) {
770             /* u and v are skipped on yuv420p */
771             if (fmt != AV_PIX_FMT_YUV420P) {
772                 if (h[x] <= ht) {
773                     *lpy++ = 16;
774                     *lpu++ = 128;
775                     *lpv++ = 128;
776                 } else {
777                     mul = (h[x] - ht) * rcp_h[x];
778                     *lpy++ = mul * c[x].yuv.y + 16.5f;
779                     *lpu++ = mul * c[x].yuv.u + 128.5f;
780                     *lpv++ = mul * c[x].yuv.v + 128.5f;
781                 }
782             } else {
783                 if (h[x] <= ht) {
784                     *lpy++ = 16;
785                 } else {
786                     mul = (h[x] - ht) * rcp_h[x];
787                     *lpy++ = mul * c[x].yuv.y + 16.5f;
788                 }
789             }
790             /* u and v are skipped on yuv422p and yuv420p */
791             if (out->format == AV_PIX_FMT_YUV444P) {
792                 if (h[x+1] <= ht) {
793                     *lpy++ = 16;
794                     *lpu++ = 128;
795                     *lpv++ = 128;
796                 } else {
797                     mul = (h[x+1] - ht) * rcp_h[x+1];
798                     *lpy++ = mul * c[x+1].yuv.y + 16.5f;
799                     *lpu++ = mul * c[x+1].yuv.u + 128.5f;
800                     *lpv++ = mul * c[x+1].yuv.v + 128.5f;
801                 }
802             } else {
803                 if (h[x+1] <= ht) {
804                     *lpy++ = 16;
805                 } else {
806                     mul = (h[x+1] - ht) * rcp_h[x+1];
807                     *lpy++ = mul * c[x+1].yuv.y + 16.5f;
808                 }
809             }
810         }
811     }
812 }
813
814 static void draw_axis_rgb(AVFrame *out, AVFrame *axis, const ColorFloat *c, int off)
815 {
816     int x, y, w = axis->width, h = axis->height;
817     float a, rcp_255 = 1.0f / 255.0f;
818     uint8_t *lp, *lpa;
819
820     for (y = 0; y < h; y++) {
821         lp = out->data[0] + (off + y) * out->linesize[0];
822         lpa = axis->data[0] + y * axis->linesize[0];
823         for (x = 0; x < w; x++) {
824             a = rcp_255 * lpa[3];
825             *lp++ = a * lpa[0] + (1.0f - a) * c[x].rgb.r + 0.5f;
826             *lp++ = a * lpa[1] + (1.0f - a) * c[x].rgb.g + 0.5f;
827             *lp++ = a * lpa[2] + (1.0f - a) * c[x].rgb.b + 0.5f;
828             lpa += 4;
829         }
830     }
831 }
832
833 static void draw_axis_yuv(AVFrame *out, AVFrame *axis, const ColorFloat *c, int off)
834 {
835     int fmt = out->format, x, y, yh, w = axis->width, h = axis->height;
836     int offh = (fmt == AV_PIX_FMT_YUV420P) ? off / 2 : off;
837     float a, rcp_255 = 1.0f / 255.0f;
838     uint8_t *vy = out->data[0], *vu = out->data[1], *vv = out->data[2];
839     uint8_t *vay = axis->data[0], *vau = axis->data[1], *vav = axis->data[2], *vaa = axis->data[3];
840     int lsy = out->linesize[0], lsu = out->linesize[1], lsv = out->linesize[2];
841     int lsay = axis->linesize[0], lsau = axis->linesize[1], lsav = axis->linesize[2], lsaa = axis->linesize[3];
842     uint8_t *lpy, *lpu, *lpv, *lpay, *lpau, *lpav, *lpaa;
843
844     for (y = 0; y < h; y += 2) {
845         yh = (fmt == AV_PIX_FMT_YUV420P) ? y / 2 : y;
846         lpy = vy + (off + y) * lsy;
847         lpu = vu + (offh + yh) * lsu;
848         lpv = vv + (offh + yh) * lsv;
849         lpay = vay + y * lsay;
850         lpau = vau + yh * lsau;
851         lpav = vav + yh * lsav;
852         lpaa = vaa + y * lsaa;
853         for (x = 0; x < w; x += 2) {
854             a = rcp_255 * (*lpaa++);
855             *lpy++ = a * (*lpay++) + (1.0f - a) * (c[x].yuv.y + 16.0f) + 0.5f;
856             *lpu++ = a * (*lpau++) + (1.0f - a) * (c[x].yuv.u + 128.0f) + 0.5f;
857             *lpv++ = a * (*lpav++) + (1.0f - a) * (c[x].yuv.v + 128.0f) + 0.5f;
858             /* u and v are skipped on yuv422p and yuv420p */
859             a = rcp_255 * (*lpaa++);
860             *lpy++ = a * (*lpay++) + (1.0f - a) * (c[x+1].yuv.y + 16.0f) + 0.5f;
861             if (fmt == AV_PIX_FMT_YUV444P) {
862                 *lpu++ = a * (*lpau++) + (1.0f - a) * (c[x+1].yuv.u + 128.0f) + 0.5f;
863                 *lpv++ = a * (*lpav++) + (1.0f - a) * (c[x+1].yuv.v + 128.0f) + 0.5f;
864             }
865         }
866
867         lpy = vy + (off + y + 1) * lsy;
868         lpu = vu + (off + y + 1) * lsu;
869         lpv = vv + (off + y + 1) * lsv;
870         lpay = vay + (y + 1) * lsay;
871         lpau = vau + (y + 1) * lsau;
872         lpav = vav + (y + 1) * lsav;
873         lpaa = vaa + (y + 1) * lsaa;
874         for (x = 0; x < out->width; x += 2) {
875             /* u and v are skipped on yuv420p */
876             a = rcp_255 * (*lpaa++);
877             *lpy++ = a * (*lpay++) + (1.0f - a) * (c[x].yuv.y + 16.0f) + 0.5f;
878             if (fmt != AV_PIX_FMT_YUV420P) {
879                 *lpu++ = a * (*lpau++) + (1.0f - a) * (c[x].yuv.u + 128.0f) + 0.5f;
880                 *lpv++ = a * (*lpav++) + (1.0f - a) * (c[x].yuv.v + 128.0f) + 0.5f;
881             }
882             /* u and v are skipped on yuv422p and yuv420p */
883             a = rcp_255 * (*lpaa++);
884             *lpy++ = a * (*lpay++) + (1.0f - a) * (c[x+1].yuv.y + 16.0f) + 0.5f;
885             if (fmt == AV_PIX_FMT_YUV444P) {
886                 *lpu++ = a * (*lpau++) + (1.0f - a) * (c[x+1].yuv.u + 128.0f) + 0.5f;
887                 *lpv++ = a * (*lpav++) + (1.0f - a) * (c[x+1].yuv.v + 128.0f) + 0.5f;
888             }
889         }
890     }
891 }
892
893 static void draw_sono(AVFrame *out, AVFrame *sono, int off, int idx)
894 {
895     int fmt = out->format, h = sono->height;
896     int nb_planes = (fmt == AV_PIX_FMT_RGB24) ? 1 : 3;
897     int offh = (fmt == AV_PIX_FMT_YUV420P) ? off / 2 : off;
898     int inc = (fmt == AV_PIX_FMT_YUV420P) ? 2 : 1;
899     int ls, i, y, yh;
900
901     ls = FFMIN(out->linesize[0], sono->linesize[0]);
902     for (y = 0; y < h; y++) {
903         memcpy(out->data[0] + (off + y) * out->linesize[0],
904                sono->data[0] + (idx + y) % h * sono->linesize[0], ls);
905     }
906
907     for (i = 1; i < nb_planes; i++) {
908         ls = FFMIN(out->linesize[i], sono->linesize[i]);
909         for (y = 0; y < h; y += inc) {
910             yh = (fmt == AV_PIX_FMT_YUV420P) ? y / 2 : y;
911             memcpy(out->data[i] + (offh + yh) * out->linesize[i],
912                    sono->data[i] + (idx + y) % h * sono->linesize[i], ls);
913         }
914     }
915 }
916
917 static void update_sono_rgb(AVFrame *sono, const ColorFloat *c, int idx)
918 {
919     int x, w = sono->width;
920     uint8_t *lp = sono->data[0] + idx * sono->linesize[0];
921
922     for (x = 0; x < w; x++) {
923         *lp++ = c[x].rgb.r + 0.5f;
924         *lp++ = c[x].rgb.g + 0.5f;
925         *lp++ = c[x].rgb.b + 0.5f;
926     }
927 }
928
929 static void update_sono_yuv(AVFrame *sono, const ColorFloat *c, int idx)
930 {
931     int x, fmt = sono->format, w = sono->width;
932     uint8_t *lpy = sono->data[0] + idx * sono->linesize[0];
933     uint8_t *lpu = sono->data[1] + idx * sono->linesize[1];
934     uint8_t *lpv = sono->data[2] + idx * sono->linesize[2];
935
936     for (x = 0; x < w; x += 2) {
937         *lpy++ = c[x].yuv.y + 16.5f;
938         *lpu++ = c[x].yuv.u + 128.5f;
939         *lpv++ = c[x].yuv.v + 128.5f;
940         *lpy++ = c[x+1].yuv.y + 16.5f;
941         if (fmt == AV_PIX_FMT_YUV444P) {
942             *lpu++ = c[x+1].yuv.u + 128.5f;
943             *lpv++ = c[x+1].yuv.v + 128.5f;
944         }
945     }
946 }
947
948 static void process_cqt(ShowCQTContext *s)
949 {
950     int x, i;
951     if (!s->sono_count) {
952         for (x = 0; x < s->cqt_len; x++) {
953             s->h_buf[x] = s->bar_v_buf[x] * 0.5f * (s->cqt_result[x].re + s->cqt_result[x].im);
954         }
955         if (s->fcount > 1) {
956             float rcp_fcount = 1.0f / s->fcount;
957             for (x = 0; x < s->width; x++) {
958                 float h = 0.0f;
959                 for (i = 0; i < s->fcount; i++)
960                     h += s->h_buf[s->fcount * x + i];
961                 s->h_buf[x] = rcp_fcount * h;
962             }
963         }
964         for (x = 0; x < s->width; x++) {
965             s->h_buf[x] = calculate_gamma(s->h_buf[x], s->bar_g);
966             s->rcp_h_buf[x] = 1.0f / (s->h_buf[x] + 0.0001f);
967         }
968     }
969
970     for (x = 0; x < s->cqt_len; x++) {
971         s->cqt_result[x].re *= s->sono_v_buf[x];
972         s->cqt_result[x].im *= s->sono_v_buf[x];
973     }
974
975     if (s->fcount > 1) {
976         float rcp_fcount = 1.0f / s->fcount;
977         for (x = 0; x < s->width; x++) {
978             FFTComplex result = {0.0f, 0.0f};
979             for (i = 0; i < s->fcount; i++) {
980                 result.re += s->cqt_result[s->fcount * x + i].re;
981                 result.im += s->cqt_result[s->fcount * x + i].im;
982             }
983             s->cqt_result[x].re = rcp_fcount * result.re;
984             s->cqt_result[x].im = rcp_fcount * result.im;
985         }
986     }
987
988     if (s->format == AV_PIX_FMT_RGB24)
989         rgb_from_cqt(s->c_buf, s->cqt_result, s->sono_g, s->width);
990     else
991         yuv_from_cqt(s->c_buf, s->cqt_result, s->sono_g, s->width);
992 }
993
994 static int plot_cqt(AVFilterContext *ctx, AVFrame **frameout)
995 {
996     AVFilterLink *outlink = ctx->outputs[0];
997     ShowCQTContext *s = ctx->priv;
998
999     memcpy(s->fft_result, s->fft_data, s->fft_len * sizeof(*s->fft_data));
1000     av_fft_permute(s->fft_ctx, s->fft_result);
1001     av_fft_calc(s->fft_ctx, s->fft_result);
1002     s->fft_result[s->fft_len] = s->fft_result[0];
1003     s->cqt_calc(s->cqt_result, s->fft_result, s->coeffs, s->cqt_len, s->fft_len);
1004     process_cqt(s);
1005     if (s->sono_h)
1006         s->update_sono(s->sono_frame, s->c_buf, s->sono_idx);
1007     if (!s->sono_count) {
1008         AVFrame *out = *frameout = ff_get_video_buffer(outlink, outlink->w, outlink->h);
1009         if (!out)
1010             return AVERROR(ENOMEM);
1011         if (s->bar_h)
1012             s->draw_bar(out, s->h_buf, s->rcp_h_buf, s->c_buf, s->bar_h);
1013         if (s->axis_h)
1014             s->draw_axis(out, s->axis_frame, s->c_buf, s->bar_h);
1015         if (s->sono_h)
1016             s->draw_sono(out, s->sono_frame, s->bar_h + s->axis_h, s->sono_idx);
1017         out->pts = s->next_pts;
1018         s->next_pts += PTS_STEP;
1019     }
1020     s->sono_count = (s->sono_count + 1) % s->count;
1021     if (s->sono_h)
1022         s->sono_idx = (s->sono_idx + s->sono_h - 1) % s->sono_h;
1023     return 0;
1024 }
1025
1026 /* main filter control */
1027 static av_cold int init(AVFilterContext *ctx)
1028 {
1029     ShowCQTContext *s = ctx->priv;
1030     s->ctx = ctx;
1031
1032     if (!s->fullhd) {
1033         av_log(ctx, AV_LOG_WARNING, "fullhd option is deprecated, use size/s option instead.\n");
1034         if (s->width != 1920 || s->height != 1080) {
1035             av_log(ctx, AV_LOG_ERROR, "fullhd set to 0 but with custom dimension.\n");
1036             return AVERROR(EINVAL);
1037         }
1038         s->width /= 2;
1039         s->height /= 2;
1040         s->fullhd = 1;
1041     }
1042
1043     if (s->axis_h < 0) {
1044         s->axis_h = s->width / 60;
1045         if (s->axis_h & 1)
1046             s->axis_h++;
1047         if (s->bar_h >= 0 && s->sono_h >= 0)
1048             s->axis_h = s->height - s->bar_h - s->sono_h;
1049         if (s->bar_h >= 0 && s->sono_h < 0)
1050             s->axis_h = FFMIN(s->axis_h, s->height - s->bar_h);
1051         if (s->bar_h < 0 && s->sono_h >= 0)
1052             s->axis_h = FFMIN(s->axis_h, s->height - s->sono_h);
1053     }
1054
1055     if (s->bar_h < 0) {
1056         s->bar_h = (s->height - s->axis_h) / 2;
1057         if (s->bar_h & 1)
1058             s->bar_h--;
1059         if (s->sono_h >= 0)
1060             s->bar_h = s->height - s->sono_h - s->axis_h;
1061     }
1062
1063     if (s->sono_h < 0)
1064         s->sono_h = s->height - s->axis_h - s->bar_h;
1065
1066     if ((s->width & 1) || (s->height & 1) || (s->bar_h & 1) || (s->axis_h & 1) || (s->sono_h & 1) ||
1067         (s->bar_h < 0) || (s->axis_h < 0) || (s->sono_h < 0) || (s->bar_h > s->height) ||
1068         (s->axis_h > s->height) || (s->sono_h > s->height) || (s->bar_h + s->axis_h + s->sono_h != s->height)) {
1069         av_log(ctx, AV_LOG_ERROR, "invalid dimension.\n");
1070         return AVERROR(EINVAL);
1071     }
1072
1073     if (!s->fcount) {
1074         do {
1075             s->fcount++;
1076         } while(s->fcount * s->width < 1920 && s->fcount < 10);
1077     }
1078
1079     return 0;
1080 }
1081
1082 static av_cold void uninit(AVFilterContext *ctx)
1083 {
1084     common_uninit(ctx->priv);
1085 }
1086
1087 static int query_formats(AVFilterContext *ctx)
1088 {
1089     AVFilterFormats *formats = NULL;
1090     AVFilterChannelLayouts *layouts = NULL;
1091     AVFilterLink *inlink = ctx->inputs[0];
1092     AVFilterLink *outlink = ctx->outputs[0];
1093     enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_NONE };
1094     enum AVPixelFormat pix_fmts[] = {
1095         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
1096         AV_PIX_FMT_YUV444P, AV_PIX_FMT_RGB24, AV_PIX_FMT_NONE
1097     };
1098     int64_t channel_layouts[] = { AV_CH_LAYOUT_STEREO, AV_CH_LAYOUT_STEREO_DOWNMIX, -1 };
1099     int ret;
1100
1101     /* set input audio formats */
1102     formats = ff_make_format_list(sample_fmts);
1103     if ((ret = ff_formats_ref(formats, &inlink->out_formats)) < 0)
1104         return ret;
1105
1106     layouts = avfilter_make_format64_list(channel_layouts);
1107     if ((ret = ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts)) < 0)
1108         return ret;
1109
1110     formats = ff_all_samplerates();
1111     if ((ret = ff_formats_ref(formats, &inlink->out_samplerates)) < 0)
1112         return ret;
1113
1114     /* set output video format */
1115     formats = ff_make_format_list(pix_fmts);
1116     if ((ret = ff_formats_ref(formats, &outlink->in_formats)) < 0)
1117         return ret;
1118
1119     return 0;
1120 }
1121
1122 static int config_output(AVFilterLink *outlink)
1123 {
1124     AVFilterContext *ctx = outlink->src;
1125     AVFilterLink *inlink = ctx->inputs[0];
1126     ShowCQTContext *s = ctx->priv;
1127     int ret;
1128
1129     common_uninit(s);
1130
1131     outlink->w = s->width;
1132     outlink->h = s->height;
1133     s->format = outlink->format;
1134     outlink->sample_aspect_ratio = av_make_q(1, 1);
1135     outlink->frame_rate = s->rate;
1136     outlink->time_base = av_mul_q(av_inv_q(s->rate), av_make_q(1, PTS_STEP));
1137     av_log(ctx, AV_LOG_INFO, "video: %dx%d %s %d/%d fps, bar_h = %d, axis_h = %d, sono_h = %d.\n",
1138            s->width, s->height, av_get_pix_fmt_name(s->format), s->rate.num, s->rate.den,
1139            s->bar_h, s->axis_h, s->sono_h);
1140
1141     s->cqt_len = s->width * s->fcount;
1142     if (!(s->freq = create_freq_table(s->basefreq, s->endfreq, s->cqt_len)))
1143         return AVERROR(ENOMEM);
1144
1145     if ((ret = init_volume(s)) < 0)
1146         return ret;
1147
1148     s->fft_bits = ceil(log2(inlink->sample_rate * s->timeclamp));
1149     s->fft_len = 1 << s->fft_bits;
1150     av_log(ctx, AV_LOG_INFO, "fft_len = %d, cqt_len = %d.\n", s->fft_len, s->cqt_len);
1151
1152     s->fft_ctx = av_fft_init(s->fft_bits, 0);
1153     s->fft_data = av_calloc(s->fft_len, sizeof(*s->fft_data));
1154     s->fft_result = av_calloc(s->fft_len + 64, sizeof(*s->fft_result));
1155     s->cqt_result = av_malloc_array(s->cqt_len, sizeof(*s->cqt_result));
1156     if (!s->fft_ctx || !s->fft_data || !s->fft_result || !s->cqt_result)
1157         return AVERROR(ENOMEM);
1158
1159     s->cqt_align = 1;
1160     s->cqt_coeffs_type = COEFFS_TYPE_DEFAULT;
1161     s->cqt_calc = cqt_calc;
1162     s->draw_sono = draw_sono;
1163     if (s->format == AV_PIX_FMT_RGB24) {
1164         s->draw_bar = draw_bar_rgb;
1165         s->draw_axis = draw_axis_rgb;
1166         s->update_sono = update_sono_rgb;
1167     } else {
1168         s->draw_bar = draw_bar_yuv;
1169         s->draw_axis = draw_axis_yuv;
1170         s->update_sono = update_sono_yuv;
1171     }
1172
1173     if ((ret = init_cqt(s)) < 0)
1174         return ret;
1175
1176     if (s->axis_h) {
1177         if (!s->axis) {
1178             if ((ret = init_axis_empty(s)) < 0)
1179                 return ret;
1180         } else if (s->axisfile) {
1181             if (init_axis_from_file(s) < 0) {
1182                 av_log(ctx, AV_LOG_WARNING, "loading axis image failed, fallback to font rendering.\n");
1183                 if (init_axis_from_font(s) < 0) {
1184                     av_log(ctx, AV_LOG_WARNING, "loading axis font failed, disable text drawing.\n");
1185                     if ((ret = init_axis_empty(s)) < 0)
1186                         return ret;
1187                 }
1188             }
1189         } else {
1190             if (init_axis_from_font(s) < 0) {
1191                 av_log(ctx, AV_LOG_WARNING, "loading axis font failed, disable text drawing.\n");
1192                 if ((ret = init_axis_empty(s)) < 0)
1193                     return ret;
1194             }
1195         }
1196     }
1197
1198     if (s->sono_h) {
1199         s->sono_frame = alloc_frame_empty((outlink->format == AV_PIX_FMT_YUV420P) ?
1200                         AV_PIX_FMT_YUV422P : outlink->format, s->width, s->sono_h);
1201         if (!s->sono_frame)
1202             return AVERROR(ENOMEM);
1203     }
1204
1205     s->h_buf = av_malloc_array(s->cqt_len, sizeof (*s->h_buf));
1206     s->rcp_h_buf = av_malloc_array(s->width, sizeof(*s->rcp_h_buf));
1207     s->c_buf = av_malloc_array(s->width, sizeof(*s->c_buf));
1208     if (!s->h_buf || !s->rcp_h_buf || !s->c_buf)
1209         return AVERROR(ENOMEM);
1210
1211     s->sono_count = 0;
1212     s->next_pts = 0;
1213     s->sono_idx = 0;
1214     s->remaining_fill = s->fft_len / 2;
1215     s->remaining_frac = 0;
1216     s->step_frac = av_div_q(av_make_q(inlink->sample_rate, s->count) , s->rate);
1217     s->step = (int)(s->step_frac.num / s->step_frac.den);
1218     s->step_frac.num %= s->step_frac.den;
1219     if (s->step_frac.num) {
1220         av_log(ctx, AV_LOG_INFO, "audio: %d Hz, step = %d + %d/%d.\n",
1221                inlink->sample_rate, s->step, s->step_frac.num, s->step_frac.den);
1222         av_log(ctx, AV_LOG_WARNING, "fractional step.\n");
1223     } else {
1224         av_log(ctx, AV_LOG_INFO, "audio: %d Hz, step = %d.\n",
1225                inlink->sample_rate, s->step);
1226     }
1227
1228     return 0;
1229 }
1230
1231
1232 static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
1233 {
1234     AVFilterContext *ctx = inlink->dst;
1235     AVFilterLink *outlink = ctx->outputs[0];
1236     ShowCQTContext *s = ctx->priv;
1237     int remaining, step, ret, x, i, j, m;
1238     float *audio_data;
1239     AVFrame *out = NULL;
1240
1241     if (!insamples) {
1242         while (s->remaining_fill < s->fft_len / 2) {
1243             memset(&s->fft_data[s->fft_len - s->remaining_fill], 0, sizeof(*s->fft_data) * s->remaining_fill);
1244             ret = plot_cqt(ctx, &out);
1245             if (ret < 0)
1246                 return ret;
1247
1248             step = s->step + (s->step_frac.num + s->remaining_frac) / s->step_frac.den;
1249             s->remaining_frac = (s->step_frac.num + s->remaining_frac) % s->step_frac.den;
1250             for (x = 0; x < (s->fft_len-step); x++)
1251                 s->fft_data[x] = s->fft_data[x+step];
1252             s->remaining_fill += step;
1253
1254             if (out)
1255                 return ff_filter_frame(outlink, out);
1256         }
1257         return AVERROR_EOF;
1258     }
1259
1260     remaining = insamples->nb_samples;
1261     audio_data = (float*) insamples->data[0];
1262
1263     while (remaining) {
1264         i = insamples->nb_samples - remaining;
1265         j = s->fft_len - s->remaining_fill;
1266         if (remaining >= s->remaining_fill) {
1267             for (m = 0; m < s->remaining_fill; m++) {
1268                 s->fft_data[j+m].re = audio_data[2*(i+m)];
1269                 s->fft_data[j+m].im = audio_data[2*(i+m)+1];
1270             }
1271             ret = plot_cqt(ctx, &out);
1272             if (ret < 0) {
1273                 av_frame_free(&insamples);
1274                 return ret;
1275             }
1276             remaining -= s->remaining_fill;
1277             if (out) {
1278                 int64_t pts = av_rescale_q(insamples->pts, inlink->time_base, av_make_q(1, inlink->sample_rate));
1279                 pts += insamples->nb_samples - remaining - s->fft_len/2;
1280                 pts = av_rescale_q(pts, av_make_q(1, inlink->sample_rate), outlink->time_base);
1281                 if (FFABS(pts - out->pts) > PTS_TOLERANCE) {
1282                     av_log(ctx, AV_LOG_DEBUG, "changing pts from %"PRId64" (%.3f) to %"PRId64" (%.3f).\n",
1283                            out->pts, out->pts * av_q2d(outlink->time_base),
1284                            pts, pts * av_q2d(outlink->time_base));
1285                     out->pts = pts;
1286                     s->next_pts = pts + PTS_STEP;
1287                 }
1288                 ret = ff_filter_frame(outlink, out);
1289                 if (ret < 0) {
1290                     av_frame_free(&insamples);
1291                     return ret;
1292                 }
1293                 out = NULL;
1294             }
1295             step = s->step + (s->step_frac.num + s->remaining_frac) / s->step_frac.den;
1296             s->remaining_frac = (s->step_frac.num + s->remaining_frac) % s->step_frac.den;
1297             for (m = 0; m < s->fft_len-step; m++)
1298                 s->fft_data[m] = s->fft_data[m+step];
1299             s->remaining_fill = step;
1300         } else {
1301             for (m = 0; m < remaining; m++) {
1302                 s->fft_data[j+m].re = audio_data[2*(i+m)];
1303                 s->fft_data[j+m].im = audio_data[2*(i+m)+1];
1304             }
1305             s->remaining_fill -= remaining;
1306             remaining = 0;
1307         }
1308     }
1309     av_frame_free(&insamples);
1310     return 0;
1311 }
1312
1313 static int request_frame(AVFilterLink *outlink)
1314 {
1315     AVFilterLink *inlink = outlink->src->inputs[0];
1316     int ret;
1317
1318     ret = ff_request_frame(inlink);
1319     if (ret == AVERROR_EOF)
1320         ret = filter_frame(inlink, NULL);
1321     return ret;
1322 }
1323
1324 static const AVFilterPad showcqt_inputs[] = {
1325     {
1326         .name         = "default",
1327         .type         = AVMEDIA_TYPE_AUDIO,
1328         .filter_frame = filter_frame,
1329     },
1330     { NULL }
1331 };
1332
1333 static const AVFilterPad showcqt_outputs[] = {
1334     {
1335         .name          = "default",
1336         .type          = AVMEDIA_TYPE_VIDEO,
1337         .config_props  = config_output,
1338         .request_frame = request_frame,
1339     },
1340     { NULL }
1341 };
1342
1343 AVFilter ff_avf_showcqt = {
1344     .name          = "showcqt",
1345     .description   = NULL_IF_CONFIG_SMALL("Convert input audio to a CQT (Constant/Clamped Q Transform) spectrum video output."),
1346     .init          = init,
1347     .uninit        = uninit,
1348     .query_formats = query_formats,
1349     .priv_size     = sizeof(ShowCQTContext),
1350     .inputs        = showcqt_inputs,
1351     .outputs       = showcqt_outputs,
1352     .priv_class    = &showcqt_class,
1353 };