libavfilter/vf_lut.c
dd2793c8
 /*
  * Copyright (c) 2011 Stefano Sabatini
  *
  * 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
  */
 
 /**
  * @file
  * Compute a look-up table for binding the input value to the output
  * value, and apply it to input video.
  */
 
1d9c2dc8
 #include "libavutil/common.h"
dd2793c8
 #include "libavutil/eval.h"
 #include "libavutil/opt.h"
 #include "libavutil/pixdesc.h"
 #include "avfilter.h"
ba1cbf40
 #include "drawutils.h"
b74a1da4
 #include "formats.h"
7464a53a
 #include "internal.h"
803391f7
 #include "video.h"
dd2793c8
 
b0f29db5
 static const char *const var_names[] = {
dd2793c8
     "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_W,
     VAR_H,
     VAR_VAL,
     VAR_MAXVAL,
     VAR_MINVAL,
     VAR_NEGVAL,
     VAR_CLIPVAL,
     VAR_VARS_NB
 };
 
 typedef struct {
     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 step;
15f03725
     int negate_alpha; /* only used by negate */
dd2793c8
 } 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)
42d621d1
 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
dd2793c8
 
a77436ab
 static const AVOption options[] = {
42d621d1
     {"c0", "set component #0 expression", OFFSET(comp_expr_str[0]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
     {"c1", "set component #1 expression", OFFSET(comp_expr_str[1]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
     {"c2", "set component #2 expression", OFFSET(comp_expr_str[2]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
     {"c3", "set component #3 expression", OFFSET(comp_expr_str[3]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
     {"y",  "set Y expression", OFFSET(comp_expr_str[Y]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
     {"u",  "set U expression", OFFSET(comp_expr_str[U]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
     {"v",  "set V expression", OFFSET(comp_expr_str[V]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
     {"r",  "set R expression", OFFSET(comp_expr_str[R]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
     {"g",  "set G expression", OFFSET(comp_expr_str[G]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
     {"b",  "set B expression", OFFSET(comp_expr_str[B]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
     {"a",  "set A expression", OFFSET(comp_expr_str[A]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
dd2793c8
     {NULL},
 };
 
 static av_cold void uninit(AVFilterContext *ctx)
 {
     LutContext *lut = ctx->priv;
     int i;
 
     for (i = 0; i < 4; i++) {
         av_expr_free(lut->comp_expr[i]);
         lut->comp_expr[i] = NULL;
         av_freep(&lut->comp_expr_str[i]);
     }
 }
 
 #define YUV_FORMATS                                         \
716d413c
     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
dd2793c8
 
 #define RGB_FORMATS                             \
716d413c
     AV_PIX_FMT_ARGB,         AV_PIX_FMT_RGBA,         \
     AV_PIX_FMT_ABGR,         AV_PIX_FMT_BGRA,         \
     AV_PIX_FMT_RGB24,        AV_PIX_FMT_BGR24
dd2793c8
 
ac627b3d
 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 };
dd2793c8
 
 static int query_formats(AVFilterContext *ctx)
 {
     LutContext *lut = ctx->priv;
 
ac627b3d
     const enum AVPixelFormat *pix_fmts = lut->is_rgb ? rgb_pix_fmts :
d7e95ccd
                                        lut->is_yuv ? yuv_pix_fmts : all_pix_fmts;
dd2793c8
 
b74a1da4
     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
dd2793c8
     return 0;
 }
 
 /**
  * Clip value val in the minval - maxval range.
  */
 static double clip(void *opaque, double val)
 {
     LutContext *lut = opaque;
     double minval = lut->var_values[VAR_MINVAL];
     double maxval = lut->var_values[VAR_MAXVAL];
 
     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)
 {
     LutContext *lut = opaque;
     double val    = lut->var_values[VAR_CLIPVAL];
     double minval = lut->var_values[VAR_MINVAL];
     double maxval = lut->var_values[VAR_MAXVAL];
 
     return pow((val-minval)/(maxval-minval), gamma) * (maxval-minval)+minval;
 }
 
 static double (* const funcs1[])(void *, double) = {
     (void *)clip,
     (void *)compute_gammaval,
     NULL
 };
 
 static const char * const funcs1_names[] = {
     "clip",
     "gammaval",
     NULL
 };
 
 static int config_props(AVFilterLink *inlink)
 {
     AVFilterContext *ctx = inlink->dst;
     LutContext *lut = ctx->priv;
59ee9f78
     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
ba1cbf40
     uint8_t rgba_map[4]; /* component index -> RGBA color index map */
dd2793c8
     int min[4], max[4];
     int val, comp, ret;
 
     lut->hsub = desc->log2_chroma_w;
     lut->vsub = desc->log2_chroma_h;
 
     lut->var_values[VAR_W] = inlink->w;
     lut->var_values[VAR_H] = inlink->h;
 
     switch (inlink->format) {
716d413c
     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:
dd2793c8
         min[Y] = min[U] = min[V] = 16;
         max[Y] = 235;
         max[U] = max[V] = 240;
59bd0fef
         min[A] = 0; max[A] = 255;
dd2793c8
         break;
     default:
         min[0] = min[1] = min[2] = min[3] = 0;
         max[0] = max[1] = max[2] = max[3] = 255;
     }
 
     lut->is_yuv = lut->is_rgb = 0;
7464a53a
     if      (ff_fmt_is_in(inlink->format, yuv_pix_fmts)) lut->is_yuv = 1;
     else if (ff_fmt_is_in(inlink->format, rgb_pix_fmts)) lut->is_rgb = 1;
dd2793c8
 
     if (lut->is_rgb) {
ba1cbf40
         ff_fill_rgba_map(rgba_map, inlink->format);
dd2793c8
         lut->step = av_get_bits_per_pixel(desc) >> 3;
     }
 
     for (comp = 0; comp < desc->nb_components; comp++) {
         double res;
f3fea5ba
         int color = lut->is_rgb ? rgba_map[comp] : comp;
 
dd2793c8
         /* create the parsed expression */
f3fea5ba
         ret = av_expr_parse(&lut->comp_expr[color], lut->comp_expr_str[color],
dd2793c8
                             var_names, funcs1_names, funcs1, NULL, NULL, 0, ctx);
         if (ret < 0) {
             av_log(ctx, AV_LOG_ERROR,
f3fea5ba
                    "Error when parsing the expression '%s' for the component %d and color %d.\n",
                    lut->comp_expr_str[comp], comp, color);
dd2793c8
             return AVERROR(EINVAL);
         }
 
         /* compute the lut */
f3fea5ba
         lut->var_values[VAR_MAXVAL] = max[color];
         lut->var_values[VAR_MINVAL] = min[color];
dd2793c8
 
         for (val = 0; val < 256; val++) {
             lut->var_values[VAR_VAL] = val;
f3fea5ba
             lut->var_values[VAR_CLIPVAL] = av_clip(val, min[color], max[color]);
dd2793c8
             lut->var_values[VAR_NEGVAL] =
f3fea5ba
                 av_clip(min[color] + max[color] - lut->var_values[VAR_VAL],
                         min[color], max[color]);
dd2793c8
 
f3fea5ba
             res = av_expr_eval(lut->comp_expr[color], lut->var_values, lut);
dd2793c8
             if (isnan(res)) {
                 av_log(ctx, AV_LOG_ERROR,
f3fea5ba
                        "Error when evaluating the expression '%s' for the value %d for the component %d.\n",
                        lut->comp_expr_str[color], val, comp);
dd2793c8
                 return AVERROR(EINVAL);
             }
f3fea5ba
             lut->lut[comp][val] = av_clip((int)res, min[color], max[color]);
             av_log(ctx, AV_LOG_DEBUG, "val[%d][%d] = %d\n", comp, val, lut->lut[comp][val]);
dd2793c8
         }
     }
 
     return 0;
 }
 
bff576c7
 static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *in)
dd2793c8
 {
     AVFilterContext *ctx = inlink->dst;
     LutContext *lut = ctx->priv;
     AVFilterLink *outlink = ctx->outputs[0];
bff576c7
     AVFilterBufferRef *out;
cdeb803e
     uint8_t *inrow, *outrow, *inrow0, *outrow0;
bb39c74b
     int i, j, plane;
dd2793c8
 
bff576c7
     out = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);
     if (!out) {
         avfilter_unref_bufferp(&in);
         return AVERROR(ENOMEM);
     }
     avfilter_copy_buffer_ref_props(out, in);
 
dd2793c8
     if (lut->is_rgb) {
         /* packed */
bff576c7
         inrow0  = in ->data[0];
         outrow0 = out->data[0];
dd2793c8
 
bff576c7
         for (i = 0; i < in->video->h; i ++) {
002d9ded
             int w = inlink->w;
2a793ff2
             const uint8_t (*tab)[256] = (const uint8_t (*)[256])lut->lut;
cdeb803e
             inrow  = inrow0;
             outrow = outrow0;
002d9ded
             for (j = 0; j < w; j++) {
38477e19
                 outrow[0] = tab[0][inrow[0]];
002d9ded
                 if (lut->step>1) {
38477e19
                     outrow[1] = tab[1][inrow[1]];
002d9ded
                     if (lut->step>2) {
38477e19
                         outrow[2] = tab[2][inrow[2]];
002d9ded
                         if (lut->step>3) {
38477e19
                             outrow[3] = tab[3][inrow[3]];
002d9ded
                         }
                     }
                 }
dd2793c8
                 outrow += lut->step;
                 inrow  += lut->step;
             }
bff576c7
             inrow0  += in ->linesize[0];
             outrow0 += out->linesize[0];
dd2793c8
         }
     } else {
         /* planar */
bff576c7
         for (plane = 0; plane < 4 && in->data[plane]; plane++) {
dd2793c8
             int vsub = plane == 1 || plane == 2 ? lut->vsub : 0;
             int hsub = plane == 1 || plane == 2 ? lut->hsub : 0;
 
bff576c7
             inrow  = in ->data[plane];
             outrow = out->data[plane];
dd2793c8
 
bff576c7
             for (i = 0; i < (in->video->h + (1<<vsub) - 1)>>vsub; i ++) {
79a1d986
                 const uint8_t *tab = lut->lut[plane];
a46f8915
                 int w = (inlink->w + (1<<hsub) - 1)>>hsub;
79a1d986
                 for (j = 0; j < w; j++)
                     outrow[j] = tab[inrow[j]];
bff576c7
                 inrow  += in ->linesize[plane];
                 outrow += out->linesize[plane];
dd2793c8
             }
         }
     }
 
bff576c7
     avfilter_unref_bufferp(&in);
     return ff_filter_frame(outlink, out);
dd2793c8
 }
 
3db40703
 static const AVFilterPad inputs[] = {
     { .name            = "default",
       .type            = AVMEDIA_TYPE_VIDEO,
bff576c7
       .filter_frame    = filter_frame,
3db40703
       .config_props    = config_props,
       .min_perms       = AV_PERM_READ, },
     { .name = NULL}
 };
 static const AVFilterPad outputs[] = {
     { .name            = "default",
       .type            = AVMEDIA_TYPE_VIDEO, },
     { .name = NULL}
 };
a77436ab
 #define DEFINE_LUT_FILTER(name_, description_)                          \
dd2793c8
     AVFilter avfilter_vf_##name_ = {                                    \
633aa01f
         .name          = #name_,                                        \
         .description   = NULL_IF_CONFIG_SMALL(description_),            \
dd2793c8
         .priv_size     = sizeof(LutContext),                            \
                                                                         \
a77436ab
         .init          = name_##_init,                                  \
dd2793c8
         .uninit        = uninit,                                        \
         .query_formats = query_formats,                                 \
                                                                         \
3db40703
         .inputs        = inputs,                                        \
         .outputs       = outputs,                                       \
a77436ab
         .priv_class    = &name_##_class,                                \
dd2793c8
     }
 
8fe0c527
 #if CONFIG_LUT_FILTER
a77436ab
 
 #define lut_options options
 AVFILTER_DEFINE_CLASS(lut);
 
 static int lut_init(AVFilterContext *ctx, const char *args)
 {
     LutContext *lut = ctx->priv;
     int ret;
 
     lut->class = &lut_class;
     av_opt_set_defaults(lut);
 
     if (args && (ret = av_set_options_string(lut, args, "=", ":")) < 0)
         return ret;
 
     return 0;
 }
 
 DEFINE_LUT_FILTER(lut, "Compute and apply a lookup table to the RGB/YUV input video.");
8fe0c527
 #endif
a77436ab
 
8fe0c527
 #if CONFIG_LUTYUV_FILTER
a77436ab
 
 #define lutyuv_options options
 AVFILTER_DEFINE_CLASS(lutyuv);
 
 static int lutyuv_init(AVFilterContext *ctx, const char *args)
 {
     LutContext *lut = ctx->priv;
     int ret;
 
     lut->class = &lutyuv_class;
     lut->is_yuv = 1;
     av_opt_set_defaults(lut);
 
     if (args && (ret = av_set_options_string(lut, args, "=", ":")) < 0)
         return ret;
 
     return 0;
 }
 
 DEFINE_LUT_FILTER(lutyuv, "Compute and apply a lookup table to the YUV input video.");
8fe0c527
 #endif
a77436ab
 
8fe0c527
 #if CONFIG_LUTRGB_FILTER
a77436ab
 
 #define lutrgb_options options
 AVFILTER_DEFINE_CLASS(lutrgb);
 
 static int lutrgb_init(AVFilterContext *ctx, const char *args)
 {
     LutContext *lut = ctx->priv;
     int ret;
 
     lut->class = &lutrgb_class;
     lut->is_rgb = 1;
     av_opt_set_defaults(lut);
 
     if (args && (ret = av_set_options_string(lut, args, "=", ":")) < 0)
         return ret;
 
     return 0;
 }
 
 DEFINE_LUT_FILTER(lutrgb, "Compute and apply a lookup table to the RGB input video.");
8fe0c527
 #endif
15f03725
 
 #if CONFIG_NEGATE_FILTER
 
a77436ab
 #define negate_options options
 AVFILTER_DEFINE_CLASS(negate);
 
a5e8c41c
 static int negate_init(AVFilterContext *ctx, const char *args)
15f03725
 {
     LutContext *lut = ctx->priv;
171868e2
     char lut_params[64];
15f03725
 
     if (args)
         sscanf(args, "%d", &lut->negate_alpha);
 
171868e2
     av_log(ctx, AV_LOG_DEBUG, "negate_alpha:%d\n", lut->negate_alpha);
15f03725
 
     snprintf(lut_params, sizeof(lut_params), "c0=negval:c1=negval:c2=negval:a=%s",
              lut->negate_alpha ? "negval" : "val");
 
a77436ab
     lut->class = &negate_class;
     av_opt_set_defaults(lut);
 
     return av_set_options_string(lut, lut_params, "=", ":");
15f03725
 }
 
a77436ab
 DEFINE_LUT_FILTER(negate, "Negate input video.");
15f03725
 
d7847333
 #endif