2 * Copyright (c) 2014 Muhammad Faiz <mfcc64@gmail.com>
4 * This file is part of FFmpeg.
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.
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.
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
21 #include "libavcodec/avfft.h"
22 #include "libavutil/avassert.h"
23 #include "libavutil/channel_layout.h"
24 #include "libavutil/opt.h"
25 #include "libavutil/xga_font_data.h"
26 #include "libavutil/qsort.h"
27 #include "libavutil/time.h"
34 /* this filter is designed to do 16 bins/semitones constant Q transform with Brown-Puckette algorithm
35 * start from E0 to D#10 (10 octaves)
36 * so there are 16 bins/semitones * 12 semitones/octaves * 10 octaves = 1920 bins
37 * match with full HD resolution */
39 #define VIDEO_WIDTH 1920
40 #define VIDEO_HEIGHT 1080
41 #define FONT_HEIGHT 32
42 #define SPECTOGRAM_HEIGHT ((VIDEO_HEIGHT-FONT_HEIGHT)/2)
43 #define SPECTOGRAM_START (VIDEO_HEIGHT-SPECTOGRAM_HEIGHT)
44 #define BASE_FREQ 20.051392800492
45 #define COEFF_CLAMP 1.0e-4
55 FFTContext *fft_context;
57 FFTComplex *fft_result_left;
58 FFTComplex *fft_result_right;
60 SparseCoeff *coeff_sort;
61 SparseCoeff *coeffs[VIDEO_WIDTH];
62 int coeffs_len[VIDEO_WIDTH];
63 uint8_t font_color[VIDEO_WIDTH];
71 double timeclamp; /* lower timeclamp, time-accurate, higher timeclamp, freq-accurate (at low freq)*/
72 float coeffclamp; /* lower coeffclamp, more precise, higher coeffclamp, faster */
73 int fullhd; /* if true, output video is at full HD resolution, otherwise it will be halved */
74 float gamma; /* lower gamma, more contrast, higher gamma, more range */
75 int fps; /* the required fps is so strict, so it's enough to be int, but 24000/1001 etc cannot be encoded */
76 int count; /* fps * count = transform rate */
79 #define OFFSET(x) offsetof(ShowCQTContext, x)
80 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
82 static const AVOption showcqt_options[] = {
83 { "volume", "set volume", OFFSET(volume), AV_OPT_TYPE_DOUBLE, { .dbl = 16 }, 0.1, 100, FLAGS },
84 { "timeclamp", "set timeclamp", OFFSET(timeclamp), AV_OPT_TYPE_DOUBLE, { .dbl = 0.17 }, 0.1, 1.0, FLAGS },
85 { "coeffclamp", "set coeffclamp", OFFSET(coeffclamp), AV_OPT_TYPE_FLOAT, { .dbl = 1 }, 0.1, 10, FLAGS },
86 { "gamma", "set gamma", OFFSET(gamma), AV_OPT_TYPE_FLOAT, { .dbl = 3 }, 1, 7, FLAGS },
87 { "fullhd", "set full HD resolution", OFFSET(fullhd), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, FLAGS },
88 { "fps", "set video fps", OFFSET(fps), AV_OPT_TYPE_INT, { .i64 = 25 }, 10, 100, FLAGS },
89 { "count", "set number of transform per frame", OFFSET(count), AV_OPT_TYPE_INT, { .i64 = 6 }, 1, 30, FLAGS },
93 AVFILTER_DEFINE_CLASS(showcqt);
95 static av_cold void uninit(AVFilterContext *ctx)
99 ShowCQTContext *s = ctx->priv;
100 av_fft_end(s->fft_context);
101 s->fft_context = NULL;
102 for (k = 0; k < VIDEO_WIDTH; k++)
103 av_freep(&s->coeffs[k]);
104 av_freep(&s->fft_data);
105 av_freep(&s->fft_result_left);
106 av_freep(&s->fft_result_right);
107 av_freep(&s->coeff_sort);
108 av_freep(&s->spectogram);
109 av_frame_free(&s->outpicref);
112 static int query_formats(AVFilterContext *ctx)
114 AVFilterFormats *formats = NULL;
115 AVFilterChannelLayouts *layouts = NULL;
116 AVFilterLink *inlink = ctx->inputs[0];
117 AVFilterLink *outlink = ctx->outputs[0];
118 static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_NONE };
119 static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_RGB24, AV_PIX_FMT_NONE };
120 static const int64_t channel_layouts[] = { AV_CH_LAYOUT_STEREO, AV_CH_LAYOUT_STEREO_DOWNMIX, -1 };
121 static const int samplerates[] = { 44100, 48000, -1 };
123 /* set input audio formats */
124 formats = ff_make_format_list(sample_fmts);
126 return AVERROR(ENOMEM);
127 ff_formats_ref(formats, &inlink->out_formats);
129 layouts = avfilter_make_format64_list(channel_layouts);
131 return AVERROR(ENOMEM);
132 ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts);
134 formats = ff_make_format_list(samplerates);
136 return AVERROR(ENOMEM);
137 ff_formats_ref(formats, &inlink->out_samplerates);
139 /* set output video format */
140 formats = ff_make_format_list(pix_fmts);
142 return AVERROR(ENOMEM);
143 ff_formats_ref(formats, &outlink->in_formats);
148 static inline int qsort_sparsecoeff(const SparseCoeff *a, const SparseCoeff *b)
150 if (fabsf(a->value) >= fabsf(b->value))
156 static int config_output(AVFilterLink *outlink)
158 AVFilterContext *ctx = outlink->src;
159 AVFilterLink *inlink = ctx->inputs[0];
160 ShowCQTContext *s = ctx->priv;
161 int fft_len, k, x, y;
163 int rate = inlink->sample_rate;
164 double max_len = rate * (double) s->timeclamp;
165 int64_t start_time, end_time;
166 int video_scale = s->fullhd ? 2 : 1;
167 int video_width = (VIDEO_WIDTH/2) * video_scale;
168 int video_height = (VIDEO_HEIGHT/2) * video_scale;
169 int spectogram_height = (SPECTOGRAM_HEIGHT/2) * video_scale;
171 s->fft_bits = ceil(log2(max_len));
172 fft_len = 1 << s->fft_bits;
174 if (rate % (s->fps * s->count)) {
175 av_log(ctx, AV_LOG_ERROR, "Rate (%u) is not divisible by fps*count (%u*%u)\n", rate, s->fps, s->count);
176 return AVERROR(EINVAL);
179 s->fft_data = av_malloc_array(fft_len, sizeof(*s->fft_data));
180 s->coeff_sort = av_malloc_array(fft_len, sizeof(*s->coeff_sort));
181 s->fft_result_left = av_malloc_array(fft_len, sizeof(*s->fft_result_left));
182 s->fft_result_right = av_malloc_array(fft_len, sizeof(*s->fft_result_right));
183 s->fft_context = av_fft_init(s->fft_bits, 0);
185 if (!s->fft_data || !s->coeff_sort || !s->fft_result_left || !s->fft_result_right || !s->fft_context)
186 return AVERROR(ENOMEM);
188 /* initializing font */
189 for (x = 0; x < video_width; x++) {
190 if (x >= (12*3+8)*8*video_scale && x < (12*4+8)*8*video_scale) {
191 float fx = (x-(12*3+8)*8*video_scale) * (2.0f/(192.0f*video_scale));
192 float sv = sinf(M_PI*fx);
193 s->font_color[x] = sv*sv*255.0f + 0.5f;
195 s->font_color[x] = 0;
199 av_log(ctx, AV_LOG_INFO, "Calculating spectral kernel, please wait\n");
200 start_time = av_gettime_relative();
201 for (k = 0; k < VIDEO_WIDTH; k++) {
202 int hlen = fft_len >> 1;
205 double freq = BASE_FREQ * exp2(k * (1.0/192.0));
206 double tlen = rate * (24.0 * 16.0) /freq;
207 /* a window function from Albert H. Nuttall,
208 * "Some Windows with Very Good Sidelobe Behavior"
209 * -93.32 dB peak sidelobe and 18 dB/octave asymptotic decay
210 * coefficient normalized to a0 = 1 */
211 double a0 = 0.355768;
212 double a1 = 0.487396/a0;
213 double a2 = 0.144232/a0;
214 double a3 = 0.012604/a0;
215 double sv_step, cv_step, sv, cv;
216 double sw_step, cw_step, sw, cw, w;
218 tlen = tlen * max_len / (tlen + max_len);
219 s->fft_data[0].re = 0;
220 s->fft_data[0].im = 0;
221 s->fft_data[hlen].re = (1.0 + a1 + a2 + a3) * (1.0/tlen) * s->volume * (1.0/fft_len);
222 s->fft_data[hlen].im = 0;
223 sv_step = sv = sin(2.0*M_PI*freq*(1.0/rate));
224 cv_step = cv = cos(2.0*M_PI*freq*(1.0/rate));
225 /* also optimizing window func */
226 sw_step = sw = sin(2.0*M_PI*(1.0/tlen));
227 cw_step = cw = cos(2.0*M_PI*(1.0/tlen));
228 for (x = 1; x < 0.5 * tlen; x++) {
229 double cv_tmp, cw_tmp;
230 double cw2, cw3, sw2;
232 cw2 = cw * cw - sw * sw;
233 sw2 = cw * sw + sw * cw;
234 cw3 = cw * cw2 - sw * sw2;
235 w = (1.0 + a1 * cw + a2 * cw2 + a3 * cw3) * (1.0/tlen) * s->volume * (1.0/fft_len);
236 s->fft_data[hlen + x].re = w * cv;
237 s->fft_data[hlen + x].im = w * sv;
238 s->fft_data[hlen - x].re = s->fft_data[hlen + x].re;
239 s->fft_data[hlen - x].im = -s->fft_data[hlen + x].im;
241 cv_tmp = cv * cv_step - sv * sv_step;
242 sv = sv * cv_step + cv * sv_step;
244 cw_tmp = cw * cw_step - sw * sw_step;
245 sw = sw * cw_step + cw * sw_step;
248 for (; x < hlen; x++) {
249 s->fft_data[hlen + x].re = 0;
250 s->fft_data[hlen + x].im = 0;
251 s->fft_data[hlen - x].re = 0;
252 s->fft_data[hlen - x].im = 0;
254 av_fft_permute(s->fft_context, s->fft_data);
255 av_fft_calc(s->fft_context, s->fft_data);
257 for (x = 0; x < fft_len; x++) {
258 s->coeff_sort[x].index = x;
259 s->coeff_sort[x].value = s->fft_data[x].re;
262 AV_QSORT(s->coeff_sort, fft_len, SparseCoeff, qsort_sparsecoeff);
263 for (x = 0; x < fft_len; x++)
264 total += fabsf(s->coeff_sort[x].value);
266 for (x = 0; x < fft_len; x++) {
267 partial += fabsf(s->coeff_sort[x].value);
268 if (partial > total * s->coeffclamp * COEFF_CLAMP) {
269 s->coeffs_len[k] = fft_len - x;
270 num_coeffs += s->coeffs_len[k];
271 s->coeffs[k] = av_malloc_array(s->coeffs_len[k], sizeof(*s->coeffs[k]));
273 return AVERROR(ENOMEM);
274 for (y = 0; y < s->coeffs_len[k]; y++)
275 s->coeffs[k][y] = s->coeff_sort[x+y];
280 end_time = av_gettime_relative();
281 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);
283 outlink->w = video_width;
284 outlink->h = video_height;
286 s->req_fullfilled = 0;
287 s->spectogram_index = 0;
289 s->spectogram_count = 0;
290 s->remaining_fill = fft_len >> 1;
291 memset(s->fft_data, 0, fft_len * sizeof(*s->fft_data));
293 s->outpicref = ff_get_video_buffer(outlink, outlink->w, outlink->h);
295 return AVERROR(ENOMEM);
297 s->spectogram = av_calloc(spectogram_height, s->outpicref->linesize[0]);
299 return AVERROR(ENOMEM);
301 outlink->sample_aspect_ratio = av_make_q(1, 1);
302 outlink->time_base = av_make_q(1, s->fps);
303 outlink->frame_rate = av_make_q(s->fps, 1);
307 static int plot_cqt(AVFilterLink *inlink)
309 AVFilterContext *ctx = inlink->dst;
310 ShowCQTContext *s = ctx->priv;
311 AVFilterLink *outlink = ctx->outputs[0];
312 int fft_len = 1 << s->fft_bits;
313 FFTSample result[VIDEO_WIDTH][4];
315 int linesize = s->outpicref->linesize[0];
316 int video_scale = s->fullhd ? 2 : 1;
317 int video_width = (VIDEO_WIDTH/2) * video_scale;
318 int spectogram_height = (SPECTOGRAM_HEIGHT/2) * video_scale;
319 int spectogram_start = (SPECTOGRAM_START/2) * video_scale;
320 int font_height = (FONT_HEIGHT/2) * video_scale;
322 /* real part contains left samples, imaginary part contains right samples */
323 memcpy(s->fft_result_left, s->fft_data, fft_len * sizeof(*s->fft_data));
324 av_fft_permute(s->fft_context, s->fft_result_left);
325 av_fft_calc(s->fft_context, s->fft_result_left);
327 /* separate left and right, (and multiply by 2.0) */
328 s->fft_result_right[0].re = 2.0f * s->fft_result_left[0].im;
329 s->fft_result_right[0].im = 0;
330 s->fft_result_left[0].re = 2.0f * s->fft_result_left[0].re;
331 s->fft_result_left[0].im = 0;
332 for (x = 1; x <= fft_len >> 1; x++) {
333 FFTSample tmpy = s->fft_result_left[fft_len-x].im - s->fft_result_left[x].im;
335 s->fft_result_right[x].re = s->fft_result_left[x].im + s->fft_result_left[fft_len-x].im;
336 s->fft_result_right[x].im = s->fft_result_left[x].re - s->fft_result_left[fft_len-x].re;
337 s->fft_result_right[fft_len-x].re = s->fft_result_right[x].re;
338 s->fft_result_right[fft_len-x].im = -s->fft_result_right[x].im;
340 s->fft_result_left[x].re = s->fft_result_left[x].re + s->fft_result_left[fft_len-x].re;
341 s->fft_result_left[x].im = tmpy;
342 s->fft_result_left[fft_len-x].re = s->fft_result_left[x].re;
343 s->fft_result_left[fft_len-x].im = -s->fft_result_left[x].im;
346 /* calculating cqt */
347 for (x = 0; x < VIDEO_WIDTH; x++) {
349 float g = 1.0f / s->gamma;
350 FFTComplex l = {0,0};
351 FFTComplex r = {0,0};
353 for (u = 0; u < s->coeffs_len[x]; u++) {
354 FFTSample value = s->coeffs[x][u].value;
355 int index = s->coeffs[x][u].index;
356 l.re += value * s->fft_result_left[index].re;
357 l.im += value * s->fft_result_left[index].im;
358 r.re += value * s->fft_result_right[index].re;
359 r.im += value * s->fft_result_right[index].im;
361 /* result is power, not amplitude */
362 result[x][0] = l.re * l.re + l.im * l.im;
363 result[x][2] = r.re * r.re + r.im * r.im;
364 result[x][1] = 0.5f * (result[x][0] + result[x][2]);
365 result[x][3] = result[x][1];
366 result[x][0] = 255.0f * powf(FFMIN(1.0f,result[x][0]), g);
367 result[x][1] = 255.0f * powf(FFMIN(1.0f,result[x][1]), g);
368 result[x][2] = 255.0f * powf(FFMIN(1.0f,result[x][2]), g);
372 for (x = 0; x < video_width; x++) {
373 result[x][0] = 0.5f * (result[2*x][0] + result[2*x+1][0]);
374 result[x][1] = 0.5f * (result[2*x][1] + result[2*x+1][1]);
375 result[x][2] = 0.5f * (result[2*x][2] + result[2*x+1][2]);
376 result[x][3] = 0.5f * (result[2*x][3] + result[2*x+1][3]);
380 for (x = 0; x < video_width; x++) {
381 s->spectogram[s->spectogram_index*linesize + 3*x] = result[x][0] + 0.5f;
382 s->spectogram[s->spectogram_index*linesize + 3*x + 1] = result[x][1] + 0.5f;
383 s->spectogram[s->spectogram_index*linesize + 3*x + 2] = result[x][2] + 0.5f;
387 if (!s->spectogram_count) {
388 uint8_t *data = (uint8_t*) s->outpicref->data[0];
389 float rcp_result[VIDEO_WIDTH];
390 int total_length = linesize * spectogram_height;
391 int back_length = linesize * s->spectogram_index;
393 for (x = 0; x < video_width; x++)
394 rcp_result[x] = 1.0f / (result[x][3]+0.0001f);
397 for (y = 0; y < spectogram_height; y++) {
398 float height = (spectogram_height - y) * (1.0f/spectogram_height);
399 uint8_t *lineptr = data + y * linesize;
400 for (x = 0; x < video_width; x++) {
402 if (result[x][3] <= height) {
407 mul = (result[x][3] - height) * rcp_result[x];
408 *lineptr++ = mul * result[x][0] + 0.5f;
409 *lineptr++ = mul * result[x][1] + 0.5f;
410 *lineptr++ = mul * result[x][2] + 0.5f;
416 for (y = 0; y < font_height; y++) {
417 uint8_t *lineptr = data + (spectogram_height + y) * linesize;
418 memcpy(lineptr, s->spectogram + s->spectogram_index * linesize, video_width*3);
420 for (x = 0; x < video_width; x += video_width/10) {
422 static const char str[] = "EF G A BC D ";
423 uint8_t *startptr = data + spectogram_height * linesize + x * 3;
424 for (u = 0; str[u]; u++) {
426 for (v = 0; v < 16; v++) {
427 uint8_t *p = startptr + v * linesize * video_scale + 8 * 3 * u * video_scale;
428 int ux = x + 8 * u * video_scale;
430 for (mask = 0x80; mask; mask >>= 1) {
431 if (mask & avpriv_vga16_font[str[u] * 16 + v]) {
432 p[0] = 255 - s->font_color[ux];
434 p[2] = s->font_color[ux];
435 if (video_scale == 2) {
437 p[linesize+1] = p[1];
438 p[linesize+2] = p[2];
439 p[3] = p[linesize+3] = 255 - s->font_color[ux+1];
440 p[4] = p[linesize+4] = 0;
441 p[5] = p[linesize+5] = s->font_color[ux+1];
444 p += 3 * video_scale;
452 /* drawing spectogram/sonogram */
453 data += spectogram_start * linesize;
454 memcpy(data, s->spectogram + s->spectogram_index*linesize, total_length - back_length);
456 data += total_length - back_length;
458 memcpy(data, s->spectogram, back_length);
460 s->outpicref->pts = s->frame_count;
461 ret = ff_filter_frame(outlink, av_frame_clone(s->outpicref));
462 s->req_fullfilled = 1;
465 s->spectogram_count = (s->spectogram_count + 1) % s->count;
466 s->spectogram_index = (s->spectogram_index + spectogram_height - 1) % spectogram_height;
470 static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
472 AVFilterContext *ctx = inlink->dst;
473 ShowCQTContext *s = ctx->priv;
474 int step = inlink->sample_rate / (s->fps * s->count);
475 int fft_len = 1 << s->fft_bits;
480 while (s->remaining_fill < (fft_len >> 1)) {
482 memset(&s->fft_data[fft_len - s->remaining_fill], 0, sizeof(*s->fft_data) * s->remaining_fill);
483 ret = plot_cqt(inlink);
486 for (x = 0; x < (fft_len-step); x++)
487 s->fft_data[x] = s->fft_data[x+step];
488 s->remaining_fill += step;
493 remaining = insamples->nb_samples;
494 audio_data = (float*) insamples->data[0];
497 if (remaining >= s->remaining_fill) {
498 int i = insamples->nb_samples - remaining;
499 int j = fft_len - s->remaining_fill;
501 for (m = 0; m < s->remaining_fill; m++) {
502 s->fft_data[j+m].re = audio_data[2*(i+m)];
503 s->fft_data[j+m].im = audio_data[2*(i+m)+1];
505 ret = plot_cqt(inlink);
507 av_frame_free(&insamples);
510 remaining -= s->remaining_fill;
511 for (m = 0; m < fft_len-step; m++)
512 s->fft_data[m] = s->fft_data[m+step];
513 s->remaining_fill = step;
515 int i = insamples->nb_samples - remaining;
516 int j = fft_len - s->remaining_fill;
518 for (m = 0; m < remaining; m++) {
519 s->fft_data[m+j].re = audio_data[2*(i+m)];
520 s->fft_data[m+j].im = audio_data[2*(i+m)+1];
522 s->remaining_fill -= remaining;
526 av_frame_free(&insamples);
530 static int request_frame(AVFilterLink *outlink)
532 ShowCQTContext *s = outlink->src->priv;
533 AVFilterLink *inlink = outlink->src->inputs[0];
536 s->req_fullfilled = 0;
538 ret = ff_request_frame(inlink);
539 } while (!s->req_fullfilled && ret >= 0);
541 if (ret == AVERROR_EOF && s->outpicref)
542 filter_frame(inlink, NULL);
546 static const AVFilterPad showcqt_inputs[] = {
549 .type = AVMEDIA_TYPE_AUDIO,
550 .filter_frame = filter_frame,
555 static const AVFilterPad showcqt_outputs[] = {
558 .type = AVMEDIA_TYPE_VIDEO,
559 .config_props = config_output,
560 .request_frame = request_frame,
565 AVFilter ff_avf_showcqt = {
567 .description = NULL_IF_CONFIG_SMALL("Convert input audio to a CQT (Constant Q Transform) spectrum video output."),
569 .query_formats = query_formats,
570 .priv_size = sizeof(ShowCQTContext),
571 .inputs = showcqt_inputs,
572 .outputs = showcqt_outputs,
573 .priv_class = &showcqt_class,