Browse code

lavfi: add curves filter.

Clément Bœsch authored on 2013/03/05 00:06:14
Showing 6 changed files
... ...
@@ -2,6 +2,10 @@ Entries are sorted chronologically from oldest to youngest within each release,
2 2
 releases are sorted from youngest to oldest.
3 3
 
4 4
 version <next>:
5
+- curves filter
6
+
7
+
8
+version 1.2:
5 9
 
6 10
 - VDPAU hardware acceleration through normal hwaccel
7 11
 - SRTP support
... ...
@@ -2217,6 +2217,73 @@ indicates never reset and return the largest area encountered during
2217 2217
 playback.
2218 2218
 @end table
2219 2219
 
2220
+@section curves
2221
+
2222
+Apply color adjustments using curves.
2223
+
2224
+This filter is similar to the Adobe Photoshop and GIMP curves tools. Each
2225
+component (red, green and blue) has its values defined by @var{N} key points
2226
+tied from each other using a smooth curve. The x-axis represents the pixel
2227
+values from the input frame, and the y-axis the new pixel values to be set for
2228
+the output frame.
2229
+
2230
+By default, a component curve is defined by the two points @var{(0;0)} and
2231
+@var{(1;1)}. This creates a straight line where each original pixel value is
2232
+"adjusted" to its own value, which means no change to the image.
2233
+
2234
+The filter allows you to redefine these two points and add some more. A new
2235
+curve (using a natural cubic spline interpolation) will be define to pass
2236
+smoothly through all these new coordinates. The new defined points needs to be
2237
+strictly increasing over the x-axis, and their @var{x} and @var{y} values must
2238
+be in the @var{[0;1]} interval.  If the computed curves happened to go outside
2239
+the vector spaces, the values will be clipped accordingly.
2240
+
2241
+If there is no key point defined in @code{x=0}, the filter will automatically
2242
+insert a @var{(0;0)} point. In the same way, if there is no key point defined
2243
+in @code{x=1}, the filter will automatically insert a @var{(1;1)} point.
2244
+
2245
+The filter accepts parameters as a list of @var{key}=@var{value} pairs,
2246
+separated by ":".
2247
+
2248
+A description of the accepted parameters follows.
2249
+
2250
+@table @option
2251
+@item red, r
2252
+Set the key points for the red component.
2253
+@item green, g
2254
+Set the key points for the green component.
2255
+@item blue, b
2256
+Set the key points for the blue component.
2257
+@end table
2258
+
2259
+To avoid some filtergraph syntax conflicts, each key points list need to be
2260
+defined using the following syntax: @code{x0/y0 x1/y1 x2/y2 ...}.
2261
+
2262
+@subsection Examples
2263
+
2264
+@itemize
2265
+@item
2266
+Increase slightly the middle level of blue:
2267
+@example
2268
+curves=blue='0.5/0.58'
2269
+@end example
2270
+
2271
+@item
2272
+Vintage effect:
2273
+@example
2274
+curves=r='0/0.11 .42/.51 1/0.95':g='0.50/0.48':b='0/0.22 .49/.44 1/0.8'
2275
+@end example
2276
+Here we obtain the following coordinates for each components:
2277
+@table @var
2278
+@item red
2279
+@code{(0;0.11) (0.42;0.51) (1;0.95)}
2280
+@item green
2281
+@code{(0;0) (0.50;0.48) (1;1)}
2282
+@item blue
2283
+@code{(0;0.22) (0.49;0.44) (1;0.80)}
2284
+@end table
2285
+@end itemize
2286
+
2220 2287
 @section decimate
2221 2288
 
2222 2289
 Drop frames that do not differ greatly from the previous frame in
... ...
@@ -104,6 +104,7 @@ OBJS-$(CONFIG_COLORMATRIX_FILTER)            += vf_colormatrix.o
104 104
 OBJS-$(CONFIG_COPY_FILTER)                   += vf_copy.o
105 105
 OBJS-$(CONFIG_CROP_FILTER)                   += vf_crop.o
