vf_boxblur.c 12.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/*
 * Copyright (c) 2002 Michael Niedermayer <michaelni@gmx.at>
 * Copyright (c) 2011 Stefano Sabatini
 *
 * This file is part of Libav.
 *
 * Libav is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Libav 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with Libav; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

/**
 * @file
 * Apply a boxblur filter to the input video.
 * Ported from MPlayer libmpcodecs/vf_boxblur.c.
 */

#include "libavutil/avstring.h"
29
#include "libavutil/common.h"
30
#include "libavutil/eval.h"
31
#include "libavutil/opt.h"
32 33
#include "libavutil/pixdesc.h"
#include "avfilter.h"
34
#include "formats.h"
35
#include "internal.h"
36
#include "video.h"
37

38
static const char *const var_names[] = {
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
    "w",
    "h",
    "cw",
    "ch",
    "hsub",
    "vsub",
    NULL
};

enum var_name {
    VAR_W,
    VAR_H,
    VAR_CW,
    VAR_CH,
    VAR_HSUB,
    VAR_VSUB,
    VARS_NB
};

typedef struct {
    int radius;
    int power;
} FilterParam;

typedef struct {
64
    const AVClass *class;
65 66 67
    FilterParam luma_param;
    FilterParam chroma_param;
    FilterParam alpha_param;
68 69 70
    char *luma_radius_expr;
    char *chroma_radius_expr;
    char *alpha_radius_expr;
71 72 73 74 75 76 77 78 79 80 81 82

    int hsub, vsub;
    int radius[4];
    int power[4];
    uint8_t *temp[2]; ///< temporary buffer used in blur_power()
} BoxBlurContext;

#define Y 0
#define U 1
#define V 2
#define A 3

83
static av_cold int init(AVFilterContext *ctx, const char *args)
84 85 86
{
    BoxBlurContext *boxblur = ctx->priv;

87 88
    if (!boxblur->luma_radius_expr) {
        av_log(ctx, AV_LOG_ERROR, "Luma radius expression is not set.\n");
89 90 91
        return AVERROR(EINVAL);
    }

92 93 94 95
    if (!boxblur->chroma_radius_expr) {
        boxblur->chroma_radius_expr = av_strdup(boxblur->luma_radius_expr);
        if (!boxblur->chroma_radius_expr)
            return AVERROR(ENOMEM);
96 97
        boxblur->chroma_param.power = boxblur->luma_param.power;
    }
98 99 100 101
    if (!boxblur->alpha_radius_expr) {
        boxblur->alpha_radius_expr = av_strdup(boxblur->luma_radius_expr);
        if (!boxblur->alpha_radius_expr)
            return AVERROR(ENOMEM);
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
        boxblur->alpha_param.power = boxblur->luma_param.power;
    }

    return 0;
}

static av_cold void uninit(AVFilterContext *ctx)
{
    BoxBlurContext *boxblur = ctx->priv;

    av_freep(&boxblur->temp[0]);
    av_freep(&boxblur->temp[1]);
}

static int query_formats(AVFilterContext *ctx)
{
118 119 120 121 122 123 124
    enum AVPixelFormat pix_fmts[] = {
        AV_PIX_FMT_YUV444P,  AV_PIX_FMT_YUV422P,  AV_PIX_FMT_YUV420P,
        AV_PIX_FMT_YUV411P,  AV_PIX_FMT_YUV410P,  AV_PIX_FMT_YUVA420P,
        AV_PIX_FMT_YUV440P,  AV_PIX_FMT_GRAY8,
        AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ420P,
        AV_PIX_FMT_YUVJ440P,
        AV_PIX_FMT_NONE
125 126
    };

127
    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
128 129 130 131 132
    return 0;
}

