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