106 106
 OBJS-$(CONFIG_CROPDETECT_FILTER)             += vf_cropdetect.o
107
+OBJS-$(CONFIG_CURVES_FILTER)                 += vf_curves.o
107 108
 OBJS-$(CONFIG_DECIMATE_FILTER)               += vf_decimate.o
108 109
 OBJS-$(CONFIG_DELOGO_FILTER)                 += vf_delogo.o
109 110
 OBJS-$(CONFIG_DESHAKE_FILTER)                += vf_deshake.o
... ...
@@ -100,6 +100,7 @@ void avfilter_register_all(void)
100 100
     REGISTER_FILTER(COPY,           copy,           vf);
101 101
     REGISTER_FILTER(CROP,           crop,           vf);
102 102
     REGISTER_FILTER(CROPDETECT,     cropdetect,     vf);
103
+    REGISTER_FILTER(CURVES,         curves,         vf);
103 104
     REGISTER_FILTER(DECIMATE,       decimate,       vf);
104 105
     REGISTER_FILTER(DELOGO,         delogo,         vf);
105 106
     REGISTER_FILTER(DESHAKE,        deshake,        vf);
... ...
@@ -29,7 +29,7 @@
29 29
 #include "libavutil/avutil.h"
30 30
 
31 31
 #define LIBAVFILTER_VERSION_MAJOR  3
32
-#define LIBAVFILTER_VERSION_MINOR  43
32
+#define LIBAVFILTER_VERSION_MINOR  44
33 33
 #define LIBAVFILTER_VERSION_MICRO 100
34 34
 
35 35
 #define LIBAVFILTER_VERSION_INT AV_VERSION_INT(LIBAVFILTER_VERSION_MAJOR, \
