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