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