[FFmpeg-devel] [PATCH] avfilter: add showfreqs filter

Paul B Mahol onemda at gmail.com
Tue Aug 4 22:04:45 CEST 2015


---

Is this correct?

---
 libavfilter/Makefile        |   1 +
 libavfilter/allfilters.c    |   1 +
 libavfilter/avf_showfreqs.c | 333 ++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 335 insertions(+)
 create mode 100644 libavfilter/avf_showfreqs.c

diff --git a/libavfilter/Makefile b/libavfilter/Makefile
index 1865e49..049bbe8 100644
--- a/libavfilter/Makefile
+++ b/libavfilter/Makefile
@@ -256,6 +256,7 @@ OBJS-$(CONFIG_ADRAWGRAPH_FILTER)             += f_drawgraph.o
 OBJS-$(CONFIG_AVECTORSCOPE_FILTER)           += avf_avectorscope.o
 OBJS-$(CONFIG_CONCAT_FILTER)                 += avf_concat.o
 OBJS-$(CONFIG_SHOWCQT_FILTER)                += avf_showcqt.o
+OBJS-$(CONFIG_SHOWFREQS_FILTER)              += avf_showfreqs.o
 OBJS-$(CONFIG_SHOWSPECTRUM_FILTER)           += avf_showspectrum.o
 OBJS-$(CONFIG_SHOWVOLUME_FILTER)             += avf_showvolume.o
 OBJS-$(CONFIG_SHOWWAVES_FILTER)              += avf_showwaves.o
diff --git a/libavfilter/allfilters.c b/libavfilter/allfilters.c
index f8e97bc..63a274a 100644
--- a/libavfilter/allfilters.c
+++ b/libavfilter/allfilters.c
@@ -271,6 +271,7 @@ void avfilter_register_all(void)
     REGISTER_FILTER(AVECTORSCOPE,   avectorscope,   avf);
     REGISTER_FILTER(CONCAT,         concat,         avf);
     REGISTER_FILTER(SHOWCQT,        showcqt,        avf);
+    REGISTER_FILTER(SHOWFREQS,      showfreqs,      avf);
     REGISTER_FILTER(SHOWSPECTRUM,   showspectrum,   avf);
     REGISTER_FILTER(SHOWVOLUME,     showvolume,     avf);
     REGISTER_FILTER(SHOWWAVES,      showwaves,      avf);
