]> git.sesse.net Git - ffmpeg/blob - libavfilter/avf_showcqt.c
Merge commit '24e87f7f425a52b1e69661dcb2fbe0555a76f30b'
[ffmpeg] / libavfilter / avf_showcqt.c
1 /*
2  * Copyright (c) 2014 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 "config.h"
22 #include "libavcodec/avfft.h"
23 #include "libavutil/avassert.h"
24 #include "libavutil/channel_layout.h"
25 #include "libavutil/opt.h"
26 #include "libavutil/xga_font_data.h"
27 #include "libavutil/qsort.h"
28 #include "libavutil/time.h"
29 #include "libavutil/eval.h"
30 #include "avfilter.h"
31 #include "internal.h"
32
33 #include <math.h>
34 #include <stdlib.h>
35
36 #if CONFIG_LIBFREETYPE
37 #include <ft2build.h>
38 #include FT_FREETYPE_H
39 #endif
40
41 /* this filter is designed to do 16 bins/semitones constant Q transform with Brown-Puckette algorithm
42  * start from E0 to D#10 (10 octaves)
43  * so there are 16 bins/semitones * 12 semitones/octaves * 10 octaves = 1920 bins
44  * match with full HD resolution */
45
46 #define VIDEO_WIDTH 1920
47 #define VIDEO_HEIGHT 1080
48 #define FONT_HEIGHT 32
49 #define SPECTOGRAM_HEIGHT ((VIDEO_HEIGHT-FONT_HEIGHT)/2)
50 #define SPECTOGRAM_START (VIDEO_HEIGHT-SPECTOGRAM_HEIGHT)
51 #define BASE_FREQ 20.051392800492
52 #define COEFF_CLAMP 1.0e-4
53 #define TLENGTH_MIN 0.001
54 #define TLENGTH_DEFAULT "384/f*tc/(384/f+tc)"
55 #define VOLUME_MIN 1e-10
56 #define VOLUME_MAX 100.0
57
58 typedef struct {
59     FFTSample value;
60     int index;
61 } SparseCoeff;
62
63 typedef struct {
64     const AVClass *class;
65     AVFrame *outpicref;
66     FFTContext *fft_context;
67     FFTComplex *fft_data;
68     FFTComplex *fft_result_left;
69     FFTComplex *fft_result_right;
70     uint8_t *spectogram;
71     SparseCoeff *coeff_sort;
72     SparseCoeff *coeffs[VIDEO_WIDTH];
73     uint8_t *font_alpha;
74     char *fontfile;     /* using freetype */
75     int coeffs_len[VIDEO_WIDTH];
76     uint8_t font_color[VIDEO_WIDTH];
77     int64_t frame_count;
78     int spectogram_count;
79     int spectogram_index;
80     int fft_bits;
81     int req_fullfilled;
82     int remaining_fill;
83     char *tlength;
84     char *volume;
85     double timeclamp;   /* lower timeclamp, time-accurate, higher timeclamp, freq-accurate (at low freq)*/
86     float coeffclamp;   /* lower coeffclamp, more precise, higher coeffclamp, faster */
87     int fullhd;         /* if true, output video is at full HD resolution, otherwise it will be halved */
88     float gamma;        /* lower gamma, more contrast, higher gamma, more range */
89     int fps;            /* the required fps is so strict, so it's enough to be int, but 24000/1001 etc cannot be encoded */
90     int count;          /* fps * count = transform rate */
91 } ShowCQTContext;
92
93 #define OFFSET(x) offsetof(ShowCQTContext, x)
94 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
95
96 static const AVOption showcqt_options[] = {
97     { "volume", "set volume", OFFSET(volume), AV_OPT_TYPE_STRING, { .str = "16" }, CHAR_MIN, CHAR_MAX, FLAGS },
98     { "tlength", "set transform length", OFFSET(tlength), AV_OPT_TYPE_STRING, { .str = TLENGTH_DEFAULT }, CHAR_MIN, CHAR_MAX, FLAGS },
99     { "timeclamp", "set timeclamp", OFFSET(timeclamp), AV_OPT_TYPE_DOUBLE, { .dbl = 0.17 }, 0.1, 1.0, FLAGS },
100     { "coeffclamp", "set coeffclamp", OFFSET(coeffclamp), AV_OPT_TYPE_FLOAT, { .dbl = 1 }, 0.1, 10, FLAGS },
101     { "gamma", "set gamma", OFFSET(gamma), AV_OPT_TYPE_FLOAT, { .dbl = 3 }, 1, 7, FLAGS },
102     { "fullhd", "set full HD resolution", OFFSET(fullhd), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, FLAGS },
103     { "fps", "set video fps", OFFSET(fps), AV_OPT_TYPE_INT, { .i64 = 25 }, 10, 100, FLAGS },
104     { "count", "set number of transform per frame", OFFSET(count), AV_OPT_TYPE_INT, { .i64 = 6 }, 1, 30, FLAGS },
105     { "fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, { .str = NULL }, CHAR_MIN, CHAR_MAX, FLAGS },
106     { NULL }
107 };
108
109 AVFILTER_DEFINE_CLASS(showcqt);
110
111 static av_cold void uninit(AVFilterContext *ctx)
112 {
113     int k;
114
115     ShowCQTContext *s = ctx->priv;
116     av_fft_end(s->fft_context);
117     s->fft_context = NULL;
118     for (k = 0; k < VIDEO_WIDTH; k++)
119         av_freep(&s->coeffs[k]);
120     av_freep(&s->fft_data);
121     av_freep(&s->fft_result_left);
122     av_freep(&s->fft_result_right);
123     av_freep(&s->coeff_sort);
124     av_freep(&s->spectogram);
125     av_freep(&s->font_alpha);
126     av_frame_free(&s->outpicref);
127 }
128
129 static int query_formats(AVFilterContext *ctx)
130 {
131     AVFilterFormats *formats = NULL;
132     AVFilterChannelLayouts *layouts = NULL;
133     AVFilterLink *inlink = ctx->inputs[0];
134     AVFilterLink *outlink = ctx->outputs[0];
135     static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_NONE };
136     static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_RGB24, AV_PIX_FMT_NONE };
137     static const int64_t channel_layouts[] = { AV_CH_LAYOUT_STEREO, AV_CH_LAYOUT_STEREO_DOWNMIX, -1 };
138     static const int samplerates[] = { 44100, 48000, -1 };
139
140     /* set input audio formats */
141     formats = ff_make_format_list(sample_fmts);
142     if (!formats)
143         return AVERROR(ENOMEM);
144     ff_formats_ref(formats, &inlink->out_formats);
145
146     layouts = avfilter_make_format64_list(channel_layouts);
147     if (!layouts)
148         return AVERROR(ENOMEM);
149     ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts);
150
151     formats = ff_make_format_list(samplerates);
152     if (!formats)
153         return AVERROR(ENOMEM);
154     ff_formats_ref(formats, &inlink->out_samplerates);
155
156     /* set output video format */
157     formats = ff_make_format_list(pix_fmts);
158     if (!formats)
159         return AVERROR(ENOMEM);
160     ff_formats_ref(formats, &outlink->in_formats);
161
162     return 0;
163 }
164
165 #if CONFIG_LIBFREETYPE
166 static void load_freetype_font(AVFilterContext *ctx)
167 {
168     static const char str[] = "EF G A BC D ";
169     ShowCQTContext *s = ctx->priv;
170     FT_Library lib = NULL;
171     FT_Face face = NULL;
172     int video_scale = s->fullhd ? 2 : 1;
173     int video_width = (VIDEO_WIDTH/2) * video_scale;
174     int font_height = (FONT_HEIGHT/2) * video_scale;
175     int font_width = 8 * video_scale;
176     int font_repeat = font_width * 12;
177     int linear_hori_advance = font_width * 65536;
178     int non_monospace_warning = 0;
179     int x;
180
181     s->font_alpha = NULL;
182
183     if (!s->fontfile)
184         return;
185
186     if (FT_Init_FreeType(&lib))
187         goto fail;
188
189     if (FT_New_Face(lib, s->fontfile, 0, &face))
190         goto fail;
191
192     if (FT_Set_Char_Size(face, 16*64, 0, 0, 0))
193         goto fail;
194
195     if (FT_Load_Char(face, 'A', FT_LOAD_RENDER))
196         goto fail;
197
198     if (FT_Set_Char_Size(face, 16*64 * linear_hori_advance / face->glyph->linearHoriAdvance, 0, 0, 0))
199         goto fail;
200
201     s->font_alpha = av_malloc(font_height * video_width);
202     if (!s->font_alpha)
203         goto fail;
204
205     memset(s->font_alpha, 0, font_height * video_width);
206
207     for (x = 0; x < 12; x++) {
208         int sx, sy, rx, bx, by, dx, dy;
209
210         if (str[x] == ' ')
211             continue;
212
213         if (FT_Load_Char(face, str[x], FT_LOAD_RENDER))
214             goto fail;
215
216         if (face->glyph->advance.x != font_width*64 && !non_monospace_warning) {
217             av_log(ctx, AV_LOG_WARNING, "Font is not monospace\n");
218             non_monospace_warning = 1;
219         }
220
221         sy = font_height - 4*video_scale - face->glyph->bitmap_top;
222         for (rx = 0; rx < 10; rx++) {
223             sx = rx * font_repeat + x * font_width + face->glyph->bitmap_left;
224             for (by = 0; by < face->glyph->bitmap.rows; by++) {
225                 dy = by + sy;
226                 if (dy < 0)
227                     continue;
228                 if (dy >= font_height)
229                     break;
230
231                 for (bx = 0; bx < face->glyph->bitmap.width; bx++) {
232                     dx = bx + sx;
233                     if (dx < 0)
234                         continue;
235                     if (dx >= video_width)
236                         break;
237                     s->font_alpha[dy*video_width+dx] = face->glyph->bitmap.buffer[by*face->glyph->bitmap.width+bx];
238                 }
239             }
240         }
241     }
242
243     FT_Done_Face(face);
244     FT_Done_FreeType(lib);
245     return;
246
247     fail:
248     av_log(ctx, AV_LOG_WARNING, "Error while loading freetype font, using default font instead\n");
249     FT_Done_Face(face);
250     FT_Done_FreeType(lib);
251     av_freep(&s->font_alpha);
252     return;
253 }
254 #endif
255
256 static double a_weighting(void *p, double f)
257 {
258     double ret = 12200.0*12200.0 * (f*f*f*f);
259     ret /= (f*f + 20.6*20.6) * (f*f + 12200.0*12200.0) *
260            sqrt((f*f + 107.7*107.7) * (f*f + 737.9*737.9));
261     return ret;
262 }
263
264 static double b_weighting(void *p, double f)
265 {
266     double ret = 12200.0*12200.0 * (f*f*f);
267     ret /= (f*f + 20.6*20.6) * (f*f + 12200.0*12200.0) * sqrt(f*f + 158.5*158.5);
268     return ret;
269 }
270
271 static double c_weighting(void *p, double f)
272 {
273     double ret = 12200.0*12200.0 * (f*f);
274     ret /= (f*f + 20.6*20.6) * (f*f + 12200.0*12200.0);
275     return ret;
276 }
277
278 static inline int qsort_sparsecoeff(const SparseCoeff *a, const SparseCoeff *b)
279 {
280     if (fabsf(a->value) >= fabsf(b->value))
281         return 1;
282     else
283         return -1;
284 }
285
286 static int config_output(AVFilterLink *outlink)
287 {
288     AVFilterContext *ctx = outlink->src;
289     AVFilterLink *inlink = ctx->inputs[0];
290     ShowCQTContext *s = ctx->priv;
291     AVExpr *tlength_expr, *volume_expr;
292     static const char * const expr_vars[] = { "timeclamp", "tc", "frequency", "freq", "f", NULL };
293     static const char * const expr_func_names[] = { "a_weighting", "b_weighting", "c_weighting", NULL };
294     static double (* const expr_funcs[])(void *, double) = { a_weighting, b_weighting, c_weighting, NULL };
295     int fft_len, k, x, y, ret;
296     int num_coeffs = 0;
297     int rate = inlink->sample_rate;
298     double max_len = rate * (double) s->timeclamp;
299     int64_t start_time, end_time;
300     int video_scale = s->fullhd ? 2 : 1;
301     int video_width = (VIDEO_WIDTH/2) * video_scale;
302     int video_height = (VIDEO_HEIGHT/2) * video_scale;
303     int spectogram_height = (SPECTOGRAM_HEIGHT/2) * video_scale;
304
305     s->fft_bits = ceil(log2(max_len));
306     fft_len = 1 << s->fft_bits;
307
308     if (rate % (s->fps * s->count)) {
309         av_log(ctx, AV_LOG_ERROR, "Rate (%u) is not divisible by fps*count (%u*%u)\n", rate, s->fps, s->count);
310         return AVERROR(EINVAL);
311     }
312
313     s->fft_data         = av_malloc_array(fft_len, sizeof(*s->fft_data));
314     s->coeff_sort       = av_malloc_array(fft_len, sizeof(*s->coeff_sort));
315     s->fft_result_left  = av_malloc_array(fft_len, sizeof(*s->fft_result_left));
316     s->fft_result_right = av_malloc_array(fft_len, sizeof(*s->fft_result_right));
317     s->fft_context      = av_fft_init(s->fft_bits, 0);
318
319     if (!s->fft_data || !s->coeff_sort || !s->fft_result_left || !s->fft_result_right || !s->fft_context)
320         return AVERROR(ENOMEM);
321
322     /* initializing font */
323     for (x = 0; x < video_width; x++) {
324         if (x >= (12*3+8)*8*video_scale && x < (12*4+8)*8*video_scale) {
325             float fx = (x-(12*3+8)*8*video_scale) * (2.0f/(192.0f*video_scale));
326             float sv = sinf(M_PI*fx);
327             s->font_color[x] = sv*sv*255.0f + 0.5f;
328         } else {
329             s->font_color[x] = 0;
330         }
331     }
332
333 #if CONFIG_LIBFREETYPE
334     load_freetype_font(ctx);
335 #else
336     if (s->fontfile)
337         av_log(ctx, AV_LOG_WARNING, "Freetype is not available, ignoring fontfile option\n");
338     s->font_alpha = NULL;
339 #endif
340
341     av_log(ctx, AV_LOG_INFO, "Calculating spectral kernel, please wait\n");
342     start_time = av_gettime_relative();
343     ret = av_expr_parse(&tlength_expr, s->tlength, expr_vars, NULL, NULL, NULL, NULL, 0, ctx);
344     if (ret < 0)
345         return ret;
346     ret = av_expr_parse(&volume_expr, s->volume, expr_vars, expr_func_names,
347                         expr_funcs, NULL, NULL, 0, ctx);
348     if (ret < 0) {
349         av_expr_free(tlength_expr);
350         return ret;
351     }
352     for (k = 0; k < VIDEO_WIDTH; k++) {
353         int hlen = fft_len >> 1;
354         float total = 0;
355         float partial = 0;
356         double freq = BASE_FREQ * exp2(k * (1.0/192.0));
357         double tlen, tlength, volume;
358         double expr_vars_val[] = { s->timeclamp, s->timeclamp, freq, freq, freq, 0 };
359         /* a window function from Albert H. Nuttall,
360          * "Some Windows with Very Good Sidelobe Behavior"
361          * -93.32 dB peak sidelobe and 18 dB/octave asymptotic decay
362          * coefficient normalized to a0 = 1 */
363         double a0 = 0.355768;
364         double a1 = 0.487396/a0;
365         double a2 = 0.144232/a0;
366         double a3 = 0.012604/a0;
367         double sv_step, cv_step, sv, cv;
368         double sw_step, cw_step, sw, cw, w;
369
370         tlength = av_expr_eval(tlength_expr, expr_vars_val, NULL);
371         if (isnan(tlength)) {
372             av_log(ctx, AV_LOG_WARNING, "at freq %g: tlength is nan, setting it to %g\n", freq, s->timeclamp);
373             tlength = s->timeclamp;
374         } else if (tlength < TLENGTH_MIN) {
375             av_log(ctx, AV_LOG_WARNING, "at freq %g: tlength is %g, setting it to %g\n", freq, tlength, TLENGTH_MIN);
376             tlength = TLENGTH_MIN;
377         } else if (tlength > s->timeclamp) {
378             av_log(ctx, AV_LOG_WARNING, "at freq %g: tlength is %g, setting it to %g\n", freq, tlength, s->timeclamp);
379             tlength = s->timeclamp;
380         }
381
382         volume = FFABS(av_expr_eval(volume_expr, expr_vars_val, NULL));
383         if (isnan(volume)) {
384             av_log(ctx, AV_LOG_WARNING, "at freq %g: volume is nan, setting it to 0\n", freq);
385             volume = VOLUME_MIN;
386         } else if (volume < VOLUME_MIN) {
387             volume = VOLUME_MIN;
388         } else if (volume > VOLUME_MAX) {
389             av_log(ctx, AV_LOG_WARNING, "at freq %g: volume is %g, setting it to %g\n", freq, volume, VOLUME_MAX);
390             volume = VOLUME_MAX;
391         }
392
393         tlen = tlength * rate;
394         s->fft_data[0].re = 0;
395         s->fft_data[0].im = 0;
396         s->fft_data[hlen].re = (1.0 + a1 + a2 + a3) * (1.0/tlen) * volume * (1.0/fft_len);
397         s->fft_data[hlen].im = 0;
398         sv_step = sv = sin(2.0*M_PI*freq*(1.0/rate));
399         cv_step = cv = cos(2.0*M_PI*freq*(1.0/rate));
400         /* also optimizing window func */
401         sw_step = sw = sin(2.0*M_PI*(1.0/tlen));
402         cw_step = cw = cos(2.0*M_PI*(1.0/tlen));
403         for (x = 1; x < 0.5 * tlen; x++) {
404             double cv_tmp, cw_tmp;
405             double cw2, cw3, sw2;
406
407             cw2 = cw * cw - sw * sw;
408             sw2 = cw * sw + sw * cw;
409             cw3 = cw * cw2 - sw * sw2;
410             w = (1.0 + a1 * cw + a2 * cw2 + a3 * cw3) * (1.0/tlen) * volume * (1.0/fft_len);
411             s->fft_data[hlen + x].re = w * cv;
412             s->fft_data[hlen + x].im = w * sv;
413             s->fft_data[hlen - x].re = s->fft_data[hlen + x].re;
414             s->fft_data[hlen - x].im = -s->fft_data[hlen + x].im;
415
416             cv_tmp = cv * cv_step - sv * sv_step;
417             sv = sv * cv_step + cv * sv_step;
418             cv = cv_tmp;
419             cw_tmp = cw * cw_step - sw * sw_step;
420             sw = sw * cw_step + cw * sw_step;
421             cw = cw_tmp;
422         }
423         for (; x < hlen; x++) {
424             s->fft_data[hlen + x].re = 0;
425             s->fft_data[hlen + x].im = 0;
426             s->fft_data[hlen - x].re = 0;
427             s->fft_data[hlen - x].im = 0;
428         }
429         av_fft_permute(s->fft_context, s->fft_data);
430         av_fft_calc(s->fft_context, s->fft_data);
431
432         for (x = 0; x < fft_len; x++) {
433             s->coeff_sort[x].index = x;
434             s->coeff_sort[x].value = s->fft_data[x].re;
435         }
436
437         AV_QSORT(s->coeff_sort, fft_len, SparseCoeff, qsort_sparsecoeff);
438         for (x = 0; x < fft_len; x++)
439             total += fabsf(s->coeff_sort[x].value);
440
441         for (x = 0; x < fft_len; x++) {
442             partial += fabsf(s->coeff_sort[x].value);
443             if (partial > total * s->coeffclamp * COEFF_CLAMP) {
444                 s->coeffs_len[k] = fft_len - x;
445                 num_coeffs += s->coeffs_len[k];
446                 s->coeffs[k] = av_malloc_array(s->coeffs_len[k], sizeof(*s->coeffs[k]));
447                 if (!s->coeffs[k]) {
448                     av_expr_free(volume_expr);
449                     av_expr_free(tlength_expr);
450                     return AVERROR(ENOMEM);
451                 }
452                 for (y = 0; y < s->coeffs_len[k]; y++)
453                     s->coeffs[k][y] = s->coeff_sort[x+y];
454                 break;
455             }
456         }
457     }
458     av_expr_free(volume_expr);
459     av_expr_free(tlength_expr);
460     end_time = av_gettime_relative();
461     av_log(ctx, AV_LOG_INFO, "Elapsed time %.6f s (fft_len=%u, num_coeffs=%u)\n", 1e-6 * (end_time-start_time), fft_len, num_coeffs);
462
463     outlink->w = video_width;
464     outlink->h = video_height;
465
466     s->req_fullfilled = 0;
467     s->spectogram_index = 0;
468     s->frame_count = 0;
469     s->spectogram_count = 0;
470     s->remaining_fill = fft_len >> 1;
471     memset(s->fft_data, 0, fft_len * sizeof(*s->fft_data));
472
473     s->outpicref = ff_get_video_buffer(outlink, outlink->w, outlink->h);
474     if (!s->outpicref)
475         return AVERROR(ENOMEM);
476
477     s->spectogram = av_calloc(spectogram_height, s->outpicref->linesize[0]);
478     if (!s->spectogram)
479         return AVERROR(ENOMEM);
480
481     outlink->sample_aspect_ratio = av_make_q(1, 1);
482     outlink->time_base = av_make_q(1, s->fps);
483     outlink->frame_rate = av_make_q(s->fps, 1);
484     return 0;
485 }
486
487 static int plot_cqt(AVFilterLink *inlink)
488 {
489     AVFilterContext *ctx = inlink->dst;
490     ShowCQTContext *s = ctx->priv;
491     AVFilterLink *outlink = ctx->outputs[0];
492     int fft_len = 1 << s->fft_bits;
493     FFTSample result[VIDEO_WIDTH][4];
494     int x, y, ret = 0;
495     int linesize = s->outpicref->linesize[0];
496     int video_scale = s->fullhd ? 2 : 1;
497     int video_width = (VIDEO_WIDTH/2) * video_scale;
498     int spectogram_height = (SPECTOGRAM_HEIGHT/2) * video_scale;
499     int spectogram_start = (SPECTOGRAM_START/2) * video_scale;
500     int font_height = (FONT_HEIGHT/2) * video_scale;
501
502     /* real part contains left samples, imaginary part contains right samples */
503     memcpy(s->fft_result_left, s->fft_data, fft_len * sizeof(*s->fft_data));
504     av_fft_permute(s->fft_context, s->fft_result_left);
505     av_fft_calc(s->fft_context, s->fft_result_left);
506
507     /* separate left and right, (and multiply by 2.0) */
508     s->fft_result_right[0].re = 2.0f * s->fft_result_left[0].im;
509     s->fft_result_right[0].im = 0;
510     s->fft_result_left[0].re = 2.0f * s->fft_result_left[0].re;
511     s->fft_result_left[0].im = 0;
512     for (x = 1; x <= fft_len >> 1; x++) {
513         FFTSample tmpy = s->fft_result_left[fft_len-x].im - s->fft_result_left[x].im;
514
515         s->fft_result_right[x].re = s->fft_result_left[x].im + s->fft_result_left[fft_len-x].im;
516         s->fft_result_right[x].im = s->fft_result_left[x].re - s->fft_result_left[fft_len-x].re;
517         s->fft_result_right[fft_len-x].re = s->fft_result_right[x].re;
518         s->fft_result_right[fft_len-x].im = -s->fft_result_right[x].im;
519
520         s->fft_result_left[x].re = s->fft_result_left[x].re + s->fft_result_left[fft_len-x].re;
521         s->fft_result_left[x].im = tmpy;
522         s->fft_result_left[fft_len-x].re = s->fft_result_left[x].re;
523         s->fft_result_left[fft_len-x].im = -s->fft_result_left[x].im;
524     }
525
526     /* calculating cqt */
527     for (x = 0; x < VIDEO_WIDTH; x++) {
528         int u;
529         float g = 1.0f / s->gamma;
530         FFTComplex l = {0,0};
531         FFTComplex r = {0,0};
532
533         for (u = 0; u < s->coeffs_len[x]; u++) {
534             FFTSample value = s->coeffs[x][u].value;
535             int index = s->coeffs[x][u].index;
536             l.re += value * s->fft_result_left[index].re;
537             l.im += value * s->fft_result_left[index].im;
538             r.re += value * s->fft_result_right[index].re;
539             r.im += value * s->fft_result_right[index].im;
540         }
541         /* result is power, not amplitude */
542         result[x][0] = l.re * l.re + l.im * l.im;
543         result[x][2] = r.re * r.re + r.im * r.im;
544         result[x][1] = 0.5f * (result[x][0] + result[x][2]);
545         result[x][3] = result[x][1];
546         result[x][0] = 255.0f * powf(FFMIN(1.0f,result[x][0]), g);
547         result[x][1] = 255.0f * powf(FFMIN(1.0f,result[x][1]), g);
548         result[x][2] = 255.0f * powf(FFMIN(1.0f,result[x][2]), g);
549     }
550
551     if (!s->fullhd) {
552         for (x = 0; x < video_width; x++) {
553             result[x][0] = 0.5f * (result[2*x][0] + result[2*x+1][0]);
554             result[x][1] = 0.5f * (result[2*x][1] + result[2*x+1][1]);
555             result[x][2] = 0.5f * (result[2*x][2] + result[2*x+1][2]);
556             result[x][3] = 0.5f * (result[2*x][3] + result[2*x+1][3]);
557         }
558     }
559
560     for (x = 0; x < video_width; x++) {
561         s->spectogram[s->spectogram_index*linesize + 3*x] = result[x][0] + 0.5f;
562         s->spectogram[s->spectogram_index*linesize + 3*x + 1] = result[x][1] + 0.5f;
563         s->spectogram[s->spectogram_index*linesize + 3*x + 2] = result[x][2] + 0.5f;
564     }
565
566     /* drawing */
567     if (!s->spectogram_count) {
568         uint8_t *data = (uint8_t*) s->outpicref->data[0];
569         float rcp_result[VIDEO_WIDTH];
570         int total_length = linesize * spectogram_height;
571         int back_length = linesize * s->spectogram_index;
572
573         for (x = 0; x < video_width; x++)
574             rcp_result[x] = 1.0f / (result[x][3]+0.0001f);
575
576         /* drawing bar */
577         for (y = 0; y < spectogram_height; y++) {
578             float height = (spectogram_height - y) * (1.0f/spectogram_height);
579             uint8_t *lineptr = data + y * linesize;
580             for (x = 0; x < video_width; x++) {
581                 float mul;
582                 if (result[x][3] <= height) {
583                     *lineptr++ = 0;
584                     *lineptr++ = 0;
585                     *lineptr++ = 0;
586                 } else {
587                     mul = (result[x][3] - height) * rcp_result[x];
588                     *lineptr++ = mul * result[x][0] + 0.5f;
589                     *lineptr++ = mul * result[x][1] + 0.5f;
590                     *lineptr++ = mul * result[x][2] + 0.5f;
591                 }
592             }
593         }
594
595         /* drawing font */
596         if (s->font_alpha) {
597             for (y = 0; y < font_height; y++) {
598                 uint8_t *lineptr = data + (spectogram_height + y) * linesize;
599                 uint8_t *spectogram_src = s->spectogram + s->spectogram_index * linesize;
600                 for (x = 0; x < video_width; x++) {
601                     uint8_t alpha = s->font_alpha[y*video_width+x];
602                     uint8_t color = s->font_color[x];
603                     lineptr[3*x] = (spectogram_src[3*x] * (255-alpha) + (255-color) * alpha + 255) >> 8;
604                     lineptr[3*x+1] = (spectogram_src[3*x+1] * (255-alpha) + 255) >> 8;
605                     lineptr[3*x+2] = (spectogram_src[3*x+2] * (255-alpha) + color * alpha + 255) >> 8;
606                 }
607             }
608         } else {
609             for (y = 0; y < font_height; y++) {
610                 uint8_t *lineptr = data + (spectogram_height + y) * linesize;
611                 memcpy(lineptr, s->spectogram + s->spectogram_index * linesize, video_width*3);
612             }
613             for (x = 0; x < video_width; x += video_width/10) {
614                 int u;
615                 static const char str[] = "EF G A BC D ";
616                 uint8_t *startptr = data + spectogram_height * linesize + x * 3;
617                 for (u = 0; str[u]; u++) {
618                     int v;
619                     for (v = 0; v < 16; v++) {
620                         uint8_t *p = startptr + v * linesize * video_scale + 8 * 3 * u * video_scale;
621                         int ux = x + 8 * u * video_scale;
622                         int mask;
623                         for (mask = 0x80; mask; mask >>= 1) {
624                             if (mask & avpriv_vga16_font[str[u] * 16 + v]) {
625                                 p[0] = 255 - s->font_color[ux];
626                                 p[1] = 0;
627                                 p[2] = s->font_color[ux];
628                                 if (video_scale == 2) {
629                                     p[linesize] = p[0];
630                                     p[linesize+1] = p[1];
631                                     p[linesize+2] = p[2];
632                                     p[3] = p[linesize+3] = 255 - s->font_color[ux+1];
633                                     p[4] = p[linesize+4] = 0;
634                                     p[5] = p[linesize+5] = s->font_color[ux+1];
635                                 }
636                             }
637                             p  += 3 * video_scale;
638                             ux += video_scale;
639                         }
640                     }
641                 }
642             }
643         }
644
645         /* drawing spectogram/sonogram */
646         data += spectogram_start * linesize;
647         memcpy(data, s->spectogram + s->spectogram_index*linesize, total_length - back_length);
648
649         data += total_length - back_length;
650         if (back_length)
651             memcpy(data, s->spectogram, back_length);
652
653         s->outpicref->pts = s->frame_count;
654         ret = ff_filter_frame(outlink, av_frame_clone(s->outpicref));
655         s->req_fullfilled = 1;
656         s->frame_count++;
657     }
658     s->spectogram_count = (s->spectogram_count + 1) % s->count;
659     s->spectogram_index = (s->spectogram_index + spectogram_height - 1) % spectogram_height;
660     return ret;
661 }
662
663 static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
664 {
665     AVFilterContext *ctx = inlink->dst;
666     ShowCQTContext *s = ctx->priv;
667     int step = inlink->sample_rate / (s->fps * s->count);
668     int fft_len = 1 << s->fft_bits;
669     int remaining;
670     float *audio_data;
671
672     if (!insamples) {
673         while (s->remaining_fill < (fft_len >> 1)) {
674             int ret, x;
675             memset(&s->fft_data[fft_len - s->remaining_fill], 0, sizeof(*s->fft_data) * s->remaining_fill);
676             ret = plot_cqt(inlink);
677             if (ret < 0)
678                 return ret;
679             for (x = 0; x < (fft_len-step); x++)
680                 s->fft_data[x] = s->fft_data[x+step];
681             s->remaining_fill += step;
682         }
683         return AVERROR(EOF);
684     }
685
686     remaining = insamples->nb_samples;
687     audio_data = (float*) insamples->data[0];
688
689     while (remaining) {
690         if (remaining >= s->remaining_fill) {
691             int i = insamples->nb_samples - remaining;
692             int j = fft_len - s->remaining_fill;
693             int m, ret;
694             for (m = 0; m < s->remaining_fill; m++) {
695                 s->fft_data[j+m].re = audio_data[2*(i+m)];
696                 s->fft_data[j+m].im = audio_data[2*(i+m)+1];
697             }
698             ret = plot_cqt(inlink);
699             if (ret < 0) {
700                 av_frame_free(&insamples);
701                 return ret;
702             }
703             remaining -= s->remaining_fill;
704             for (m = 0; m < fft_len-step; m++)
705                 s->fft_data[m] = s->fft_data[m+step];
706             s->remaining_fill = step;
707         } else {
708             int i = insamples->nb_samples - remaining;
709             int j = fft_len - s->remaining_fill;
710             int m;
711             for (m = 0; m < remaining; m++) {
712                 s->fft_data[m+j].re = audio_data[2*(i+m)];
713                 s->fft_data[m+j].im = audio_data[2*(i+m)+1];
714             }
715             s->remaining_fill -= remaining;
716             remaining = 0;
717         }
718     }
719     av_frame_free(&insamples);
720     return 0;
721 }
722
723 static int request_frame(AVFilterLink *outlink)
724 {
725     ShowCQTContext *s = outlink->src->priv;
726     AVFilterLink *inlink = outlink->src->inputs[0];
727     int ret;
728
729     s->req_fullfilled = 0;
730     do {
731         ret = ff_request_frame(inlink);
732     } while (!s->req_fullfilled && ret >= 0);
733
734     if (ret == AVERROR_EOF && s->outpicref)
735         filter_frame(inlink, NULL);
736     return ret;
737 }
738
739 static const AVFilterPad showcqt_inputs[] = {
740     {
741         .name         = "default",
742         .type         = AVMEDIA_TYPE_AUDIO,
743         .filter_frame = filter_frame,
744     },
745     { NULL }
746 };
747
748 static const AVFilterPad showcqt_outputs[] = {
749     {
750         .name          = "default",
751         .type          = AVMEDIA_TYPE_VIDEO,
752         .config_props  = config_output,
753         .request_frame = request_frame,
754     },
755     { NULL }
756 };
757
758 AVFilter ff_avf_showcqt = {
759     .name          = "showcqt",
760     .description   = NULL_IF_CONFIG_SMALL("Convert input audio to a CQT (Constant Q Transform) spectrum video output."),
761     .uninit        = uninit,
762     .query_formats = query_formats,
763     .priv_size     = sizeof(ShowCQTContext),
764     .inputs        = showcqt_inputs,
765     .outputs       = showcqt_outputs,
766     .priv_class    = &showcqt_class,
767 };