]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_lut.c
Merge commit '36ef5369ee9b336febc2c270f8718cec4476cb85'
[ffmpeg] / libavfilter / vf_lut.c
1 /*
2  * Copyright (c) 2011 Stefano Sabatini
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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/opt.h"
29 #include "libavutil/pixdesc.h"
30 #include "avfilter.h"
31 #include "formats.h"
32 #include "internal.h"
33 #include "video.h"
34
35 static const char *const var_names[] = {
36     "w",        ///< width of the input video
37     "h",        ///< height of the input video
38     "val",      ///< input value for the pixel
39     "maxval",   ///< max value for the pixel
40     "minval",   ///< min value for the pixel
41     "negval",   ///< negated value
42     "clipval",
43     NULL
44 };
45
46 enum var_name {
47     VAR_W,
48     VAR_H,
49     VAR_VAL,
50     VAR_MAXVAL,
51     VAR_MINVAL,
52     VAR_NEGVAL,
53     VAR_CLIPVAL,
54     VAR_VARS_NB
55 };
56
57 typedef struct {
58     const AVClass *class;
59     uint8_t lut[4][256];  ///< lookup table for each component
60     char   *comp_expr_str[4];
61     AVExpr *comp_expr[4];
62     int hsub, vsub;
63     double var_values[VAR_VARS_NB];
64     int is_rgb, is_yuv;
65     int step;
66     int negate_alpha; /* only used by negate */
67 } LutContext;
68
69 #define Y 0
70 #define U 1
71 #define V 2
72 #define R 0
73 #define G 1
74 #define B 2
75 #define A 3
76
77 #define OFFSET(x) offsetof(LutContext, x)
78
79 static const AVOption lut_options[] = {
80     {"c0", "set component #0 expression", OFFSET(comp_expr_str[0]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
81     {"c1", "set component #1 expression", OFFSET(comp_expr_str[1]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
82     {"c2", "set component #2 expression", OFFSET(comp_expr_str[2]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
83     {"c3", "set component #3 expression", OFFSET(comp_expr_str[3]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
84     {"y",  "set Y expression", OFFSET(comp_expr_str[Y]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
85     {"u",  "set U expression", OFFSET(comp_expr_str[U]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
86     {"v",  "set V expression", OFFSET(comp_expr_str[V]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
87     {"r",  "set R expression", OFFSET(comp_expr_str[R]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
88     {"g",  "set G expression", OFFSET(comp_expr_str[G]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
89     {"b",  "set B expression", OFFSET(comp_expr_str[B]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
90     {"a",  "set A expression", OFFSET(comp_expr_str[A]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX},
91     {NULL},
92 };
93
94 AVFILTER_DEFINE_CLASS(lut);
95
96 static int init(AVFilterContext *ctx, const char *args)
97 {
98     LutContext *lut = ctx->priv;
99     int ret;
100
101     lut->class = &lut_class;
102     av_opt_set_defaults(lut);
103
104     lut->is_rgb = !strcmp(ctx->filter->name, "lutrgb");
105     lut->is_yuv = !strcmp(ctx->filter->name, "lutyuv");
106     if (args && (ret = av_set_options_string(lut, args, "=", ":")) < 0)
107         return ret;
108
109     return 0;
110 }
111
112 static av_cold void uninit(AVFilterContext *ctx)
113 {
114     LutContext *lut = ctx->priv;
115     int i;
116
117     for (i = 0; i < 4; i++) {
118         av_expr_free(lut->comp_expr[i]);
119         lut->comp_expr[i] = NULL;
120         av_freep(&lut->comp_expr_str[i]);
121     }
122 }
123
124 #define YUV_FORMATS                                         \
125     PIX_FMT_YUV444P,  PIX_FMT_YUV422P,  PIX_FMT_YUV420P,    \
126     PIX_FMT_YUV411P,  PIX_FMT_YUV410P,  PIX_FMT_YUV440P,    \
127     PIX_FMT_YUVA420P,                                       \
128     PIX_FMT_YUVJ444P, PIX_FMT_YUVJ422P, PIX_FMT_YUVJ420P,   \
129     PIX_FMT_YUVJ440P
130
131 #define RGB_FORMATS                             \
132     PIX_FMT_ARGB,         PIX_FMT_RGBA,         \
133     PIX_FMT_ABGR,         PIX_FMT_BGRA,         \
134     PIX_FMT_RGB24,        PIX_FMT_BGR24
135
136 static const enum PixelFormat yuv_pix_fmts[] = { YUV_FORMATS, PIX_FMT_NONE };
137 static const enum PixelFormat rgb_pix_fmts[] = { RGB_FORMATS, PIX_FMT_NONE };
138 static const enum PixelFormat all_pix_fmts[] = { RGB_FORMATS, YUV_FORMATS, PIX_FMT_NONE };
139
140 static int query_formats(AVFilterContext *ctx)
141 {
142     LutContext *lut = ctx->priv;
143
144     const enum PixelFormat *pix_fmts = lut->is_rgb ? rgb_pix_fmts :
145                                        lut->is_yuv ? yuv_pix_fmts : all_pix_fmts;
146
147     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
148     return 0;
149 }
150
151 /**
152  * Clip value val in the minval - maxval range.
153  */
154 static double clip(void *opaque, double val)
155 {
156     LutContext *lut = opaque;
157     double minval = lut->var_values[VAR_MINVAL];
158     double maxval = lut->var_values[VAR_MAXVAL];
159
160     return av_clip(val, minval, maxval);
161 }
162
163 /**
164  * Compute gamma correction for value val, assuming the minval-maxval
165  * range, val is clipped to a value contained in the same interval.
166  */
167 static double compute_gammaval(void *opaque, double gamma)
168 {
169     LutContext *lut = opaque;
170     double val    = lut->var_values[VAR_CLIPVAL];
171     double minval = lut->var_values[VAR_MINVAL];
172     double maxval = lut->var_values[VAR_MAXVAL];
173
174     return pow((val-minval)/(maxval-minval), gamma) * (maxval-minval)+minval;
175 }
176
177 static double (* const funcs1[])(void *, double) = {
178     (void *)clip,
179     (void *)compute_gammaval,
180     NULL
181 };
182
183 static const char * const funcs1_names[] = {
184     "clip",
185     "gammaval",
186     NULL
187 };
188
189 static int config_props(AVFilterLink *inlink)
190 {
191     AVFilterContext *ctx = inlink->dst;
192     LutContext *lut = ctx->priv;
193     const AVPixFmtDescriptor *desc = &av_pix_fmt_descriptors[inlink->format];
194     int rgba_map[4]; /* component index -> RGBA color index map */
195     int min[4], max[4];
196     int val, comp, ret;
197
198     lut->hsub = desc->log2_chroma_w;
199     lut->vsub = desc->log2_chroma_h;
200
201     lut->var_values[VAR_W] = inlink->w;
202     lut->var_values[VAR_H] = inlink->h;
203
204     switch (inlink->format) {
205     case PIX_FMT_YUV410P:
206     case PIX_FMT_YUV411P:
207     case PIX_FMT_YUV420P:
208     case PIX_FMT_YUV422P:
209     case PIX_FMT_YUV440P:
210     case PIX_FMT_YUV444P:
211     case PIX_FMT_YUVA420P:
212         min[Y] = min[U] = min[V] = 16;
213         max[Y] = 235;
214         max[U] = max[V] = 240;
215         min[A] = 0; max[A] = 255;
216         break;
217     default:
218         min[0] = min[1] = min[2] = min[3] = 0;
219         max[0] = max[1] = max[2] = max[3] = 255;
220     }
221
222     lut->is_yuv = lut->is_rgb = 0;
223     if      (ff_fmt_is_in(inlink->format, yuv_pix_fmts)) lut->is_yuv = 1;
224     else if (ff_fmt_is_in(inlink->format, rgb_pix_fmts)) lut->is_rgb = 1;
225
226     if (lut->is_rgb) {
227         switch (inlink->format) {
228         case PIX_FMT_ARGB:  rgba_map[0] = A; rgba_map[1] = R; rgba_map[2] = G; rgba_map[3] = B; break;
229         case PIX_FMT_ABGR:  rgba_map[0] = A; rgba_map[1] = B; rgba_map[2] = G; rgba_map[3] = R; break;
230         case PIX_FMT_RGBA:
231         case PIX_FMT_RGB24: rgba_map[0] = R; rgba_map[1] = G; rgba_map[2] = B; rgba_map[3] = A; break;
232         case PIX_FMT_BGRA:
233         case PIX_FMT_BGR24: rgba_map[0] = B; rgba_map[1] = G; rgba_map[2] = R; rgba_map[3] = A; break;
234         }
235         lut->step = av_get_bits_per_pixel(desc) >> 3;
236     }
237
238     for (comp = 0; comp < desc->nb_components; comp++) {
239         double res;
240         int color = lut->is_rgb ? rgba_map[comp] : comp;
241
242         /* create the parsed expression */
243         ret = av_expr_parse(&lut->comp_expr[color], lut->comp_expr_str[color],
244                             var_names, funcs1_names, funcs1, NULL, NULL, 0, ctx);
245         if (ret < 0) {
246             av_log(ctx, AV_LOG_ERROR,
247                    "Error when parsing the expression '%s' for the component %d and color %d.\n",
248                    lut->comp_expr_str[comp], comp, color);
249             return AVERROR(EINVAL);
250         }
251
252         /* compute the lut */
253         lut->var_values[VAR_MAXVAL] = max[color];
254         lut->var_values[VAR_MINVAL] = min[color];
255
256         for (val = 0; val < 256; val++) {
257             lut->var_values[VAR_VAL] = val;
258             lut->var_values[VAR_CLIPVAL] = av_clip(val, min[color], max[color]);
259             lut->var_values[VAR_NEGVAL] =
260                 av_clip(min[color] + max[color] - lut->var_values[VAR_VAL],
261                         min[color], max[color]);
262
263             res = av_expr_eval(lut->comp_expr[color], lut->var_values, lut);
264             if (isnan(res)) {
265                 av_log(ctx, AV_LOG_ERROR,
266                        "Error when evaluating the expression '%s' for the value %d for the component %d.\n",
267                        lut->comp_expr_str[color], val, comp);
268                 return AVERROR(EINVAL);
269             }
270             lut->lut[comp][val] = av_clip((int)res, min[color], max[color]);
271             av_log(ctx, AV_LOG_DEBUG, "val[%d][%d] = %d\n", comp, val, lut->lut[comp][val]);
272         }
273     }
274
275     return 0;
276 }
277
278 static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
279 {
280     AVFilterContext *ctx = inlink->dst;
281     LutContext *lut = ctx->priv;
282     AVFilterLink *outlink = ctx->outputs[0];
283     AVFilterBufferRef *inpic  = inlink ->cur_buf;
284     AVFilterBufferRef *outpic = outlink->out_buf;
285     uint8_t *inrow, *outrow, *inrow0, *outrow0;
286     int i, j, plane;
287
288     if (lut->is_rgb) {
289         /* packed */
290         inrow0  = inpic ->data[0] + y * inpic ->linesize[0];
291         outrow0 = outpic->data[0] + y * outpic->linesize[0];
292
293         for (i = 0; i < h; i ++) {
294             int w = inlink->w;
295             const uint8_t (*tab)[256] = (const uint8_t (*)[256])lut->lut;
296             inrow  = inrow0;
297             outrow = outrow0;
298             for (j = 0; j < w; j++) {
299                 outrow[0] = tab[0][inrow[0]];
300                 if (lut->step>1) {
301                     outrow[1] = tab[1][inrow[1]];
302                     if (lut->step>2) {
303                         outrow[2] = tab[2][inrow[2]];
304                         if (lut->step>3) {
305                             outrow[3] = tab[3][inrow[3]];
306                         }
307                     }
308                 }
309                 outrow += lut->step;
310                 inrow  += lut->step;
311             }
312             inrow0  += inpic ->linesize[0];
313             outrow0 += outpic->linesize[0];
314         }
315     } else {
316         /* planar */
317         for (plane = 0; plane < 4 && inpic->data[plane]; plane++) {
318             int vsub = plane == 1 || plane == 2 ? lut->vsub : 0;
319             int hsub = plane == 1 || plane == 2 ? lut->hsub : 0;
320
321             inrow  = inpic ->data[plane] + (y>>vsub) * inpic ->linesize[plane];
322             outrow = outpic->data[plane] + (y>>vsub) * outpic->linesize[plane];
323
324             for (i = 0; i < (h + (1<<vsub) - 1)>>vsub; i ++) {
325                 const uint8_t *tab = lut->lut[plane];
326                 int w = (inlink->w + (1<<hsub) - 1)>>hsub;
327                 for (j = 0; j < w; j++)
328                     outrow[j] = tab[inrow[j]];
329                 inrow  += inpic ->linesize[plane];
330                 outrow += outpic->linesize[plane];
331             }
332         }
333     }
334
335     return ff_draw_slice(outlink, y, h, slice_dir);
336 }
337
338 static const AVFilterPad inputs[] = {
339     { .name            = "default",
340       .type            = AVMEDIA_TYPE_VIDEO,
341       .draw_slice      = draw_slice,
342       .config_props    = config_props,
343       .min_perms       = AV_PERM_READ, },
344     { .name = NULL}
345 };
346 static const AVFilterPad outputs[] = {
347     { .name            = "default",
348       .type            = AVMEDIA_TYPE_VIDEO, },
349     { .name = NULL}
350 };
351 #define DEFINE_LUT_FILTER(name_, description_, init_)                   \
352     AVFilter avfilter_vf_##name_ = {                                    \
353         .name          = #name_,                                        \
354         .description   = NULL_IF_CONFIG_SMALL(description_),            \
355         .priv_size     = sizeof(LutContext),                            \
356                                                                         \
357         .init          = init_,                                         \
358         .uninit        = uninit,                                        \
359         .query_formats = query_formats,                                 \
360                                                                         \
361         .inputs        = inputs,                                        \
362         .outputs       = outputs,                                       \
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)
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);
391 }
392
393 DEFINE_LUT_FILTER(negate, "Negate input video.", negate_init);
394
395 #endif