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