[FFmpeg-devel] [PATCH] lavfi/WIP: add showspectrum filter.

Clément Bœsch ubitux at gmail.com
Fri Aug 10 00:31:35 CEST 2012


On Mon, Jul 30, 2012 at 11:02:26AM +0200, Stefano Sabatini wrote:
[...]
> > +/**
> > + * @file
> > + * audio to spectrum (video) transmedia filter, based on ffplay showmode and
> > + * lavfi/avf_showaudio
> 
> showwaves
> 

Fixed.

> > + */
> > +
> > +#include <math.h>
> > +
> > +#include "libavcodec/avfft.h"
> > +#include "libavutil/audioconvert.h"
> > +#include "libavutil/opt.h"
> > +#include "libavutil/parseutils.h"
> > +#include "avfilter.h"
> > +#include "formats.h"
> > +
> > +
> > +typedef struct {
> > +    const AVClass *class;
> > +    int w, h;
> > +    char *size_str;
> > +    int xpos;
> > +    AVFilterBufferRef *outpicref;
> > +
> > +    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
> > +    int filled;                 ///< number of samples (per channel) filled
> > +    float *windowing;           ///< Window function LUT
> > +} ShowSpectrumContext;
> > +
> > +#define OFFSET(x) offsetof(ShowSpectrumContext, x)
> > +
> 
> > +static const AVOption showspectrum_options[] = {
> > +    { "size", "set video size",   OFFSET(size_str), AV_OPT_TYPE_STRING, {.str = "320x240"}, 0, 0 },
> > +    { "s",    "set video size",   OFFSET(size_str), AV_OPT_TYPE_STRING, {.str = "320x240"}, 0, 0 },
> 
> AV_OPT_IMAGE_SIZE
> 

Fixed.

> 
> > +    { NULL },
> > +};
> > +
> > +static const char *showspectrum_get_name(void *ctx)
> > +{
> > +    return "showspectrum";
> > +}
> > +
> > +static const AVClass showspectrum_class = {
> > +    "ShowSpectrumContext",
> > +    showspectrum_get_name,
> > +    showspectrum_options
> > +};
> 
> AVFILTER_DEFINE_CLASS
> 

Ditto.

> > +
> > +static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
> > +{
> > +    ShowSpectrumContext *showspectrum = ctx->priv;
> > +    int err;
> > +
> > +    showspectrum->class = &showspectrum_class;
> > +    av_opt_set_defaults(showspectrum);
> > +
> > +    if ((err = (av_set_options_string(showspectrum, args, "=", ":"))) < 0) {
> > +        av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
> > +        return err;
> > +    }
> > +
> > +    if (av_parse_video_size(&showspectrum->w, &showspectrum->h, showspectrum->size_str) < 0) {
> > +        av_log(ctx, AV_LOG_ERROR, "Invalid frame size: %s\n", showspectrum->size_str);
> > +        return AVERROR(EINVAL);
> > +    }
> > +
> > +    return 0;
> > +}
> > +
> > +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, -1 };
> > +    static const enum PixelFormat pix_fmts[] = { PIX_FMT_GRAY8, -1 }; // TODO: color
> > +
> 
> > +    /* set input audio formats */
> > +    formats = avfilter_make_format_list(sample_fmts);
> > +    if (!formats)
> > +        return AVERROR(ENOMEM);
> > +    avfilter_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);
> > +    avfilter_formats_ref(formats, &inlink->out_samplerates);
> 
> Note: we may find some clever way to wrap this in a shared function.
> 

Yup, it's kept in sync with showwaves.

