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