]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_curves.c
Merge commit 'f160c6a18a574b4c7d063e0a748037cbbd9912ee'
[ffmpeg] / libavfilter / vf_curves.c
1 /*
2  * Copyright (c) 2013 Clément Bœsch
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 #include "libavutil/opt.h"
22 #include "libavutil/eval.h"
23 #include "libavutil/avassert.h"
24 #include "avfilter.h"
25 #include "formats.h"
26 #include "internal.h"
27 #include "video.h"
28
29 struct keypoint {
30     double x, y;
31     struct keypoint *next;
32 };
33
34 #define NB_COMP 3
35
36 enum preset {
37     PRESET_NONE,
38     PRESET_COLOR_NEGATIVE,
39     PRESET_CROSS_PROCESS,
40     PRESET_DARKER,
41     PRESET_INCREASE_CONTRAST,
42     PRESET_LIGHTER,
43     PRESET_LINEAR_CONTRAST,
44     PRESET_MEDIUM_CONTRAST,
45     PRESET_NEGATIVE,
46     PRESET_STRONG_CONTRAST,
47     PRESET_VINTAGE,
48     NB_PRESETS,
49 };
50
51 typedef struct {
52     const AVClass *class;
53     enum preset preset;
54     char *comp_points_str[NB_COMP];
55     char *comp_points_str_all;
56     uint8_t graph[NB_COMP][256];
57 } CurvesContext;
58
59 #define OFFSET(x) offsetof(CurvesContext, x)
60 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
61 static const AVOption curves_options[] = {
62     { "preset", "select a color curves preset", OFFSET(preset), AV_OPT_TYPE_INT, {.i64=PRESET_NONE}, PRESET_NONE, NB_PRESETS-1, FLAGS, "preset_name" },
63         { "none",               NULL, 0, AV_OPT_TYPE_CONST, {.i64=PRESET_NONE},                 INT_MIN, INT_MAX, FLAGS, "preset_name" },
64         { "color_negative",     NULL, 0, AV_OPT_TYPE_CONST, {.i64=PRESET_COLOR_NEGATIVE},       INT_MIN, INT_MAX, FLAGS, "preset_name" },
65         { "cross_process",      NULL, 0, AV_OPT_TYPE_CONST, {.i64=PRESET_CROSS_PROCESS},        INT_MIN, INT_MAX, FLAGS, "preset_name" },
66         { "darker",             NULL, 0, AV_OPT_TYPE_CONST, {.i64=PRESET_DARKER},               INT_MIN, INT_MAX, FLAGS, "preset_name" },
67         { "increase_contrast",  NULL, 0, AV_OPT_TYPE_CONST, {.i64=PRESET_INCREASE_CONTRAST},    INT_MIN, INT_MAX, FLAGS, "preset_name" },
68         { "lighter",            NULL, 0, AV_OPT_TYPE_CONST, {.i64=PRESET_LIGHTER},              INT_MIN, INT_MAX, FLAGS, "preset_name" },
69         { "linear_contrast",    NULL, 0, AV_OPT_TYPE_CONST, {.i64=PRESET_LINEAR_CONTRAST},      INT_MIN, INT_MAX, FLAGS, "preset_name" },
70         { "medium_contrast",    NULL, 0, AV_OPT_TYPE_CONST, {.i64=PRESET_MEDIUM_CONTRAST},      INT_MIN, INT_MAX, FLAGS, "preset_name" },
71         { "negative",           NULL, 0, AV_OPT_TYPE_CONST, {.i64=PRESET_NEGATIVE},             INT_MIN, INT_MAX, FLAGS, "preset_name" },
72         { "strong_contrast",    NULL, 0, AV_OPT_TYPE_CONST, {.i64=PRESET_STRONG_CONTRAST},      INT_MIN, INT_MAX, FLAGS, "preset_name" },
73         { "vintage",            NULL, 0, AV_OPT_TYPE_CONST, {.i64=PRESET_VINTAGE},              INT_MIN, INT_MAX, FLAGS, "preset_name" },
74     { "red",   "set red points coordinates",   OFFSET(comp_points_str[0]), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
75     { "r",     "set red points coordinates",   OFFSET(comp_points_str[0]), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
76     { "green", "set green points coordinates", OFFSET(comp_points_str[1]), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
77     { "g",     "set green points coordinates", OFFSET(comp_points_str[1]), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
78     { "blue",  "set blue points coordinates",  OFFSET(comp_points_str[2]), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
79     { "b",     "set blue points coordinates",  OFFSET(comp_points_str[2]), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
80     { "all",   "set points coordinates for all components", OFFSET(comp_points_str_all), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
81     { NULL }
82 };
83
84 AVFILTER_DEFINE_CLASS(curves);
85
86 static const struct {
87     const char *r;
88     const char *g;
89     const char *b;
90     const char *all;
91 } curves_presets[] = {
92     [PRESET_COLOR_NEGATIVE] = {
93         "0/1 0.129/1 0.466/0.498 0.725/0 1/0",
94         "0/1 0.109/1 0.301/0.498 0.517/0 1/0",
95         "0/1 0.098/1 0.235/0.498 0.423/0 1/0",
96     },
97     [PRESET_CROSS_PROCESS] = {
98         "0.25/0.156 0.501/0.501 0.686/0.745",
99         "0.25/0.188 0.38/0.501 0.745/0.815 1/0.815",
100         "0.231/0.094 0.709/0.874",
101     },
102     [PRESET_DARKER]             = { .all = "0.5/0.4" },
103     [PRESET_INCREASE_CONTRAST]  = { .all = "0.149/0.066 0.831/0.905 0.905/0.98" },
104     [PRESET_LIGHTER]            = { .all = "0.4/0.5" },
105     [PRESET_LINEAR_CONTRAST]    = { .all = "0.305/0.286 0.694/0.713" },
106     [PRESET_MEDIUM_CONTRAST]    = { .all = "0.286/0.219 0.639/0.643" },
107     [PRESET_NEGATIVE]           = { .all = "0/1 1/0" },
108     [PRESET_STRONG_CONTRAST]    = { .all = "0.301/0.196 0.592/0.6 0.686/0.737" },
109     [PRESET_VINTAGE] = {
110         "0/0.11 0.42/0.51 1/0.95",
111         "0.50/0.48",
112         "0/0.22 0.49/0.44 1/0.8",
113     }
114 };
115
116 static struct keypoint *make_point(double x, double y, struct keypoint *next)
117 {
118     struct keypoint *point = av_mallocz(sizeof(*point));
119
120     if (!point)
121         return NULL;
122     point->x = x;
123     point->y = y;
124     point->next = next;
125     return point;
126 }
127
128 static int parse_points_str(AVFilterContext *ctx, struct keypoint **points, const char *s)
129 {
130     char *p = (char *)s; // strtod won't alter the string
131     struct keypoint *last = NULL;
132
133     /* construct a linked list based on the key points string */
134     while (p && *p) {
135         struct keypoint *point = make_point(0, 0, NULL);
136         if (!point)
137             return AVERROR(ENOMEM);
138         point->x = av_strtod(p, &p); if (p && *p) p++;
139         point->y = av_strtod(p, &p); if (p && *p) p++;
140         if (point->x < 0 || point->x > 1 || point->y < 0 || point->y > 1) {
141             av_log(ctx, AV_LOG_ERROR, "Invalid key point coordinates (%f;%f), "
142                    "x and y must be in the [0;1] range.\n", point->x, point->y);
143             return AVERROR(EINVAL);
144         }
145         if (!*points)
146             *points = point;
147         if (last) {
148             if ((int)(last->x * 255) >= (int)(point->x * 255)) {
149                 av_log(ctx, AV_LOG_ERROR, "Key point coordinates (%f;%f) "
150                        "and (%f;%f) are too close from each other or not "
151                        "strictly increasing on the x-axis\n",
152                        last->x, last->y, point->x, point->y);
153                 return AVERROR(EINVAL);
154             }
155             last->next = point;
156         }
157         last = point;
158     }
159
160     /* auto insert first key point if missing at x=0 */
161     if (!*points) {
162         last = make_point(0, 0, NULL);
163         if (!last)
164             return AVERROR(ENOMEM);
165         last->x = last->y = 0;
166         *points = last;
167     } else if ((*points)->x != 0.) {
168         struct keypoint *newfirst = make_point(0, 0, *points);
169         if (!newfirst)
170             return AVERROR(ENOMEM);
171         *points = newfirst;
172     }
173
174     av_assert0(last);
175
176     /* auto insert last key point if missing at x=1 */
177     if (last->x != 1.) {
178         struct keypoint *point = make_point(1, 1, NULL);
179         if (!point)
180             return AVERROR(ENOMEM);
181         last->next = point;
182     }
183
184     return 0;
185 }
186
187 static int get_nb_points(const struct keypoint *d)
188 {
189     int n = 0;
190     while (d) {
191         n++;
192         d = d->next;
193     }
194     return n;
195 }
196
197 /**
198  * Natural cubic spline interpolation
199  * Finding curves using Cubic Splines notes by Steven Rauch and John Stockie.
200  * @see http://people.math.sfu.ca/~stockie/teaching/macm316/notes/splines.pdf
201  */
202 static int interpolate(AVFilterContext *ctx, uint8_t *y, const struct keypoint *points)
203 {
204     int i, ret = 0;
205     const struct keypoint *point;
206     double xprev = 0;
207
208     int n = get_nb_points(points); // number of splines
209
210     double (*matrix)[3] = av_calloc(n, sizeof(*matrix));
211     double *h = av_malloc((n - 1) * sizeof(*h));
212     double *r = av_calloc(n, sizeof(*r));
213
214     if (!matrix || !h || !r) {
215         ret = AVERROR(ENOMEM);
216         goto end;
217     }
218
219     /* h(i) = x(i+1) - x(i) */
220     i = -1;
221     for (point = points; point; point = point->next) {
222         if (i != -1)
223             h[i] = point->x - xprev;
224         xprev = point->x;
225         i++;
226     }
227
228     /* right-side of the polynomials, will be modified to contains the solution */
229     point = points;
230     for (i = 1; i < n - 1; i++) {
231         double yp = point->y,
232                yc = point->next->y,
233                yn = point->next->next->y;
234         r[i] = 6 * ((yn-yc)/h[i] - (yc-yp)/h[i-1]);
235         point = point->next;
236     }
237
238 #define B 0 /* sub  diagonal (below main) */
239 #define M 1 /* main diagonal (center) */
240 #define A 2 /* sup  diagonal (above main) */
241
242     /* left side of the polynomials into a tridiagonal matrix. */
243     matrix[0][M] = matrix[n - 1][M] = 1;
244     for (i = 1; i < n - 1; i++) {
245         matrix[i][B] = h[i-1];
246         matrix[i][M] = 2 * (h[i-1] + h[i]);
247         matrix[i][A] = h[i];
248     }
249
250     /* tridiagonal solving of the linear system */
251     for (i = 1; i < n; i++) {
252         double den = matrix[i][M] - matrix[i][B] * matrix[i-1][A];
253         double k = den ? 1./den : 1.;
254         matrix[i][A] *= k;
255         r[i] = (r[i] - matrix[i][B] * r[i - 1]) * k;
256     }
257     for (i = n - 2; i >= 0; i--)
258         r[i] = r[i] - matrix[i][A] * r[i + 1];
259
260     /* compute the graph with x=[0..255] */
261     i = 0;
262     point = points;
263     av_assert0(point->next); // always at least 2 key points
264     while (point->next) {
265         double yc = point->y;
266         double yn = point->next->y;
267
268         double a = yc;
269         double b = (yn-yc)/h[i] - h[i]*r[i]/2. - h[i]*(r[i+1]-r[i])/6.;
270         double c = r[i] / 2.;
271         double d = (r[i+1] - r[i]) / (6.*h[i]);
272
273         int x;
274         int x_start = point->x       * 255;
275         int x_end   = point->next->x * 255;
276
277         av_assert0(x_start >= 0 && x_start <= 255 &&
278                    x_end   >= 0 && x_end   <= 255);
279
280         for (x = x_start; x <= x_end; x++) {
281             double xx = (x - x_start) * 1/255.;
282             double yy = a + b*xx + c*xx*xx + d*xx*xx*xx;
283             y[x] = av_clipf(yy, 0, 1) * 255;
284             av_log(ctx, AV_LOG_DEBUG, "f(%f)=%f -> y[%d]=%d\n", xx, yy, x, y[x]);
285         }
286
287         point = point->next;
288         i++;
289     }
290
291 end:
292     av_free(matrix);
293     av_free(h);
294     av_free(r);
295     return ret;
296 }
297
298 static av_cold int init(AVFilterContext *ctx)
299 {
300     int i, j, ret;
301     CurvesContext *curves = ctx->priv;
302     struct keypoint *comp_points[NB_COMP] = {0};
303     char **pts = curves->comp_points_str;
304     const char *allp = curves->comp_points_str_all;
305
306     if (!allp && curves->preset != PRESET_NONE && curves_presets[curves->preset].all)
307         allp = curves_presets[curves->preset].all;
308
309     if (allp) {
310         for (i = 0; i < NB_COMP; i++) {
311             if (!pts[i])
312                 pts[i] = av_strdup(allp);
313             if (!pts[i])
314                 return AVERROR(ENOMEM);
315         }
316     }
317
318     if (curves->preset != PRESET_NONE) {
319         if (!pts[0]) pts[0] = av_strdup(curves_presets[curves->preset].r);
320         if (!pts[1]) pts[1] = av_strdup(curves_presets[curves->preset].g);
321         if (!pts[2]) pts[2] = av_strdup(curves_presets[curves->preset].b);
322         if (!pts[0] || !pts[1] || !pts[2])
323             return AVERROR(ENOMEM);
324     }
325
326     for (i = 0; i < NB_COMP; i++) {
327         ret = parse_points_str(ctx, comp_points + i, curves->comp_points_str[i]);
328         if (ret < 0)
329             return ret;
330         ret = interpolate(ctx, curves->graph[i], comp_points[i]);
331         if (ret < 0)
332             return ret;
333     }
334
335     if (av_log_get_level() >= AV_LOG_VERBOSE) {
336         for (i = 0; i < NB_COMP; i++) {
337             struct keypoint *point = comp_points[i];
338             av_log(ctx, AV_LOG_VERBOSE, "#%d points:", i);
339             while (point) {
340                 av_log(ctx, AV_LOG_VERBOSE, " (%f;%f)", point->x, point->y);
341                 point = point->next;
342             }
343             av_log(ctx, AV_LOG_VERBOSE, "\n");
344             av_log(ctx, AV_LOG_VERBOSE, "#%d values:", i);
345             for (j = 0; j < 256; j++)
346                 av_log(ctx, AV_LOG_VERBOSE, " %02X", curves->graph[i][j]);
347             av_log(ctx, AV_LOG_VERBOSE, "\n");
348         }
349     }
350
351     for (i = 0; i < NB_COMP; i++) {
352         struct keypoint *point = comp_points[i];
353         while (point) {
354             struct keypoint *next = point->next;
355             av_free(point);
356             point = next;
357         }
358     }
359
360     return 0;
361 }
362
363 static int query_formats(AVFilterContext *ctx)
364 {
365     static const enum AVPixelFormat pix_fmts[] = {AV_PIX_FMT_RGB24, AV_PIX_FMT_NONE};
366     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
367     return 0;
368 }
369
370 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
371 {
372     int x, y, i, direct = 0;
373     AVFilterContext *ctx = inlink->dst;
374     CurvesContext *curves = ctx->priv;
375     AVFilterLink *outlink = inlink->dst->outputs[0];
376     AVFrame *out;
377     uint8_t *dst;
378     const uint8_t *src;
379
380     if (av_frame_is_writable(in)) {
381         direct = 1;
382         out = in;
383     } else {
384         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
385         if (!out) {
386             av_frame_free(&in);
387             return AVERROR(ENOMEM);
388         }
389         av_frame_copy_props(out, in);
390     }
391
392     dst = out->data[0];
393     src = in ->data[0];
394
395     for (y = 0; y < inlink->h; y++) {
396         uint8_t *dstp = dst;
397         const uint8_t *srcp = src;
398
399         for (x = 0; x < inlink->w; x++)
400             for (i = 0; i < NB_COMP; i++, dstp++, srcp++)
401                 *dstp = curves->graph[i][*srcp];
402         dst += out->linesize[0];
403         src += in ->linesize[0];
404     }
405
406     if (!direct)
407         av_frame_free(&in);
408
409     return ff_filter_frame(outlink, out);
410 }
411
412 static const AVFilterPad curves_inputs[] = {
413     {
414         .name         = "default",
415         .type         = AVMEDIA_TYPE_VIDEO,
416         .filter_frame = filter_frame,
417     },
418     { NULL }
419 };
420
421 static const AVFilterPad curves_outputs[] = {
422      {
423          .name = "default",
424          .type = AVMEDIA_TYPE_VIDEO,
425      },
426      { NULL }
427 };
428
429 AVFilter avfilter_vf_curves = {
430     .name          = "curves",
431     .description   = NULL_IF_CONFIG_SMALL("Adjust components curves."),
432     .priv_size     = sizeof(CurvesContext),
433     .init          = init,
434     .query_formats = query_formats,
435     .inputs        = curves_inputs,
436     .outputs       = curves_outputs,
437     .priv_class    = &curves_class,
438 };