> > +
> > +    /* set output video format */
> > +    formats = avfilter_make_format_list(pix_fmts);
> > +    if (!formats)
> > +        return AVERROR(ENOMEM);
> > +    avfilter_formats_ref(formats, &outlink->in_formats);
> > +
> > +    return 0;
> > +}
> > +
> > +static int config_output(AVFilterLink *outlink)
> > +{
> > +    AVFilterContext *ctx = outlink->src;
> > +    ShowSpectrumContext *showspectrum = ctx->priv;
> > +    int i, rdft_bits, win_size;
> > +
> > +    outlink->w = showspectrum->w;
> > +    outlink->h = showspectrum->h;
> > +
> > +    /* RDFT window size (precision) according to the requested output frame height */
> > +    for (rdft_bits = 1; 1<<rdft_bits < 2*outlink->h; rdft_bits++);
> > +    win_size = 1 << rdft_bits;
> 
> > +    av_log(ctx, AV_LOG_INFO, "s:%dx%d RDFT N:%d\n", showspectrum->w, showspectrum->h, win_size);
> 
> INFO -> VERBOSE

OK

> also N -> win_size
> 

I liked the N because that's generally the mathematical reference, "N ->
N/2+1", but whatever.

> > +
> > +    /* (re-)configuration if the video output changed (or first init) */
> > +    if (rdft_bits != showspectrum->rdft_bits) {
> > +        AVFilterBufferRef *outpicref;
> > +
> > +        av_rdft_end(showspectrum->rdft);
> > +        showspectrum->rdft = av_rdft_init(rdft_bits, DFT_R2C);
> > +        showspectrum->rdft_bits = rdft_bits;
> > +
> > +        /* RDFT buffers: x2 for each (display) channel buffer */
> > +        av_free(showspectrum->rdft_data);
> > +        showspectrum->rdft_data = av_malloc(2 * win_size * sizeof(*showspectrum->rdft_data));
> > +        if (!showspectrum->rdft_data)
> > +            return AVERROR(ENOMEM);
> > +        showspectrum->filled = 0;
> > +
> > +        /* pre-calc windowing function (hann here) */
> > +        av_free(showspectrum->windowing);
> > +        showspectrum->windowing = av_malloc(win_size * sizeof(*showspectrum->windowing));
> > +        if (!showspectrum->windowing)
> > +            return AVERROR(ENOMEM);
> > +        for (i = 0; i < win_size; i++)
> > +            showspectrum->windowing[i] = .5f * (1 - cos(2*M_PI*i / (win_size-1)));
> > +
> > +        /* prepare the initial picref buffer (black frame) */
> > +        avfilter_unref_bufferp(&showspectrum->outpicref);
> 
> > +        showspectrum->outpicref = outpicref =
> > +            avfilter_get_video_buffer(outlink, AV_PERM_WRITE|AV_PERM_ALIGN,
> 
> AV_PERM_WRITE|AV_PERM_ALIGN|AV_PERM_PRESERVE
> 
> (see below)
> 
> Is ALIGN really required?
> 

I don't think so, removed (showwaves has it).

> > +                                      outlink->w, outlink->h);
> 
> 
> 
> > +        outpicref->video->w = outlink->w;
> > +        outpicref->video->h = outlink->h;
> > +        memset(outpicref->data[0], 0, outlink->h * outpicref->linesize[0]);
> 
> please check that the buffer is not already zeroed, drop the memset in
> that case, REUSE* flags are useful for the frame allocator, so you
> should use REUSE2 in this case.

OK, changed.

> 
> > +        showspectrum->xpos = 0;
> > +    }
> > +
> > +    return 0;
> > +}
> > +
> > +static int plot_spectrum_column(AVFilterLink *inlink, AVFilterBufferRef *insamples, int nb_samples)
> > +{
> > +    AVFilterContext *ctx = inlink->dst;
> > +    AVFilterLink *outlink = ctx->outputs[0];
> > +    ShowSpectrumContext *showspectrum = ctx->priv;
> > +    AVFilterBufferRef *outpicref = showspectrum->outpicref;
> > +    const int nb_channels = av_get_channel_layout_nb_channels(insamples->audio->channel_layout);
> > +
> > +    /* 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 << (showspectrum->rdft_bits - 1);
> > +    const int win_size = nb_freq << 1;
> > +
> > +    int ch, n, y;
> > +    FFTSample *data[2];
> > +    const int nb_display_channels = FFMIN(nb_channels, 2);
> > +    const int start = showspectrum->filled;
> > +    const int add_samples = FFMIN(win_size - start, nb_samples);
> > +
> > +    //av_log(0,0,"rdft_data: %d/%d <=== input: %d (-> insert %d samples)\n",
> > +    //       win_size, start, nb_samples, add_samples);
> > +
> > +    /* fill RDFT input with the number of samples available */
> > +    for (ch = 0; ch < nb_display_channels; ch++) {
> > +        const int16_t *p = (int16_t *)insamples->extended_data[ch];
> > +
> > +        data[ch] = showspectrum->rdft_data + win_size * ch; // select channel buffer
> > +        for (n = 0; n < add_samples; n++)
> > +            data[ch][start + n] = p[n] * showspectrum->windowing[start + n];
> > +    }
> > +    showspectrum->filled += add_samples;
> > +
> > +    /* complete RDFT window size? */
> > +    if (showspectrum->filled == win_size) {
> > +
> > +        /* run RDFT on each samples set */
> > +        for (ch = 0; ch < nb_display_channels; ch++)
> > +            av_rdft_calc(showspectrum->rdft, data[ch]);
> > +
> > +        /* fill a new spectrum column */
> > +#define RE(ch) data[ch][2*y + 0]
> > +#define IM(ch) data[ch][2*y + 1]
> > +#define MAGNITUDE(re, im) sqrt((re)*(re) + (im)*(im))
> > +        for (y = 0; y < outlink->h; y++) {
> > +            static float max;
> > +            // FIXME: bin[0] contains first and last bins
> > +            const int pos = showspectrum->xpos + (outlink->h - y - 1) * outpicref->linesize[0];
> > +            const double w = 1. / sqrt(nb_freq);
> > +            int a =                           sqrt(w * MAGNITUDE(RE(0), IM(0)));
> > +            int b = nb_display_channels > 1 ? sqrt(w * MAGNITUDE(RE(1), IM(1))) : a;
> > +
> > +            a = FFMIN(a, 255);
> > +            b = FFMIN(b, 255);
> > +            outpicref->data[0][pos] = (a + b) / 2;
> > +        }
> > +        showspectrum->xpos++;
> > +        if (showspectrum->xpos == outlink->w)
> > +            showspectrum->xpos = 0;
> > +
> > +        /* send the frame (RO because it is re-used in this filter each time)
> > +         * to the next filter */
> > +        outpicref->pts = insamples->pts +
> > +            showspectrum->filled * inlink->time_base.num / (inlink->time_base.den * inlink->sample_rate);
> > +        avfilter_start_frame(outlink, avfilter_ref_buffer(outpicref, ~0));
> 
> You have a buffer WRITE+ALIGN+REUSE2+READ (READ flag is automatically
> added by the filtering system). You need to add the PRESERVE flag and
> remove the WRITE flag, so the better way is to do
> avfilter_ref_buffer(outpicref, ~AV_PERM_READ), and request the frame
> with the flag PRESERVE in config.
> 

Changed.

> > +        avfilter_draw_slice(outlink, 0, outlink->h, 1);
> > +        avfilter_end_frame(outlink);
> > +        //FIXME: seems to leak heavily (+slow?)
> > +
> > +        showspectrum->filled = 0;
> > +    }
> > +
> > +    return nb_samples - add_samples;
> > +}
> > +
> > +static void filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamples)
> > +{
> > +    int left_samples = insamples->audio->nb_samples;
> > +
> > +    while (left_samples) {
> > +        //av_log(0,0,"left_samples=%d\n", left_samples);
> > +        left_samples = plot_spectrum_column(inlink, insamples, left_samples);
> 
> Would make more sense to return the number of consumed samples and do:
> left_samples -= plot_spectrum_column...
> 

Sure.

> [...]
> 
> Missing docs.

Oups, forgot to do that in the new patch...

-- 
Clément B.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 490 bytes
Desc: not available
URL: <http://ffmpeg.org/pipermail/ffmpeg-devel/attachments/20120810/74db94ad/attachment.asc>


More information about the ffmpeg-devel mailing list