static int config_input(AVFilterLink *inlink)
{
133
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
    AVFilterContext    *ctx = inlink->dst;
    BoxBlurContext *boxblur = ctx->priv;
    int w = inlink->w, h = inlink->h;
    int cw, ch;
    double var_values[VARS_NB], res;
    char *expr;
    int ret;

    av_freep(&boxblur->temp[0]);
    av_freep(&boxblur->temp[1]);
    if (!(boxblur->temp[0] = av_malloc(FFMAX(w, h))))
       return AVERROR(ENOMEM);
    if (!(boxblur->temp[1] = av_malloc(FFMAX(w, h)))) {
        av_freep(&boxblur->temp[0]);
        return AVERROR(ENOMEM);
    }

    boxblur->hsub = desc->log2_chroma_w;
    boxblur->vsub = desc->log2_chroma_h;

    var_values[VAR_W]       = inlink->w;
    var_values[VAR_H]       = inlink->h;
    var_values[VAR_CW] = cw = w>>boxblur->hsub;
    var_values[VAR_CH] = ch = h>>boxblur->vsub;
    var_values[VAR_HSUB]    = 1<<boxblur->hsub;
    var_values[VAR_VSUB]    = 1<<boxblur->vsub;

#define EVAL_RADIUS_EXPR(comp)                                          \
    expr = boxblur->comp##_radius_expr;                                 \
    ret = av_expr_parse_and_eval(&res, expr, var_names, var_values,     \
                                 NULL, NULL, NULL, NULL, NULL, 0, ctx); \
    boxblur->comp##_param.radius = res;                                 \
    if (ret < 0) {                                                      \
        av_log(NULL, AV_LOG_ERROR,                                      \
               "Error when evaluating " #comp " radius expression '%s'\n", expr); \
        return ret;                                                     \
    }
    EVAL_RADIUS_EXPR(luma);
    EVAL_RADIUS_EXPR(chroma);
    EVAL_RADIUS_EXPR(alpha);

    av_log(ctx, AV_LOG_DEBUG,
           "luma_radius:%d luma_power:%d "
           "chroma_radius:%d chroma_power:%d "
           "alpha_radius:%d alpha_power:%d "
           "w:%d chroma_w:%d h:%d chroma_h:%d\n",
           boxblur->luma_param  .radius, boxblur->luma_param  .power,
           boxblur->chroma_param.radius, boxblur->chroma_param.power,
           boxblur->alpha_param .radius, boxblur->alpha_param .power,
           w, cw, h, ch);

#define CHECK_RADIUS_VAL(w_, h_, comp)                                  \
    if (boxblur->comp##_param.radius < 0 ||                             \
        2*boxblur->comp##_param.radius > FFMIN(w_, h_)) {               \
        av_log(ctx, AV_LOG_ERROR,                                       \
               "Invalid " #comp " radius value %d, must be >= 0 and <= %d\n", \
               boxblur->comp##_param.radius, FFMIN(w_, h_)/2);          \
        return AVERROR(EINVAL);                                         \
    }
    CHECK_RADIUS_VAL(w,  h,  luma);
    CHECK_RADIUS_VAL(cw, ch, chroma);
    CHECK_RADIUS_VAL(w,  h,  alpha);

    boxblur->radius[Y] = boxblur->luma_param.radius;
    boxblur->radius[U] = boxblur->radius[V] = boxblur->chroma_param.radius;
    boxblur->radius[A] = boxblur->alpha_param.radius;

    boxblur->power[Y] = boxblur->luma_param.power;
    boxblur->power[U] = boxblur->power[V] = boxblur->chroma_param.power;
    boxblur->power[A] = boxblur->alpha_param.power;

    return 0;
}

static inline void blur(uint8_t *dst, int dst_step, const uint8_t *src, int src_step,
                        int len, int radius)
{
    /* Naive boxblur would sum source pixels from x-radius .. x+radius
     * for destination pixel x. That would be O(radius*width).
     * If you now look at what source pixels represent 2 consecutive
     * output pixels, then you see they are almost identical and only
     * differ by 2 pixels, like:
     * src0       111111111
     * dst0           1
     * src1        111111111
     * dst1            1
     * src0-src1  1       -1
     * so when you know one output pixel you can find the next by just adding
     * and subtracting 1 input pixel.
     * The following code adopts this faster variant.
     */
    const int length = radius*2 + 1;
    const int inv = ((1<<16) + length/2)/length;
    int x, sum = 0;

    for (x = 0; x < radius; x++)
        sum += src[x*src_step]<<1;
    sum += src[radius*src_step];

    for (x = 0; x <= radius; x++) {
        sum += src[(radius+x)*src_step] - src[(radius-x)*src_step];
        dst[x*dst_step] = (sum*inv + (1<<15))>>16;
    }

    for (; x < len-radius; x++) {
        sum += src[(radius+x)*src_step] - src[(x-radius-1)*src_step];
        dst[x*dst_step] = (sum*inv + (1<<15))>>16;
    }

    for (; x < len; x++) {
        sum += src[(2*len-radius-x-1)*src_step] - src[(x-radius-1)*src_step];
        dst[x*dst_step] = (sum*inv + (1<<15))>>16;
    }
}

static inline void blur_power(uint8_t *dst, int dst_step, const uint8_t *src, int src_step,
                              int len, int radius, int power, uint8_t *temp[2])
{
    uint8_t *a = temp[0], *b = temp[1];

    if (radius && power) {
        blur(a, 1, src, src_step, len, radius);
        for (; power > 2; power--) {
            uint8_t *c;
            blur(b, 1, a, 1, len, radius);
            c = a; a = b; b = c;
        }
        if (power > 1) {
            blur(dst, dst_step, a, 1, len, radius);
        } else {
            int i;
            for (i = 0; i < len; i++)
                dst[i*dst_step] = a[i];
        }
    } else {
        int i;
        for (i = 0; i < len; i++)
            dst[i*dst_step] = src[i*src_step];
    }
}

static void hblur(uint8_t *dst, int dst_linesize, const uint8_t *src, int src_linesize,
                  int w, int h, int radius, int power, uint8_t *temp[2])
{
    int y;

    if (radius == 0 && dst == src)
        return;

    for (y = 0; y < h; y++)
        blur_power(dst + y*dst_linesize, 1, src + y*src_linesize, 1,
                   w, radius, power, temp);
}

static void vblur(uint8_t *dst, int dst_linesize, const uint8_t *src, int src_linesize,
                  int w, int h, int radius, int power, uint8_t *temp[2])
{
    int x;

    if (radius == 0 && dst == src)
        return;

    for (x = 0; x < w; x++)
        blur_power(dst + x, dst_linesize, src + x, src_linesize,
                   h, radius, power, temp);
}

A
Anton Khirnov 已提交
301
static int filter_frame(AVFilterLink *inlink, AVFrame *in)
302 303 304 305
{
    AVFilterContext *ctx = inlink->dst;
    BoxBlurContext *boxblur = ctx->priv;
    AVFilterLink *outlink = inlink->dst->outputs[0];
A
Anton Khirnov 已提交
306
    AVFrame *out;
307
    int plane;
A
Anton Khirnov 已提交
308
    int cw = inlink->w >> boxblur->hsub, ch = in->height >> boxblur->vsub;
309
    int w[4] = { inlink->w, cw, cw, inlink->w };
A
Anton Khirnov 已提交
310
    int h[4] = { in->height, ch, ch, in->height };
311

A
Anton Khirnov 已提交
312
    out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
313
    if (!out) {
A
Anton Khirnov 已提交
314
        av_frame_free(&in);
315 316
        return AVERROR(ENOMEM);
    }
A
Anton Khirnov 已提交
317
    av_frame_copy_props(out, in);
318 319 320 321

    for (plane = 0; in->data[plane] && plane < 4; plane++)
        hblur(out->data[plane], out->linesize[plane],
              in ->data[plane], in ->linesize[plane],
322 323 324
              w[plane], h[plane], boxblur->radius[plane], boxblur->power[plane],
              boxblur->temp);

325 326 327
    for (plane = 0; in->data[plane] && plane < 4; plane++)
        vblur(out->data[plane], out->linesize[plane],
              out->data[plane], out->linesize[plane],
328 329 330
              w[plane], h[plane], boxblur->radius[plane], boxblur->power[plane],
              boxblur->temp);

A
Anton Khirnov 已提交
331
    av_frame_free(&in);
332 333

    return ff_filter_frame(outlink, out);
334 335
}

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
#define OFFSET(x) offsetof(BoxBlurContext, x)
#define FLAGS AV_OPT_FLAG_VIDEO_PARAM
static const AVOption options[] = {
    { "luma_radius", "Radius of the luma blurring box",     OFFSET(luma_radius_expr),   AV_OPT_TYPE_STRING,               .flags = FLAGS },
    { "luma_power",  "How many times should the boxblur be applied to luma",
                                                            OFFSET(luma_param.power),   AV_OPT_TYPE_INT, { .i64 = 1 }, 0, INT_MAX, FLAGS },
    { "chroma_radius", "Radius of the chroma blurring box", OFFSET(chroma_radius_expr), AV_OPT_TYPE_STRING,               .flags = FLAGS },
    { "chroma_power",  "How many times should the boxblur be applied to chroma",
                                                            OFFSET(chroma_param.power), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, INT_MAX, FLAGS },
    { "alpha_radius", "Radius of the alpha blurring box",   OFFSET(alpha_radius_expr),  AV_OPT_TYPE_STRING,               .flags = FLAGS },
    { "alpha_power",  "How many times should the boxblur be applied to alpha",
                                                            OFFSET(alpha_param.power),  AV_OPT_TYPE_INT, { .i64 = 1 }, 0, INT_MAX, FLAGS },
    { NULL },
};

static const AVClass boxblur_class = {
    .class_name = "boxblur",
    .item_name  = av_default_item_name,
    .option     = options,
    .version    = LIBAVUTIL_VERSION_INT,
};

358 359 360 361 362
static const AVFilterPad avfilter_vf_boxblur_inputs[] = {
    {
        .name         = "default",
        .type         = AVMEDIA_TYPE_VIDEO,
        .config_props = config_input,
363
        .filter_frame = filter_frame,
364 365 366 367 368 369 370 371 372 373 374 375
    },
    { NULL }
};

static const AVFilterPad avfilter_vf_boxblur_outputs[] = {
    {
        .name = "default",
        .type = AVMEDIA_TYPE_VIDEO,
    },
    { NULL }
};

376 377 378 379
AVFilter avfilter_vf_boxblur = {
    .name          = "boxblur",
    .description   = NULL_IF_CONFIG_SMALL("Blur the input."),
    .priv_size     = sizeof(BoxBlurContext),
380
    .priv_class    = &boxblur_class,
381 382 383 384
    .init          = init,
    .uninit        = uninit,
    .query_formats = query_formats,

385 386
    .inputs    = avfilter_vf_boxblur_inputs,
    .outputs   = avfilter_vf_boxblur_outputs,
387
};