vf_lut.c 14 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
/*
 * 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 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.
 *
 * 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser 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
 * Compute a look-up table for binding the input value to the output
 * value, and apply it to input video.
 */

27
#include "libavutil/attributes.h"
28
#include "libavutil/common.h"
29 30 31 32 33
#include "libavutil/eval.h"
#include "libavutil/mathematics.h"
#include "libavutil/opt.h"
#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 64 65
    "E",
    "PHI",
    "PI",
    "w",        ///< width of the input video
    "h",        ///< height of the input video
    "val",      ///< input value for the pixel
    "maxval",   ///< max value for the pixel
    "minval",   ///< min value for the pixel
    "negval",   ///< negated value
    "clipval",
    NULL
};

enum var_name {
    VAR_E,
    VAR_PHI,
    VAR_PI,
    VAR_W,
    VAR_H,
    VAR_VAL,
    VAR_MAXVAL,
    VAR_MINVAL,
    VAR_NEGVAL,
    VAR_CLIPVAL,
    VAR_VARS_NB
};

66
typedef struct LutContext {
67 68 69 70 71 72 73 74 75
    const AVClass *class;
    uint8_t lut[4][256];  ///< lookup table for each component
    char   *comp_expr_str[4];
    AVExpr *comp_expr[4];
    int hsub, vsub;
    double var_values[VAR_VARS_NB];
    int is_rgb, is_yuv;
    int rgba_map[4];
    int step;
76
    int negate_alpha; /* only used by negate */
77 78 79 80 81 82 83 84 85 86 87
} LutContext;

#define Y 0
#define U 1
#define V 2
#define R 0
#define G 1
#define B 2
#define A 3

#define OFFSET(x) offsetof(LutContext, x)
88
#define FLAGS AV_OPT_FLAG_VIDEO_PARAM
89 90

static const AVOption lut_options[] = {
91 92 93 94 95 96 97 98 99 100 101 102
    { "c0", "set component #0 expression", OFFSET(comp_expr_str[0]),  AV_OPT_TYPE_STRING, { .str = "val" }, .flags = FLAGS },
    { "c1", "set component #1 expression", OFFSET(comp_expr_str[1]),  AV_OPT_TYPE_STRING, { .str = "val" }, .flags = FLAGS },
    { "c2", "set component #2 expression", OFFSET(comp_expr_str[2]),  AV_OPT_TYPE_STRING, { .str = "val" }, .flags = FLAGS },
    { "c3", "set component #3 expression", OFFSET(comp_expr_str[3]),  AV_OPT_TYPE_STRING, { .str = "val" }, .flags = FLAGS },
    { "y",  "set Y expression",            OFFSET(comp_expr_str[Y]),  AV_OPT_TYPE_STRING, { .str = "val" }, .flags = FLAGS },
    { "u",  "set U expression",            OFFSET(comp_expr_str[U]),  AV_OPT_TYPE_STRING, { .str = "val" }, .flags = FLAGS },
    { "v",  "set V expression",            OFFSET(comp_expr_str[V]),  AV_OPT_TYPE_STRING, { .str = "val" }, .flags = FLAGS },
    { "r",  "set R expression",            OFFSET(comp_expr_str[R]),  AV_OPT_TYPE_STRING, { .str = "val" }, .flags = FLAGS },
    { "g",  "set G expression",            OFFSET(comp_expr_str[G]),  AV_OPT_TYPE_STRING, { .str = "val" }, .flags = FLAGS },
    { "b",  "set B expression",            OFFSET(comp_expr_str[B]),  AV_OPT_TYPE_STRING, { .str = "val" }, .flags = FLAGS },
    { "a",  "set A expression",            OFFSET(comp_expr_str[A]),  AV_OPT_TYPE_STRING, { .str = "val" }, .flags = FLAGS },
    { NULL },
103 104
};

105
static av_cold int init(AVFilterContext *ctx)
106
{
107
    LutContext *s = ctx->priv;
108

109 110 111
    s->var_values[VAR_PHI] = M_PHI;
    s->var_values[VAR_PI]  = M_PI;
    s->var_values[VAR_E ]  = M_E;
112

113 114
    s->is_rgb = !strcmp(ctx->filter->name, "lutrgb");
    s->is_yuv = !strcmp(ctx->filter->name, "lutyuv");
115 116 117 118 119 120

    return 0;
}