diff --git a/libavfilter/avf_showfreqs.c b/libavfilter/avf_showfreqs.c
new file mode 100644
index 0000000..54902b9
--- /dev/null
+++ b/libavfilter/avf_showfreqs.c
@@ -0,0 +1,333 @@
+/*
+ * Copyright (c) 2015 Paul B Mahol
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <math.h>
+
+#include "libavcodec/avfft.h"
+#include "libavutil/avassert.h"
+#include "libavutil/channel_layout.h"
+#include "libavutil/intreadwrite.h"
+#include "libavutil/opt.h"
+#include "avfilter.h"
+#include "internal.h"
+
+enum DisplayMode  { LINE, BAR, DOT, NB_MODES };
+enum DisplayScale { LINEAR, SQRT, CBRT, LOG, NB_SCALES };
+enum WindowFunc   { WFUNC_NONE, WFUNC_HANN, WFUNC_HAMMING, WFUNC_BLACKMAN, NB_WFUNC };
+
+typedef struct ShowFreqsContext {
+    const AVClass *class;
+    int w, h;
+    RDFTContext *rdft;          ///< Real Discrete Fourier Transform context
+    int rdft_bits;              ///< number of bits (RDFT window size = 1<<rdft_bits)
+    FFTSample **rdft_data;      ///< bins holder for each (displayed) channels
+    float *window_func_lut;     ///< Window function LUT
+    int win_func;
+    int nb_channels;
+    int mode;
+    int scale;
+} ShowFreqsContext;
+
+#define OFFSET(x) offsetof(ShowFreqsContext, x)
+#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
+
+static const AVOption showfreqs_options[] = {
+    { "size", "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "1024x512"}, 0, 0, FLAGS },
+    { "s",    "set video size", OFFSET(w), AV_OPT_TYPE_IMAGE_SIZE, {.str = "1024x512"}, 0, 0, FLAGS },
+    { "mode", "set display mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=LINE}, LINEAR, NB_MODES-1, FLAGS, "mode" },
+        { "line", "show lines",  0, AV_OPT_TYPE_CONST, {.i64=LINE},   0, 0, FLAGS, "mode" },
+        { "bar",  "show bars",   0, AV_OPT_TYPE_CONST, {.i64=BAR},    0, 0, FLAGS, "mode" },
+        { "dot",  "show dots",   0, AV_OPT_TYPE_CONST, {.i64=DOT},    0, 0, FLAGS, "mode" },
+    { "scale", "set display scale", OFFSET(scale), AV_OPT_TYPE_INT, {.i64=SQRT}, LINEAR, NB_SCALES-1, FLAGS, "scale" },
+        { "sqrt", "square root", 0, AV_OPT_TYPE_CONST, {.i64=SQRT},   0, 0, FLAGS, "scale" },
+        { "cbrt", "cubic root",  0, AV_OPT_TYPE_CONST, {.i64=CBRT},   0, 0, FLAGS, "scale" },
+        { "log",  "logarithmic", 0, AV_OPT_TYPE_CONST, {.i64=LOG},    0, 0, FLAGS, "scale" },
+        { "lin",  "linear",      0, AV_OPT_TYPE_CONST, {.i64=LINEAR}, 0, 0, FLAGS, "scale" },
+    { "win_func", "set window function", OFFSET(win_func), AV_OPT_TYPE_INT, {.i64 = WFUNC_HANN}, 0, NB_WFUNC-1, FLAGS, "win_func" },
+        { "hann",     "Hann window",     0, AV_OPT_TYPE_CONST, {.i64 = WFUNC_HANN},     0, 0, FLAGS, "win_func" },
+        { "hamming",  "Hamming window",  0, AV_OPT_TYPE_CONST, {.i64 = WFUNC_HAMMING},  0, 0, FLAGS, "win_func" },
+        { "blackman", "Blackman window", 0, AV_OPT_TYPE_CONST, {.i64 = WFUNC_BLACKMAN}, 0, 0, FLAGS, "win_func" },
+    { NULL }
+};
+
+AVFILTER_DEFINE_CLASS(showfreqs);
+
+static int query_formats(AVFilterContext *ctx)
+{
+    AVFilterFormats *formats = NULL;
+    AVFilterChannelLayouts *layouts = NULL;
+    AVFilterLink *inlink = ctx->inputs[0];
+    AVFilterLink *outlink = ctx->outputs[0];
+    static const enum AVSampleFormat sample_fmts[] = { AV_SAMPLE_FMT_S16P, AV_SAMPLE_FMT_NONE };
+    static const enum AVPixelFormat pix_fmts[] = { AV_PIX_FMT_RGBA, AV_PIX_FMT_NONE };
+
+    /* set input audio formats */
+    formats = ff_make_format_list(sample_fmts);
+    if (!formats)
+        return AVERROR(ENOMEM);
+    ff_formats_ref(formats, &inlink->out_formats);
+
+    layouts = ff_all_channel_layouts();
+    if (!layouts)
+        return AVERROR(ENOMEM);
+    ff_channel_layouts_ref(layouts, &inlink->out_channel_layouts);
+
+    formats = ff_all_samplerates();
+    if (!formats)
+        return AVERROR(ENOMEM);
+    ff_formats_ref(formats, &inlink->out_samplerates);
+
+    /* set output video format */
+    formats = ff_make_format_list(pix_fmts);
+    if (!formats)
+        return AVERROR(ENOMEM);
+    ff_formats_ref(formats, &outlink->in_formats);
+
+    return 0;
+}
+
+static int config_output(AVFilterLink *outlink)
+{
+    AVFilterContext *ctx = outlink->src;
+    AVFilterLink *inlink = ctx->inputs[0];
+    ShowFreqsContext *s = ctx->priv;
+    unsigned win_size;
+    int i, rdft_bits;
+
+    outlink->w = s->w;
+    outlink->h = s->h;
+
+    /* RDFT window size (precision) according to the requested output frame height */
+    for (rdft_bits = 1; 1 << rdft_bits < 2 * outlink->w; rdft_bits++);
+    win_size = 1 << rdft_bits;
+
+    /* (re-)configuration if the video output changed (or first init) */
+    if (rdft_bits != s->rdft_bits) {
+        size_t rdft_size, rdft_listsize;
+
+        av_rdft_end(s->rdft);
+        s->rdft = av_rdft_init(rdft_bits, DFT_R2C);
+        if (!s->rdft) {
+            av_log(ctx, AV_LOG_ERROR, "Unable to create RDFT context. "
+                   "The window size might be too high.\n");
+            return AVERROR(EINVAL);
+        }
+        s->rdft_bits = rdft_bits;
+
+        /* RDFT buffers: x2 for each (display) channel buffer.
+         * Note: we use free and malloc instead of a realloc-like function to
+         * make sure the buffer is aligned in memory for the FFT functions. */
+        for (i = 0; i < s->nb_channels; i++)
+            av_freep(&s->rdft_data[i]);
+        av_freep(&s->rdft_data);
+        s->nb_channels = inlink->channels;
+
+        if (av_size_mult(sizeof(*s->rdft_data),
+                         s->nb_channels, &rdft_listsize) < 0)
+            return AVERROR(EINVAL);
+        if (av_size_mult(sizeof(**s->rdft_data),
+                         win_size, &rdft_size) < 0)
+            return AVERROR(EINVAL);
+        s->rdft_data = av_malloc(rdft_listsize);
+        if (!s->rdft_data)
+            return AVERROR(ENOMEM);
+        for (i = 0; i < s->nb_channels; i++) {
+            s->rdft_data[i] = av_malloc(rdft_size);
+            if (!s->rdft_data[i])
+                return AVERROR(ENOMEM);
+        }
+
+        /* pre-calc windowing function */
+        s->window_func_lut =
+            av_realloc_f(s->window_func_lut, win_size,
+                         sizeof(*s->window_func_lut));
+        if (!s->window_func_lut)
+            return AVERROR(ENOMEM);
+        switch (s->win_func) {
+        case WFUNC_NONE:
+            for (i = 0; i < win_size; i++)
+                s->window_func_lut[i] = 1.;
+            break;
+        case WFUNC_HANN:
+            for (i = 0; i < win_size; i++)
+                s->window_func_lut[i] = .5f * (1 - cos(2*M_PI*i / (win_size-1)));
+            break;
+        case WFUNC_HAMMING:
+            for (i = 0; i < win_size; i++)
+                s->window_func_lut[i] = .54f - .46f * cos(2*M_PI*i / (win_size-1));
+            break;
+        case WFUNC_BLACKMAN: {
+            for (i = 0; i < win_size; i++)
+                s->window_func_lut[i] = .42f - .5f*cos(2*M_PI*i / (win_size-1)) + .08f*cos(4*M_PI*i / (win_size-1));
+            break;
+        }
+        default:
+            av_assert0(0);
+        }
+
+        outlink->sample_aspect_ratio = (AVRational){1,1};
+    }
+
+    outlink->frame_rate = av_make_q(inlink->sample_rate, win_size);
+
+    inlink->min_samples = inlink->max_samples = inlink->partial_buf_size =
+        win_size;
+
+    av_log(ctx, AV_LOG_VERBOSE, "s:%dx%d RDFT window size:%d\n",
+           s->w, s->h, win_size);
+    return 0;
+}
+
+static int plot_freqs(AVFilterLink *inlink, AVFrame *insamples)
+{
+    AVFilterContext *ctx = inlink->dst;
+    AVFilterLink *outlink = ctx->outputs[0];
+    ShowFreqsContext *s = ctx->priv;
+    AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
+
+    /* nb_freq contains the power of two superior or equal to the output image
+     * height (or half the RDFT window size) */
+    const int nb_freq = 1 << (s->rdft_bits - 1);
+    const int win_size = nb_freq << 1;
+    const double w = 1. / (nb_freq * 32768.);
+    int ch, n, x;
+
+    /* fill RDFT input with the number of samples available */
+    for (ch = 0; ch < s->nb_channels; ch++) {
+        const int16_t *p = (int16_t *)insamples->extended_data[ch];
+
+        for (n = 0; n < insamples->nb_samples; n++)
+            s->rdft_data[ch][n] = p[n] * s->window_func_lut[n];
+        for (; n < win_size; n++)
+            s->rdft_data[ch][n] = 0;
+    }
+
+        /* run RDFT on each samples set */
+    for (ch = 0; ch < s->nb_channels; ch++)
+        av_rdft_calc(s->rdft, s->rdft_data[ch]);
+
+#define RE(x, ch) s->rdft_data[ch][2 * (x) + 0]
+#define IM(x, ch) s->rdft_data[ch][2 * (x) + 1]
+#define MAGNITUDE(x, ch) hypot(RE(x, ch), IM(x, ch))
+
+    for (ch = 0; ch < s->nb_channels; ch++) {
+        for (x = 0; x < outlink->w; x++) {
+            double a = w * MAGNITUDE(x, ch);
+            int y, prev_y, i;
+
+            switch(s->scale) {
+            case SQRT:
+                a = 1.0 - sqrt(a);
+                break;
+            case CBRT:
+                a = 1.0 - cbrt(a);
+                break;
+            case LOG:
+                a = log(FFMAX(FFMIN(1, a), 1e-6)) / log(1e-6); // zero = -120dBFS
+                break;
+            case LINEAR:
+                a = 1.0 - a;
+                break;
+            }
+            y = a * (outlink->h - 1);
+
+            switch(s->mode) {
+            case LINE:
+                if (x == 0) {
+                    prev_y = y;
+                }
+                if (y <= prev_y) {
+                    for (i = y; i <= prev_y; i++)
+                        AV_WL32(out->data[0] + i * out->linesize[0] + x * 4, 0xffffffff);
+                } else {
+                    for (i = prev_y; i <= y; i++)
+                        AV_WL32(out->data[0] + i * out->linesize[0] + x * 4, 0xffffffff);
+                }
+                prev_y = y;
+                break;
+            case BAR:
+                for (; y < outlink->h; y++)
+                    AV_WL32(out->data[0] + y * out->linesize[0] + x * 4, 0xffffffff);
+                break;
+            case DOT:
+                AV_WL32(out->data[0] + y * out->linesize[0] + x * 4, 0xffffffff);
+                break;
+            }
+        }
+    }
+
+    out->pts = insamples->pts;
+    return ff_filter_frame(outlink, out);
+}
+
+static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)
+{
+    AVFilterContext *ctx = inlink->dst;
+    ShowFreqsContext *s = ctx->priv;
+    unsigned win_size = 1 << s->rdft_bits;
+    int ret;
+
+    av_assert0(insamples->nb_samples <= win_size);
+    ret = plot_freqs(inlink, insamples);
+
+    av_frame_free(&insamples);
+    return ret;
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+    ShowFreqsContext *s = ctx->priv;
+    int i;
+
+    av_rdft_end(s->rdft);
+    for (i = 0; i < s->nb_channels; i++)
+        av_freep(&s->rdft_data[i]);
+    av_freep(&s->rdft_data);
+    av_freep(&s->window_func_lut);
+}
+
+static const AVFilterPad showfreqs_inputs[] = {
+    {
+        .name         = "default",
+        .type         = AVMEDIA_TYPE_AUDIO,
+        .filter_frame = filter_frame,
+    },
+    { NULL }
+};
+
+static const AVFilterPad showfreqs_outputs[] = {
+    {
+        .name          = "default",
+        .type          = AVMEDIA_TYPE_VIDEO,
+        .config_props  = config_output,
+    },
+    { NULL }
+};
+
+AVFilter ff_avf_showfreqs = {
+    .name          = "showfreqs",
+    .description   = NULL_IF_CONFIG_SMALL("Convert input audio to a frequencies video output."),
+    .uninit        = uninit,
+    .query_formats = query_formats,
+    .priv_size     = sizeof(ShowFreqsContext),
+    .inputs        = showfreqs_inputs,
+    .outputs       = showfreqs_outputs,
+    .priv_class    = &showfreqs_class,
+};
-- 
2.4.5



More information about the ffmpeg-devel mailing list