]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_lut.c
lavfi: make formats API private on next bump.
[ffmpeg] / libavfilter / vf_lut.c
1 /*
2  * Copyright (c) 2011 Stefano Sabatini
3  *
4  * This file is part of Libav.
5  *
6  * Libav is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * Libav is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with Libav; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * Compute a look-up table for binding the input value to the output
24  * value, and apply it to input video.
25  */
26
27 #include "libavutil/eval.h"
28 #include "libavutil/mathematics.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/pixdesc.h"
31 #include "avfilter.h"
32 #include "formats.h"
33 #include "internal.h"
34
35 static const char *const var_names[] = {
36     "E",
37     "PHI",
38     "PI",
39     "w",        ///< width of the input video
40     "h",        ///< height of the input video
41     "val",      ///< input value for the pixel
42     "maxval",   ///< max value for the pixel
43     "minval",   ///< min value for the pixel
44     "negval",   ///< negated value
45     "clipval",
46     NULL
47 };
48
49 enum var_name {
50     VAR_E,
51     VAR_PHI,
52     VAR_PI,
53     VAR_W,
54     VAR_H,
55     VAR_VAL,
56     VAR_MAXVAL,
57     VAR_MINVAL,
58     VAR_NEGVAL,
59     VAR_CLIPVAL,
60     VAR_VARS_NB
61 };
62
63 typedef struct {
64     const AVClass *class;
65     uint8_t lut[4][256];  ///< lookup table for each component
66     char   *comp_expr_str[4];
67     AVExpr *comp_expr[4];
68     int hsub, vsub;
69     double var_values[VAR_VARS_NB];
70     int is_rgb, is_yuv;
71     int rgba_map[4];
72     int step;
73     int negate_alpha; /* only used by negate */
74 } LutContext;
75
76 #define Y 0
77 #define U 1
78 #define V 2
79 #define R 0
80 #define G 1
81 #define B 2
82 #define A 3
83
84 #define OFFSET(x) offsetof(LutContext, x)
85
86 static const AVOption lut_options[] = {
87     {"c0", "set component #0 expression", OFFSET(comp_expr_str[0]),  FF_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
88     {"c1", "set component #1 expression", OFFSET(comp_expr_str[1]),  FF_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
89     {"c2", "set component #2 expression", OFFSET(comp_expr_str[2]),  FF_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
90     {"c3", "set component #3 expression", OFFSET(comp_expr_str[3]),  FF_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
91     {"y",  "set Y expression", OFFSET(comp_expr_str[Y]),  FF_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
92     {"u",  "set U expression", OFFSET(comp_expr_str[U]),  FF_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
93     {"v",  "set V expression", OFFSET(comp_expr_str[V]),  FF_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
94     {"r",  "set R expression", OFFSET(comp_expr_str[R]),  FF_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
95     {"g",  "set G expression", OFFSET(comp_expr_str[G]),  FF_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
96     {"b",  "set B expression", OFFSET(comp_expr_str[B]),  FF_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
97     {"a",  "set A expression", OFFSET(comp_expr_str[A]),  FF_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
98     {NULL},
99 };
100
101 static const char *lut_get_name(void *ctx)
102 {
103     return "lut";
104 }
105
106 static const AVClass lut_class = {
107     "LutContext",
108     lut_get_name,
109     lut_options
110 };
111
112 static int init(AVFilterContext *ctx, const char *args, void *opaque)
113 {
114     LutContext *lut = ctx->priv;
115     int ret;
116
117     lut->class = &lut_class;
118     av_opt_set_defaults(lut);
119
120     lut->var_values[VAR_PHI] = M_PHI;
121     lut->var_values[VAR_PI]  = M_PI;
122     lut->var_values[VAR_E ]  = M_E;
123
124     lut->is_rgb = !strcmp(ctx->filter->name, "lutrgb");
125     lut->is_yuv = !strcmp(ctx->filter->name, "lutyuv");
126     if (args && (ret = av_set_options_string(lut, args, "=", ":")) < 0)
127         return ret;
128
129     return 0;
130 }
131
132 static av_cold void uninit(AVFilterContext *ctx)
133 {
134     LutContext *lut = ctx->priv;
135     int i;
136
137     for (i = 0; i < 4; i++) {
138         av_expr_free(lut->comp_expr[i]);
139         lut->comp_expr[i] = NULL;
140         av_freep(&lut->comp_expr_str[i]);
141     }
142 }
143
144 #define YUV_FORMATS                                         \
145     PIX_FMT_YUV444P,  PIX_FMT_YUV422P,  PIX_FMT_YUV420P,    \
146     PIX_FMT_YUV411P,  PIX_FMT_YUV410P,  PIX_FMT_YUV440P,    \
147     PIX_FMT_YUVA420P,                                       \
148     PIX_FMT_YUVJ444P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ420P,   \
149     PIX_FMT_YUVJ440P
150
151 #define RGB_FORMATS                             \
152     PIX_FMT_ARGB,         PIX_FMT_RGBA,         \
153     PIX_FMT_ABGR,         PIX_FMT_BGRA,         \
154     PIX_FMT_RGB24,        PIX_FMT_BGR24
155
156 static enum PixelFormat yuv_pix_fmts[] = { YUV_FORMATS, PIX_FMT_NONE };
157 static enum PixelFormat rgb_pix_fmts[] = { RGB_FORMATS, PIX_FMT_NONE };
158 static enum PixelFormat all_pix_fmts[] = { RGB_FORMATS, YUV_FORMATS, PIX_FMT_NONE };
159
160 static int query_formats(AVFilterContext *ctx)
161 {
162     LutContext *lut = ctx->priv;
163
164     enum PixelFormat *pix_fmts = lut->is_rgb ? rgb_pix_fmts :
165                                  lut->is_yuv ? yuv_pix_fmts : all_pix_fmts;
166
167     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
168     return 0;
169 }
170
171 /**
172  * Clip value val in the minval - maxval range.
173  */
174 static double clip(void *opaque, double val)
175 {
176     LutContext *lut = opaque;
177     double minval = lut->var_values[VAR_MINVAL];
178     double maxval = lut->var_values[VAR_MAXVAL];
179
180     return av_clip(val, minval, maxval);
181 }
182
183 /**
184  * Compute gamma correction for value val, assuming the minval-maxval
185  * range, val is clipped to a value contained in the same interval.
186  */
187 static double compute_gammaval(void *opaque, double gamma)
188 {
189     LutContext *lut = opaque;
190     double val    = lut->var_values[VAR_CLIPVAL];
191     double minval = lut->var_values[VAR_MINVAL];
192     double maxval = lut->var_values[VAR_MAXVAL];
193
194     return pow((val-minval)/(maxval-minval), gamma) * (maxval-minval)+minval;
195 }
196
197 static double (* const funcs1[])(void *, double) = {
198     clip,
199     compute_gammaval,
200     NULL
201 };
202
203 static const char * const funcs1_names[] = {
204     "clip",
205     "gammaval",
206     NULL
207 };
208
209 static int config_props(AVFilterLink *inlink)
210 {
211     AVFilterContext *ctx = inlink->dst;
212     LutContext *lut = ctx->priv;
213     const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[inlink->format];
214     int min[4], max[4];
215     int val, comp, ret;
216
217     lut->hsub = desc->log2_chroma_w;
218     lut->vsub = desc->log2_chroma_h;
219
220     lut->var_values[VAR_W] = inlink->w;
221     lut->var_values[VAR_H] = inlink->h;
222
223     switch (inlink->format) {
224     case PIX_FMT_YUV410P:
225     case PIX_FMT_YUV411P:
226     case PIX_FMT_YUV420P:
227     case PIX_FMT_YUV422P:
228     case PIX_FMT_YUV440P:
229     case PIX_FMT_YUV444P:
230     case PIX_FMT_YUVA420P:
231         min[Y] = min[U] = min[V] = 16;
232         max[Y] = 235;
233         max[U] = max[V] = 240;
234         min[A] = 0; max[A] = 255;
235         break;
236     default:
237         min[0] = min[1] = min[2] = min[3] = 0;
238         max[0] = max[1] = max[2] = max[3] = 255;
239     }
240
241     lut->is_yuv = lut->is_rgb = 0;
242     if      (ff_fmt_is_in(inlink->format, yuv_pix_fmts)) lut->is_yuv = 1;
243     else if (ff_fmt_is_in(inlink->format, rgb_pix_fmts)) lut->is_rgb = 1;
244
245     if (lut->is_rgb) {
246         switch (inlink->format) {
247         case PIX_FMT_ARGB:  lut->rgba_map[A] = 0; lut->rgba_map[R] = 1; lut->rgba_map[G] = 2; lut->rgba_map[B] = 3; break;
248         case PIX_FMT_ABGR:  lut->rgba_map[A] = 0; lut->rgba_map[B] = 1; lut->rgba_map[G] = 2; lut->rgba_map[R] = 3; break;
249         case PIX_FMT_RGBA:
250         case PIX_FMT_RGB24: lut->rgba_map[R] = 0; lut->rgba_map[G] = 1; lut->rgba_map[B] = 2; lut->rgba_map[A] = 3; break;
251         case PIX_FMT_BGRA:
252         case PIX_FMT_BGR24: lut->rgba_map[B] = 0; lut->rgba_map[G] = 1; lut->rgba_map[R] = 2; lut->rgba_map[A] = 3; break;
253         }
254         lut->step = av_get_bits_per_pixel(desc) >> 3;
255     }
256
257     for (comp = 0; comp < desc->nb_components; comp++) {
258         double res;
259
260         /* create the parsed expression */
261         ret = av_expr_parse(&lut->comp_expr[comp], lut->comp_expr_str[comp],
262                             var_names, funcs1_names, funcs1, NULL, NULL, 0, ctx);
263         if (ret < 0) {
264             av_log(ctx, AV_LOG_ERROR,
265                    "Error when parsing the expression '%s' for the component %d.\n",
266                    lut->comp_expr_str[comp], comp);
267             return AVERROR(EINVAL);
268         }
269
270         /* compute the lut */
271         lut->var_values[VAR_MAXVAL] = max[comp];
272         lut->var_values[VAR_MINVAL] = min[comp];
273
274         for (val = 0; val < 256; val++) {
275             lut->var_values[VAR_VAL] = val;
276             lut->var_values[VAR_CLIPVAL] = av_clip(val, min[comp], max[comp]);
277             lut->var_values[VAR_NEGVAL] =
278                 av_clip(min[comp] + max[comp] - lut->var_values[VAR_VAL],
279                         min[comp], max[comp]);
280
281             res = av_expr_eval(lut->comp_expr[comp], lut->var_values, lut);
282             if (isnan(res)) {
283                 av_log(ctx, AV_LOG_ERROR,
284                        "Error when evaluating the expression '%s' for the value %d for the component #%d.\n",
285                        lut->comp_expr_str[comp], val, comp);
286                 return AVERROR(EINVAL);
287             }
288             lut->lut[comp][val] = av_clip((int)res, min[comp], max[comp]);
289             av_log(ctx, AV_LOG_DEBUG, "val[%d][%d] = %d\n", comp, val, lut->lut[comp][val]);
290         }
291     }
292
293     return 0;
294 }
295
296 static void draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
297 {
298     AVFilterContext *ctx = inlink->dst;
299     LutContext *lut = ctx->priv;
300     AVFilterLink *outlink = ctx->outputs[0];
301     AVFilterBufferRef *inpic  = inlink ->cur_buf;
302     AVFilterBufferRef *outpic = outlink->out_buf;
303     uint8_t *inrow, *outrow, *inrow0, *outrow0;
304     int i, j, k, plane;
305
306     if (lut->is_rgb) {
307         /* packed */
308         inrow0  = inpic ->data[0] + y * inpic ->linesize[0];
309         outrow0 = outpic->data[0] + y * outpic->linesize[0];
310
311         for (i = 0; i < h; i ++) {
312             inrow  = inrow0;
313             outrow = outrow0;
314             for (j = 0; j < inlink->w; j++) {
315                 for (k = 0; k < lut->step; k++)
316                     outrow[k] = lut->lut[lut->rgba_map[k]][inrow[k]];
317                 outrow += lut->step;
318                 inrow  += lut->step;
319             }
320             inrow0  += inpic ->linesize[0];
321             outrow0 += outpic->linesize[0];
322         }
323     } else {
324         /* planar */
325         for (plane = 0; plane < 4 && inpic->data[plane]; plane++) {
326             int vsub = plane == 1 || plane == 2 ? lut->vsub : 0;
327             int hsub = plane == 1 || plane == 2 ? lut->hsub : 0;
328
329             inrow  = inpic ->data[plane] + (y>>vsub) * inpic ->linesize[plane];
330             outrow = outpic->data[plane] + (y>>vsub) * outpic->linesize[plane];
331
332             for (i = 0; i < h>>vsub; i ++) {
333                 for (j = 0; j < inlink->w>>hsub; j++)
334                     outrow[j] = lut->lut[plane][inrow[j]];
335                 inrow  += inpic ->linesize[plane];
336                 outrow += outpic->linesize[plane];
337             }
338         }
339     }
340
341     avfilter_draw_slice(outlink, y, h, slice_dir);
342 }
343
344 #define DEFINE_LUT_FILTER(name_, description_, init_)                   \
345     AVFilter avfilter_vf_##name_ = {                                    \
346         .name          = #name_,                                        \
347         .description   = NULL_IF_CONFIG_SMALL(description_),            \
348         .priv_size     = sizeof(LutContext),                            \
349                                                                         \
350         .init          = init_,                                         \
351         .uninit        = uninit,                                        \
352         .query_formats = query_formats,                                 \
353                                                                         \
354         .inputs    = (AVFilterPad[]) {{ .name            = "default",   \
355                                         .type            = AVMEDIA_TYPE_VIDEO, \
356                                         .draw_slice      = draw_slice,  \
357                                         .config_props    = config_props, \
358                                         .min_perms       = AV_PERM_READ, }, \
359                                       { .name = NULL}},                 \
360         .outputs   = (AVFilterPad[]) {{ .name            = "default",   \
361                                         .type            = AVMEDIA_TYPE_VIDEO, }, \
362                                       { .name = NULL}},                 \
363     }
364
365 #if CONFIG_LUT_FILTER
366 DEFINE_LUT_FILTER(lut,    "Compute and apply a lookup table to the RGB/YUV input video.", init);
367 #endif
368 #if CONFIG_LUTYUV_FILTER
369 DEFINE_LUT_FILTER(lutyuv, "Compute and apply a lookup table to the YUV input video.",     init);
370 #endif
371 #if CONFIG_LUTRGB_FILTER
372 DEFINE_LUT_FILTER(lutrgb, "Compute and apply a lookup table to the RGB input video.",     init);
373 #endif
374
375 #if CONFIG_NEGATE_FILTER
376
377 static int negate_init(AVFilterContext *ctx, const char *args, void *opaque)
378 {
379     LutContext *lut = ctx->priv;
380     char lut_params[64];
381
382     if (args)
383         sscanf(args, "%d", &lut->negate_alpha);
384
385     av_log(ctx, AV_LOG_DEBUG, "negate_alpha:%d\n", lut->negate_alpha);
386
387     snprintf(lut_params, sizeof(lut_params), "c0=negval:c1=negval:c2=negval:a=%s",
388              lut->negate_alpha ? "negval" : "val");
389
390     return init(ctx, lut_params, opaque);
391 }
392
393 DEFINE_LUT_FILTER(negate, "Negate input video.", negate_init);
394
395 #endif