static av_cold void uninit(AVFilterContext *ctx)
{
121
    LutContext *s = ctx->priv;
122 123 124
    int i;

    for (i = 0; i < 4; i++) {
125 126 127
        av_expr_free(s->comp_expr[i]);
        s->comp_expr[i] = NULL;
        av_freep(&s->comp_expr_str[i]);
128 129 130 131
    }
}

#define YUV_FORMATS                                         \
132 133 134 135 136
    AV_PIX_FMT_YUV444P,  AV_PIX_FMT_YUV422P,  AV_PIX_FMT_YUV420P,    \
    AV_PIX_FMT_YUV411P,  AV_PIX_FMT_YUV410P,  AV_PIX_FMT_YUV440P,    \
    AV_PIX_FMT_YUVA420P,                                       \
    AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ420P,   \
    AV_PIX_FMT_YUVJ440P
137 138

#define RGB_FORMATS                             \
139 140 141
    AV_PIX_FMT_ARGB,         AV_PIX_FMT_RGBA,         \
    AV_PIX_FMT_ABGR,         AV_PIX_FMT_BGRA,         \
    AV_PIX_FMT_RGB24,        AV_PIX_FMT_BGR24
142

143 144 145
static const enum AVPixelFormat yuv_pix_fmts[] = { YUV_FORMATS, AV_PIX_FMT_NONE };
static const enum AVPixelFormat rgb_pix_fmts[] = { RGB_FORMATS, AV_PIX_FMT_NONE };
static const enum AVPixelFormat all_pix_fmts[] = { RGB_FORMATS, YUV_FORMATS, AV_PIX_FMT_NONE };
146 147 148

static int query_formats(AVFilterContext *ctx)
{
149
    LutContext *s = ctx->priv;
150

151 152 153
    const enum AVPixelFormat *pix_fmts = s->is_rgb ? rgb_pix_fmts :
                                                     s->is_yuv ? yuv_pix_fmts :
                                                                 all_pix_fmts;
154

155
    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
156 157 158 159 160 161 162 163
    return 0;
}

/**
 * Clip value val in the minval - maxval range.
 */
static double clip(void *opaque, double val)
{
164 165 166
    LutContext *s = opaque;
    double minval = s->var_values[VAR_MINVAL];
    double maxval = s->var_values[VAR_MAXVAL];
167 168 169 170 171 172 173 174 175 176

    return av_clip(val, minval, maxval);
}

/**
 * Compute gamma correction for value val, assuming the minval-maxval
 * range, val is clipped to a value contained in the same interval.
 */
static double compute_gammaval(void *opaque, double gamma)
{
177 178 179 180
    LutContext *s = opaque;
    double val    = s->var_values[VAR_CLIPVAL];
    double minval = s->var_values[VAR_MINVAL];
    double maxval = s->var_values[VAR_MAXVAL];
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199

    return pow((val-minval)/(maxval-minval), gamma) * (maxval-minval)+minval;
}

static double (* const funcs1[])(void *, double) = {
    clip,
    compute_gammaval,
    NULL
};

static const char * const funcs1_names[] = {
    "clip",
    "gammaval",
    NULL
};

