]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_lut.c
Merge commit '468ea9d5b14f92fe61f47f034e67066f65163f5f'
[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/common.h"
28 #include "libavutil/eval.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/pixdesc.h"
31 #include "avfilter.h"
32 #include "formats.h"
33 #include "internal.h"
34 #include "video.h"
35
36 static const char *const var_names[] = {
37     "w",        ///< width of the input video
38     "h",        ///< height of the input video
39     "val",      ///< input value for the pixel
40     "maxval",   ///< max value for the pixel
41     "minval",   ///< min value for the pixel
42     "negval",   ///< negated value
43     "clipval",
44     NULL
45 };
46
47 enum var_name {
48     VAR_W,
49     VAR_H,
50     VAR_VAL,
51     VAR_MAXVAL,
52     VAR_MINVAL,
53     VAR_NEGVAL,
54     VAR_CLIPVAL,
55     VAR_VARS_NB
56 };
57
58 typedef struct {
59     const AVClass *class;
60     uint8_t lut[4][256];  ///< lookup table for each component
61     char   *comp_expr_str[4];
62     AVExpr *comp_expr[4];
63     int hsub, vsub;
64     double var_values[VAR_VARS_NB];
65     int is_rgb, is_yuv;
66     int step;
67     int negate_alpha; /* only used by negate */
68 } LutContext;
69
70 #define Y 0
71 #define U 1
72 #define V 2
73 #define R 0
74 #define G 1
75 #define B 2
76 #define A 3
77
78 #define OFFSET(x) offsetof(LutContext, x)
79 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
80
81 static const AVOption options[] = {
82     {"c0", "set component #0 expression", OFFSET(comp_expr_str[0]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
83     {"c1", "set component #1 expression", OFFSET(comp_expr_str[1]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
84     {"c2", "set component #2 expression", OFFSET(comp_expr_str[2]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
85     {"c3", "set component #3 expression", OFFSET(comp_expr_str[3]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
86     {"y",  "set Y expression", OFFSET(comp_expr_str[Y]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
87     {"u",  "set U expression", OFFSET(comp_expr_str[U]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
88     {"v",  "set V expression", OFFSET(comp_expr_str[V]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
89     {"r",  "set R expression", OFFSET(comp_expr_str[R]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
90     {"g",  "set G expression", OFFSET(comp_expr_str[G]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
91     {"b",  "set B expression", OFFSET(comp_expr_str[B]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
92     {"a",  "set A expression", OFFSET(comp_expr_str[A]),  AV_OPT_TYPE_STRING, {.str="val"}, CHAR_MIN, CHAR_MAX, FLAGS},
93     {NULL},
94 };
95
96 static av_cold void uninit(AVFilterContext *ctx)
97 {
98     LutContext *lut = ctx->priv;
99     int i;
100
101     for (i = 0; i < 4; i++) {
102         av_expr_free(lut->comp_expr[i]);
103         lut->comp_expr[i] = NULL;
104         av_freep(&lut->comp_expr_str[i]);
105     }
106 }
107
108 #define YUV_FORMATS                                         \
109     AV_PIX_FMT_YUV444P,  AV_PIX_FMT_YUV422P,  AV_PIX_FMT_YUV420P,    \
110     AV_PIX_FMT_YUV411P,  AV_PIX_FMT_YUV410P,  AV_PIX_FMT_YUV440P,    \
111     AV_PIX_FMT_YUVA420P,                                       \
112     AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ420P,   \
113     AV_PIX_FMT_YUVJ440P
114
115 #define RGB_FORMATS                             \
116     AV_PIX_FMT_ARGB,         AV_PIX_FMT_RGBA,         \
117     AV_PIX_FMT_ABGR,         AV_PIX_FMT_BGRA,         \
118     AV_PIX_FMT_RGB24,        AV_PIX_FMT_BGR24
119
120 static const enum AVPixelFormat yuv_pix_fmts[] = { YUV_FORMATS, AV_PIX_FMT_NONE };
121 static const enum AVPixelFormat rgb_pix_fmts[] = { RGB_FORMATS, AV_PIX_FMT_NONE };
122 static const enum AVPixelFormat all_pix_fmts[] = { RGB_FORMATS, YUV_FORMATS, AV_PIX_FMT_NONE };
123
124 static int query_formats(AVFilterContext *ctx)
125 {
126     LutContext *lut = ctx->priv;
127
128     const enum AVPixelFormat *pix_fmts = lut->is_rgb ? rgb_pix_fmts :
129                                        lut->is_yuv ? yuv_pix_fmts : all_pix_fmts;
130
131     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
132     return 0;
133 }
134
135 /**
136  * Clip value val in the minval - maxval range.
137  */
138 static double clip(void *opaque, double val)
139 {
140     LutContext *lut = opaque;
141     double minval = lut->var_values[VAR_MINVAL];
142     double maxval = lut->var_values[VAR_MAXVAL];
143
144     return av_clip(val, minval, maxval);
145 }
146
147 /**
148  * Compute gamma correction for value val, assuming the minval-maxval
149  * range, val is clipped to a value contained in the same interval.
150  */
151 static double compute_gammaval(void *opaque, double gamma)
152 {
153     LutContext *lut = opaque;
154     double val    = lut->var_values[VAR_CLIPVAL];
155     double minval = lut->var_values[VAR_MINVAL];
156     double maxval = lut->var_values[VAR_MAXVAL];
157
158     return pow((val-minval)/(maxval-minval), gamma) * (maxval-minval)+minval;
159 }
160
161 static double (* const funcs1[])(void *, double) = {
162     (void *)clip,
163     (void *)compute_gammaval,
164     NULL
165 };
166
167 static const char * const funcs1_names[] = {
168     "clip",
169     "gammaval",
170     NULL
171 };
172
173 static int config_props(AVFilterLink *inlink)
174 {
175     AVFilterContext *ctx = inlink->dst;
176     LutContext *lut = ctx->priv;
177     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
178     int rgba_map[4]; /* component index -> RGBA color index map */
179     int min[4], max[4];
180     int val, comp, ret;
181
182     lut->hsub = desc->log2_chroma_w;
183     lut->vsub = desc->log2_chroma_h;
184
185     lut->var_values[VAR_W] = inlink->w;
186     lut->var_values[VAR_H] = inlink->h;
187
188     switch (inlink->format) {
189     case AV_PIX_FMT_YUV410P:
190     case AV_PIX_FMT_YUV411P:
191     case AV_PIX_FMT_YUV420P:
192     case AV_PIX_FMT_YUV422P:
193     case AV_PIX_FMT_YUV440P:
194     case AV_PIX_FMT_YUV444P:
195     case AV_PIX_FMT_YUVA420P:
196         min[Y] = min[U] = min[V] = 16;
197         max[Y] = 235;
198         max[U] = max[V] = 240;
199         min[A] = 0; max[A] = 255;
200         break;
201     default:
202         min[0] = min[1] = min[2] = min[3] = 0;
203         max[0] = max[1] = max[2] = max[3] = 255;
204     }
205
206     lut->is_yuv = lut->is_rgb = 0;
207     if      (ff_fmt_is_in(inlink->format, yuv_pix_fmts)) lut->is_yuv = 1;
208     else if (ff_fmt_is_in(inlink->format, rgb_pix_fmts)) lut->is_rgb = 1;
209
210     if (lut->is_rgb) {
211         switch (inlink->format) {
212         case AV_PIX_FMT_ARGB:  rgba_map[0] = A; rgba_map[1] = R; rgba_map[2] = G; rgba_map[3] = B; break;
213         case AV_PIX_FMT_ABGR:  rgba_map[0] = A; rgba_map[1] = B; rgba_map[2] = G; rgba_map[3] = R; break;
214         case AV_PIX_FMT_RGBA:
215         case AV_PIX_FMT_RGB24: rgba_map[0] = R; rgba_map[1] = G; rgba_map[2] = B; rgba_map[3] = A; break;
216         case AV_PIX_FMT_BGRA:
217         case AV_PIX_FMT_BGR24: rgba_map[0] = B; rgba_map[1] = G; rgba_map[2] = R; rgba_map[3] = A; break;
218         }
219         lut->step = av_get_bits_per_pixel(desc) >> 3;
220     }
221
222     for (comp = 0; comp < desc->nb_components; comp++) {
223         double res;
224         int color = lut->is_rgb ? rgba_map[comp] : comp;
225
226         /* create the parsed expression */
227         ret = av_expr_parse(&lut->comp_expr[color], lut->comp_expr_str[color],
228                             var_names, funcs1_names, funcs1, NULL, NULL, 0, ctx);
229         if (ret < 0) {
230             av_log(ctx, AV_LOG_ERROR,
231                    "Error when parsing the expression '%s' for the component %d and color %d.\n",
232                    lut->comp_expr_str[comp], comp, color);
233             return AVERROR(EINVAL);
234         }
235
236         /* compute the lut */
237         lut->var_values[VAR_MAXVAL] = max[color];
238         lut->var_values[VAR_MINVAL] = min[color];
239
240         for (val = 0; val < 256; val++) {
241             lut->var_values[VAR_VAL] = val;
242             lut->var_values[VAR_CLIPVAL] = av_clip(val, min[color], max[color]);
243             lut->var_values[VAR_NEGVAL] =
244                 av_clip(min[color] + max[color] - lut->var_values[VAR_VAL],
245                         min[color], max[color]);
246
247             res = av_expr_eval(lut->comp_expr[color], lut->var_values, lut);
248             if (isnan(res)) {
249                 av_log(ctx, AV_LOG_ERROR,
250                        "Error when evaluating the expression '%s' for the value %d for the component %d.\n",
251                        lut->comp_expr_str[color], val, comp);
252                 return AVERROR(EINVAL);
253             }
254             lut->lut[comp][val] = av_clip((int)res, min[color], max[color]);
255             av_log(ctx, AV_LOG_DEBUG, "val[%d][%d] = %d\n", comp, val, lut->lut[comp][val]);
256         }
257     }
258
259     return 0;
260 }
261
262 static int draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)
263 {
264     AVFilterContext *ctx = inlink->dst;
265     LutContext *lut = ctx->priv;
266     AVFilterLink *outlink = ctx->outputs[0];
267     AVFilterBufferRef *inpic  = inlink ->cur_buf;
268     AVFilterBufferRef *outpic = outlink->out_buf;
269     uint8_t *inrow, *outrow, *inrow0, *outrow0;
270     int i, j, plane;
271
272     if (lut->is_rgb) {
273         /* packed */
274         inrow0  = inpic ->data[0] + y * inpic ->linesize[0];
275         outrow0 = outpic->data[0] + y * outpic->linesize[0];
276
277         for (i = 0; i < h; i ++) {
278             int w = inlink->w;
279             const uint8_t (*tab)[256] = (const uint8_t (*)[256])lut->lut;
280             inrow  = inrow0;
281             outrow = outrow0;
282             for (j = 0; j < w; j++) {
283                 outrow[0] = tab[0][inrow[0]];
284                 if (lut->step>1) {
285                     outrow[1] = tab[1][inrow[1]];
286                     if (lut->step>2) {
287                         outrow[2] = tab[2][inrow[2]];
288                         if (lut->step>3) {
289                             outrow[3] = tab[3][inrow[3]];
290                         }
291                     }
292                 }
293                 outrow += lut->step;
294                 inrow  += lut->step;
295             }
296             inrow0  += inpic ->linesize[0];
297             outrow0 += outpic->linesize[0];
298         }
299     } else {
300         /* planar */
301         for (plane = 0; plane < 4 && inpic->data[plane]; plane++) {
302             int vsub = plane == 1 || plane == 2 ? lut->vsub : 0;
303             int hsub = plane == 1 || plane == 2 ? lut->hsub : 0;
304
305             inrow  = inpic ->data[plane] + (y>>vsub) * inpic ->linesize[plane];
306             outrow = outpic->data[plane] + (y>>vsub) * outpic->linesize[plane];
307
308             for (i = 0; i < (h + (1<<vsub) - 1)>>vsub; i ++) {
309                 const uint8_t *tab = lut->lut[plane];
310                 int w = (inlink->w + (1<<hsub) - 1)>>hsub;
311                 for (j = 0; j < w; j++)
312                     outrow[j] = tab[inrow[j]];
313                 inrow  += inpic ->linesize[plane];
314                 outrow += outpic->linesize[plane];
315             }
316         }
317     }
318
319     return ff_draw_slice(outlink, y, h, slice_dir);
320 }
321
322 static const AVFilterPad inputs[] = {
323     { .name            = "default",
324       .type            = AVMEDIA_TYPE_VIDEO,
325       .draw_slice      = draw_slice,
326       .config_props    = config_props,
327       .min_perms       = AV_PERM_READ, },
328     { .name = NULL}
329 };
330 static const AVFilterPad outputs[] = {
331     { .name            = "default",
332       .type            = AVMEDIA_TYPE_VIDEO, },
333     { .name = NULL}
334 };
335 #define DEFINE_LUT_FILTER(name_, description_)                          \
336     AVFilter avfilter_vf_##name_ = {                                    \
337         .name          = #name_,                                        \
338         .description   = NULL_IF_CONFIG_SMALL(description_),            \
339         .priv_size     = sizeof(LutContext),                            \
340                                                                         \
341         .init          = name_##_init,                                  \
342         .uninit        = uninit,                                        \
343         .query_formats = query_formats,                                 \
344                                                                         \
345         .inputs        = inputs,                                        \
346         .outputs       = outputs,                                       \
347         .priv_class    = &name_##_class,                                \
348     }
349
350 #if CONFIG_LUT_FILTER
351
352 #define lut_options options
353 AVFILTER_DEFINE_CLASS(lut);
354
355 static int lut_init(AVFilterContext *ctx, const char *args)
356 {
357     LutContext *lut = ctx->priv;
358     int ret;
359
360     lut->class = &lut_class;
361     av_opt_set_defaults(lut);
362
363     if (args && (ret = av_set_options_string(lut, args, "=", ":")) < 0)
364         return ret;
365
366     return 0;
367 }
368
369 DEFINE_LUT_FILTER(lut, "Compute and apply a lookup table to the RGB/YUV input video.");
370 #endif
371
372 #if CONFIG_LUTYUV_FILTER
373
374 #define lutyuv_options options
375 AVFILTER_DEFINE_CLASS(lutyuv);
376
377 static int lutyuv_init(AVFilterContext *ctx, const char *args)
378 {
379     LutContext *lut = ctx->priv;
380     int ret;
381
382     lut->class = &lutyuv_class;
383     lut->is_yuv = 1;
384     av_opt_set_defaults(lut);
385
386     if (args && (ret = av_set_options_string(lut, args, "=", ":")) < 0)
387         return ret;
388
389     return 0;
390 }
391
392 DEFINE_LUT_FILTER(lutyuv, "Compute and apply a lookup table to the YUV input video.");
393 #endif
394
395 #if CONFIG_LUTRGB_FILTER
396
397 #define lutrgb_options options
398 AVFILTER_DEFINE_CLASS(lutrgb);
399
400 static int lutrgb_init(AVFilterContext *ctx, const char *args)
401 {
402     LutContext *lut = ctx->priv;
403     int ret;
404
405     lut->class = &lutrgb_class;
406     lut->is_rgb = 1;
407     av_opt_set_defaults(lut);
408
409     if (args && (ret = av_set_options_string(lut, args, "=", ":")) < 0)
410         return ret;
411
412     return 0;
413 }
414
415 DEFINE_LUT_FILTER(lutrgb, "Compute and apply a lookup table to the RGB input video.");
416 #endif
417
418 #if CONFIG_NEGATE_FILTER
419
420 #define negate_options options
421 AVFILTER_DEFINE_CLASS(negate);
422
423 static int negate_init(AVFilterContext *ctx, const char *args)
424 {
425     LutContext *lut = ctx->priv;
426     char lut_params[64];
427
428     if (args)
429         sscanf(args, "%d", &lut->negate_alpha);
430
431     av_log(ctx, AV_LOG_DEBUG, "negate_alpha:%d\n", lut->negate_alpha);
432
433     snprintf(lut_params, sizeof(lut_params), "c0=negval:c1=negval:c2=negval:a=%s",
434              lut->negate_alpha ? "negval" : "val");
435
436     lut->class = &negate_class;
437     av_opt_set_defaults(lut);
438
439     return av_set_options_string(lut, lut_params, "=", ":");
440 }
441
442 DEFINE_LUT_FILTER(negate, "Negate input video.");
443
444 #endif