36 36
new file mode 100644
... ...
@@ -0,0 +1,363 @@
0
+/*
1
+ * Copyright (c) 2013 Clément Bœsch
2
+ *
3
+ * This file is part of FFmpeg.
4
+ *
5
+ * FFmpeg is free software; you can redistribute it and/or
6
+ * modify it under the terms of the GNU Lesser General Public
7
+ * License as published by the Free Software Foundation; either
8
+ * version 2.1 of the License, or (at your option) any later version.
9
+ *
10
+ * FFmpeg is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
+ * Lesser General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU Lesser General Public
16
+ * License along with FFmpeg; if not, write to the Free Software
17
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
+ */
19
+
20
+#include "libavutil/opt.h"
21
+#include "libavutil/eval.h"
22
+#include "libavutil/avassert.h"
23
+#include "avfilter.h"
24
+#include "formats.h"
25
+#include "internal.h"
26
+#include "video.h"
27
+
28
+struct keypoint {
29
+    double x, y;
30
+    struct keypoint *next;
31
+};
32
+
33
+#define NB_COMP 3
34
+
35
+typedef struct {
36
+    const AVClass *class;
37
+    char *comp_points_str[NB_COMP];
38
+    uint8_t graph[NB_COMP][256];
39
+} CurvesContext;
40
+
41
+#define OFFSET(x) offsetof(CurvesContext, x)
42
+#define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
43
+static const AVOption curves_options[] = {
44
+    { "red",   "set red points coordinates",   OFFSET(comp_points_str[0]), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
45
+    { "r",     "set red points coordinates",   OFFSET(comp_points_str[0]), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
46
+    { "green", "set green points coordinates", OFFSET(comp_points_str[1]), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
47
+    { "g",     "set green points coordinates", OFFSET(comp_points_str[1]), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
48
+    { "blue",  "set blue points coordinates",  OFFSET(comp_points_str[2]), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
49
+    { "b",     "set blue points coordinates",  OFFSET(comp_points_str[2]), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
50
+    { NULL }
51
+};
52
+
53
+AVFILTER_DEFINE_CLASS(curves);
54
+
55
+static struct keypoint *make_point(double x, double y, struct keypoint *next)
56
+{
57
+    struct keypoint *point = av_mallocz(sizeof(*point));
58
+
59
+    if (!point)
60
+        return NULL;
61
+    point->x = x;
62
+    point->y = y;
63
+    point->next = next;
64
+    return point;
65
+}
66
+
67
+static int parse_points_str(AVFilterContext *ctx, struct keypoint **points, const char *s)
68
+{
69
+    char *p = (char *)s; // strtod won't alter the string
70
+    struct keypoint *last = NULL;
71
+
72
+    /* construct a linked list based on the key points string */
73
+    while (p && *p) {
74
+        struct keypoint *point = make_point(0, 0, NULL);
75
+        if (!point)
76
+            return AVERROR(ENOMEM);
77
+        point->x = av_strtod(p, &p); if (p && *p) p++;
78
+        point->y = av_strtod(p, &p); if (p && *p) p++;
79
+        if (point->x < 0 || point->x > 1 || point->y < 0 || point->y > 1) {
80
+            av_log(ctx, AV_LOG_ERROR, "Invalid key point coordinates (%f;%f), "
81
+                   "x and y must be in the [0;1] range.\n", point->x, point->y);
82
+            return AVERROR(EINVAL);
83
+        }
84
+        if (!*points)
85
+            *points = point;
86
+        if (last) {
87
+            if ((int)(last->x * 255) >= (int)(point->x * 255)) {
88
+                av_log(ctx, AV_LOG_ERROR, "Key point coordinates (%f;%f) "
89
+                       "and (%f;%f) are too close from each other or not "
90
+                       "strictly increasing on the x-axis\n",
91
+                       last->x, last->y, point->x, point->y);
92
+                return AVERROR(EINVAL);
93
+            }
94
+            last->next = point;
95
+        }
96
+        last = point;
97
+    }
98
+
99
+    /* auto insert first key point if missing at x=0 */
100
+    if (!*points) {
101
+        last = make_point(0, 0, NULL);
102
+        if (!last)
103
+            return AVERROR(ENOMEM);
104
+        last->x = last->y = 0;
105
+        *points = last;
106
+    } else if ((*points)->x != 0.) {
107
+        struct keypoint *newfirst = make_point(0, 0, *points);
108
+        if (!newfirst)
109
+            return AVERROR(ENOMEM);
110
+        *points = newfirst;
111
+    }
112
+
113
+    av_assert0(last);
114
+
115
+    /* auto insert last key point if missing at x=1 */
116
+    if (last->x != 1.) {
117
+        struct keypoint *point = make_point(1, 1, NULL);
118
+        if (!point)
119
+            return AVERROR(ENOMEM);
120
+        last->next = point;
121
+    }
122
+
123
+    return 0;
124
+}
125
+
126
+static int get_nb_points(const struct keypoint *d)
127
+{
128
+    int n = 0;
129
+    while (d) {
130
+        n++;
131
+        d = d->next;
132
+    }
133
+    return n;
134
+}
135
+
136
+/**
137
+ * Natural cubic spline interpolation
138
+ * Finding curves using Cubic Splines notes by Steven Rauch and John Stockie.
139
+ * @see http://people.math.sfu.ca/~stockie/teaching/macm316/notes/splines.pdf
140
+ */
141
+static int interpolate(AVFilterContext *ctx, uint8_t *y, const struct keypoint *points)
142
+{
143
+    int i, ret = 0;
144
+    const struct keypoint *point;
145
+    double xprev = 0;
146
+
147
+    int n = get_nb_points(points); // number of splines
148
+
149
+    double (*matrix)[3] = av_calloc(n, sizeof(*matrix));
150
+    double *h = av_malloc((n - 1) * sizeof(*h));
151
+    double *r = av_calloc(n, sizeof(*r));
152
+
153
+    if (!matrix || !h || !r) {
154
+        ret = AVERROR(ENOMEM);
155
+        goto end;
156
+    }
157
+
158
+    /* h(i) = x(i+1) - x(i) */
159
+    i = -1;
160
+    for (point = points; point; point = point->next) {
161
+        if (i != -1)
162
+            h[i] = point->x - xprev;
163
+        xprev = point->x;
164
+        i++;
165
+    }
166
+
167
+    /* right-side of the polynomials, will be modified to contains the solution */
168
+    point = points;
169
+    for (i = 1; i < n - 1; i++) {
170
+        double yp = point->y,
171
+               yc = point->next->y,
172
+               yn = point->next->next->y;
173
+        r[i] = 6 * ((yn-yc)/h[i] - (yc-yp)/h[i-1]);
174
+        point = point->next;
175
+    }
176
+
177
+#define B 0 /* sub  diagonal (below main) */
178
+#define M 1 /* main diagonal (center) */
179
+#define A 2 /* sup  diagonal (above main) */
180
+
181
+    /* left side of the polynomials into a tridiagonal matrix. */
182
+    matrix[0][M] = matrix[n - 1][M] = 1;
183
+    for (i = 1; i < n - 1; i++) {
184
+        matrix[i][B] = h[i-1];
185
+        matrix[i][M] = 2 * (h[i-1] + h[i]);
186
+        matrix[i][A] = h[i];
187
+    }
188
+
189
+    /* tridiagonal solving of the linear system */
190
+    for (i = 1; i < n; i++) {
191
+        double den = matrix[i][M] - matrix[i][B] * matrix[i-1][A];
192
+        double k = den ? 1./den : 1.;
193
+        matrix[i][A] *= k;
194
+        r[i] = (r[i] - matrix[i][B] * r[i - 1]) * k;
195
+    }
196
+    for (i = n - 2; i >= 0; i--)
197
+        r[i] = r[i] - matrix[i][A] * r[i + 1];
198
+
199
+    /* compute the graph with x=[0..255] */
200
+    i = 0;
201
+    point = points;
202
+    av_assert0(point->next); // always at least 2 key points
203
+    while (point->next) {
204
+        double yc = point->y;
205
+        double yn = point->next->y;
206
+
207
+        double a = yc;
208
+        double b = (yn-yc)/h[i] - h[i]*r[i]/2. - h[i]*(r[i+1]-r[i])/6.;
209
+        double c = r[i] / 2.;
210
+        double d = (r[i+1] - r[i]) / (6.*h[i]);
211
+
212
+        int x;
213
+        int x_start = point->x       * 255;
214
+        int x_end   = point->next->x * 255;
215
+
216
+        av_assert0(x_start >= 0 && x_start <= 255 &&
217
+                   x_end   >= 0 && x_end   <= 255);
218
+
219
+        for (x = x_start; x <= x_end; x++) {
220
+            double xx = (x - x_start) * 1/255.;
221
+            double yy = a + b*xx + c*xx*xx + d*xx*xx*xx;
222
+            y[x] = av_clipf(yy, 0, 1) * 255;
223
+            av_log(ctx, AV_LOG_DEBUG, "f(%f)=%f -> y[%d]=%d\n", xx, yy, x, y[x]);
224
+        }
225
+
226
+        point = point->next;
227
+        i++;
228
+    }
229
+
230
+end:
231
+    av_free(matrix);
232
+    av_free(h);
233
+    av_free(r);
234
+    return ret;
235
+}
236
+
237
+static av_cold int init(AVFilterContext *ctx, const char *args)
238
+{
239
+    int i, j, ret;
240
+    CurvesContext *curves = ctx->priv;
241
+    struct keypoint *comp_points[NB_COMP] = {0};
242
+
243
+    curves->class = &curves_class;
244
+    av_opt_set_defaults(curves);
245
+
246
+    if ((ret = av_set_options_string(curves, args, "=", ":")) < 0)
247
+        return ret;
248
+
249
+    for (i = 0; i < NB_COMP; i++) {
250
+        ret = parse_points_str(ctx, comp_points + i, curves->comp_points_str[i]);
251
+        if (ret < 0)
252
+            return ret;
253
+        ret = interpolate(ctx, curves->graph[i], comp_points[i]);
254
+        if (ret < 0)
255
+            return ret;
256
+    }
257
+
258
+    if (av_log_get_level() >= AV_LOG_VERBOSE) {
259
+        for (i = 0; i < NB_COMP; i++) {
260
+            struct keypoint *point = comp_points[i];
261
+            av_log(ctx, AV_LOG_VERBOSE, "#%d points:", i);
262
+            while (point) {
263
+                av_log(ctx, AV_LOG_VERBOSE, " (%f;%f)", point->x, point->y);
264
+                point = point->next;
265
+            }
266
+            av_log(ctx, AV_LOG_VERBOSE, "\n");
267
+            av_log(ctx, AV_LOG_VERBOSE, "#%d values:", i);
268
+            for (j = 0; j < 256; j++)
269
+                av_log(ctx, AV_LOG_VERBOSE, " %02X", curves->graph[i][j]);
270
+            av_log(ctx, AV_LOG_VERBOSE, "\n");
271
+        }
272
+    }
273
+
274
+    for (i = 0; i < NB_COMP; i++) {
275
+        struct keypoint *point = comp_points[i];
276
+        while (point) {
277
+            struct keypoint *next = point->next;
278
+            av_free(point);
279
+            point = next;
280
+        }
281
+    }
282
+
283
+    av_opt_free(curves);
284
+    return 0;
285
+}
286
+
287
+static int query_formats(AVFilterContext *ctx)
288
+{
289
+    static const enum AVPixelFormat pix_fmts[] = {AV_PIX_FMT_RGB24, AV_PIX_FMT_NONE};
290
+    ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
291
+    return 0;
292
+}
293
+
294
+static int filter_frame(AVFilterLink *inlink, AVFrame *in)
295
+{
296
+    int x, y, i, direct = 0;
297
+    AVFilterContext *ctx = inlink->dst;
298
+    CurvesContext *curves = ctx->priv;
299
+    AVFilterLink *outlink = inlink->dst->outputs[0];
300
+    AVFrame *out;
301
+    uint8_t *dst;
302
+    const uint8_t *src;
303
+
304
+    if (av_frame_is_writable(in)) {
305
+        direct = 1;
306
+        out = in;
307
+    } else {
308
+        out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
309
+        if (!out) {
310
+            av_frame_free(&in);
311
+            return AVERROR(ENOMEM);
312
+        }
313
+        av_frame_copy_props(out, in);
314
+    }
315
+
316
+    dst = out->data[0];
317
+    src = in ->data[0];
318
+
319
+    for (y = 0; y < inlink->h; y++) {
320
+        uint8_t *dstp = dst;
321
+        const uint8_t *srcp = src;
322
+
323
+        for (x = 0; x < inlink->w; x++)
324
+            for (i = 0; i < NB_COMP; i++, dstp++, srcp++)
325
+                *dstp = curves->graph[i][*srcp];
326
+        dst += out->linesize[0];
327
+        src += in ->linesize[0];
328
+    }
329
+
330
+    if (!direct)
331
+        av_frame_free(&in);
332
+
333
+    return ff_filter_frame(outlink, out);
334
+}
335
+
336
+static const AVFilterPad curves_inputs[] = {
337
+    {
338
+        .name         = "default",
339
+        .type         = AVMEDIA_TYPE_VIDEO,
340
+        .filter_frame = filter_frame,
341
+    },
342
+    { NULL }
343
+};
344
+
345
+static const AVFilterPad curves_outputs[] = {
346
+     {
347
+         .name = "default",
348
+         .type = AVMEDIA_TYPE_VIDEO,
349
+     },
350
+     { NULL }
351
+};
352
+
353
+AVFilter avfilter_vf_curves = {
354
+    .name          = "curves",
355
+    .description   = NULL_IF_CONFIG_SMALL("Adjust components curves."),
356
+    .priv_size     = sizeof(CurvesContext),
357
+    .init          = init,
358
+    .query_formats = query_formats,
359
+    .inputs        = curves_inputs,
360
+    .outputs       = curves_outputs,
361
+    .priv_class    = &curves_class,
362
+};