static int config_props(AVFilterLink *inlink)
{
    AVFilterContext *ctx = inlink->dst;
200
    LutContext *s = ctx->priv;
201
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
202 203 204
    int min[4], max[4];
    int val, comp, ret;

205 206
    s->hsub = desc->log2_chroma_w;
    s->vsub = desc->log2_chroma_h;
207

208 209
    s->var_values[VAR_W] = inlink->w;
    s->var_values[VAR_H] = inlink->h;
210 211

    switch (inlink->format) {
212 213 214 215 216 217 218
    case AV_PIX_FMT_YUV410P:
    case AV_PIX_FMT_YUV411P:
    case AV_PIX_FMT_YUV420P:
    case AV_PIX_FMT_YUV422P:
    case AV_PIX_FMT_YUV440P:
    case AV_PIX_FMT_YUV444P:
    case AV_PIX_FMT_YUVA420P:
219 220 221 222 223 224 225 226 227 228
        min[Y] = min[U] = min[V] = 16;
        max[Y] = 235;
        max[U] = max[V] = 240;
        min[A] = 0; max[A] = 255;
        break;
    default:
        min[0] = min[1] = min[2] = min[3] = 0;
        max[0] = max[1] = max[2] = max[3] = 255;
    }

229 230 231
    s->is_yuv = s->is_rgb = 0;
    if      (ff_fmt_is_in(inlink->format, yuv_pix_fmts)) s->is_yuv = 1;
    else if (ff_fmt_is_in(inlink->format, rgb_pix_fmts)) s->is_rgb = 1;
232

233
    if (s->is_rgb) {
234
        switch (inlink->format) {
235 236
        case AV_PIX_FMT_ARGB:  s->rgba_map[A] = 0; s->rgba_map[R] = 1; s->rgba_map[G] = 2; s->rgba_map[B] = 3; break;
        case AV_PIX_FMT_ABGR:  s->rgba_map[A] = 0; s->rgba_map[B] = 1; s->rgba_map[G] = 2; s->rgba_map[R] = 3; break;
237
        case AV_PIX_FMT_RGBA:
238
        case AV_PIX_FMT_RGB24: s->rgba_map[R] = 0; s->rgba_map[G] = 1; s->rgba_map[B] = 2; s->rgba_map[A] = 3; break;
239
        case AV_PIX_FMT_BGRA:
240
        case AV_PIX_FMT_BGR24: s->rgba_map[B] = 0; s->rgba_map[G] = 1; s->rgba_map[R] = 2; s->rgba_map[A] = 3; break;
241
        }
242
        s->step = av_get_bits_per_pixel(desc) >> 3;
243 244 245 246 247 248
    }

    for (comp = 0; comp < desc->nb_components; comp++) {
        double res;

        /* create the parsed expression */
249 250
        av_expr_free(s->comp_expr[comp]);
        s->comp_expr[comp] = NULL;
251
        ret = av_expr_parse(&s->comp_expr[comp], s->comp_expr_str[comp],
252 253 254 255
                            var_names, funcs1_names, funcs1, NULL, NULL, 0, ctx);
        if (ret < 0) {
            av_log(ctx, AV_LOG_ERROR,
                   "Error when parsing the expression '%s' for the component %d.\n",
256
                   s->comp_expr_str[comp], comp);
257 258 259
            return AVERROR(EINVAL);
        }

260 261 262
        /* compute the s */
        s->var_values[VAR_MAXVAL] = max[comp];
        s->var_values[VAR_MINVAL] = min[comp];
263 264

        for (val = 0; val < 256; val++) {
265 266 267 268
            s->var_values[VAR_VAL] = val;
            s->var_values[VAR_CLIPVAL] = av_clip(val, min[comp], max[comp]);
            s->var_values[VAR_NEGVAL] =
                av_clip(min[comp] + max[comp] - s->var_values[VAR_VAL],
269 270
                        min[comp], max[comp]);

271
            res = av_expr_eval(s->comp_expr[comp], s->var_values, s);
272 273 274
            if (isnan(res)) {
                av_log(ctx, AV_LOG_ERROR,
                       "Error when evaluating the expression '%s' for the value %d for the component #%d.\n",
275
                       s->comp_expr_str[comp], val, comp);
276 277
                return AVERROR(EINVAL);
            }
278 279
            s->lut[comp][val] = av_clip((int)res, min[comp], max[comp]);
            av_log(ctx, AV_LOG_DEBUG, "val[%d][%d] = %d\n", comp, val, s->lut[comp][val]);
280 281 282 283 284 285
        }
    }

    return 0;
}

286
static int filter_frame(AVFilterLink *inlink, AVFrame *in)
287 288
{
    AVFilterContext *ctx = inlink->dst;
289
    LutContext *s = ctx->priv;
290
    AVFilterLink *outlink = ctx->outputs[0];
291
    AVFrame *out;
292 293 294
    uint8_t *inrow, *outrow, *inrow0, *outrow0;
    int i, j, k, plane;

295
    out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
296
    if (!out) {
297
        av_frame_free(&in);
298 299
        return AVERROR(ENOMEM);
    }
300
    av_frame_copy_props(out, in);
301

302
    if (s->is_rgb) {
303
        /* packed */
304 305
        inrow0  = in ->data[0];
        outrow0 = out->data[0];
306

307
        for (i = 0; i < in->height; i ++) {
308 309 310
            inrow  = inrow0;
            outrow = outrow0;
            for (j = 0; j < inlink->w; j++) {
311 312 313 314
                for (k = 0; k < s->step; k++)
                    outrow[k] = s->lut[s->rgba_map[k]][inrow[k]];
                outrow += s->step;
                inrow  += s->step;
315
            }
316 317
            inrow0  += in ->linesize[0];
            outrow0 += out->linesize[0];
318 319 320
        }
    } else {
        /* planar */
321
        for (plane = 0; plane < 4 && in->data[plane]; plane++) {
322 323
            int vsub = plane == 1 || plane == 2 ? s->vsub : 0;
            int hsub = plane == 1 || plane == 2 ? s->hsub : 0;
324

325 326
            inrow  = in ->data[plane];
            outrow = out->data[plane];
327

328
            for (i = 0; i < in->height >> vsub; i ++) {
329
                for (j = 0; j < inlink->w>>hsub; j++)
330
                    outrow[j] = s->lut[plane][inrow[j]];
331 332
                inrow  += in ->linesize[plane];
                outrow += out->linesize[plane];
333 334 335 336
            }
        }
    }

337
    av_frame_free(&in);
338
    return ff_filter_frame(outlink, out);
339 340
}

341 342 343
static const AVFilterPad inputs[] = {
    { .name            = "default",
      .type            = AVMEDIA_TYPE_VIDEO,
344
      .filter_frame    = filter_frame,
345
      .config_props    = config_props,
346
    },
347 348 349 350 351 352 353
    { .name = NULL}
};
static const AVFilterPad outputs[] = {
    { .name            = "default",
      .type            = AVMEDIA_TYPE_VIDEO, },
    { .name = NULL}
};
354 355 356 357 358 359 360
#define DEFINE_LUT_FILTER(name_, description_, init_, options)          \
    static const AVClass name_ ## _class = {                            \
        .class_name = #name_,                                           \
        .item_name  = av_default_item_name,                             \
        .option     = options,                                          \
        .version    = LIBAVUTIL_VERSION_INT,                            \
    };                                                                  \
361
    AVFilter ff_vf_##name_ = {                                          \
362 363 364
        .name          = #name_,                                        \
        .description   = NULL_IF_CONFIG_SMALL(description_),            \
        .priv_size     = sizeof(LutContext),                            \
365
        .priv_class    = &name_ ## _class,                              \
366 367 368 369 370
                                                                        \
        .init          = init_,                                         \
        .uninit        = uninit,                                        \
        .query_formats = query_formats,                                 \
                                                                        \
371 372
        .inputs        = inputs,                                        \
        .outputs       = outputs,                                       \
373 374 375
    }

#if CONFIG_LUT_FILTER
376
DEFINE_LUT_FILTER(lut,    "Compute and apply a lookup table to the RGB/YUV input video.", init, lut_options);
377 378
#endif
#if CONFIG_LUTYUV_FILTER
379
DEFINE_LUT_FILTER(lutyuv, "Compute and apply a lookup table to the YUV input video.",     init, lut_options);
380 381
#endif
#if CONFIG_LUTRGB_FILTER
382
DEFINE_LUT_FILTER(lutrgb, "Compute and apply a lookup table to the RGB input video.",     init, lut_options);
383
#endif
384 385 386

#if CONFIG_NEGATE_FILTER

387 388 389 390 391
static const AVOption negate_options[] = {
    { "negate_alpha", NULL, OFFSET(negate_alpha), AV_OPT_TYPE_INT, { .i64 = 0 }, .flags = FLAGS },
    { NULL },
};

392
static av_cold int negate_init(AVFilterContext *ctx)
393
{
394
    LutContext *s = ctx->priv;
395
    int i;
396

397
    av_log(ctx, AV_LOG_DEBUG, "negate_alpha:%d\n", s->negate_alpha);
398

399
    for (i = 0; i < 4; i++) {
400
        s->comp_expr_str[i] = av_strdup((i == 3 && s->negate_alpha) ?
401
                                          "val" : "negval");
402
        if (!s->comp_expr_str[i]) {
403 404 405 406
            uninit(ctx);
            return AVERROR(ENOMEM);
        }
    }
407

408
    return init(ctx);
409 410
}

411
DEFINE_LUT_FILTER(negate, "Negate input video.", negate_init, negate_options);
412 413

#endif