]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_lut3d.c
Merge commit 'c8bca9fe466f810fd484e2c6db7ef7bc83b5a943'
[ffmpeg] / libavfilter / vf_lut3d.c
1 /*
2  * Copyright (c) 2013 Clément Bœsch
3  * Copyright (c) 2018 Paul B Mahol
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * 3D Lookup table filter
25  */
26
27 #include "libavutil/opt.h"
28 #include "libavutil/file.h"
29 #include "libavutil/intreadwrite.h"
30 #include "libavutil/avassert.h"
31 #include "libavutil/pixdesc.h"
32 #include "libavutil/avstring.h"
33 #include "avfilter.h"
34 #include "drawutils.h"
35 #include "formats.h"
36 #include "framesync.h"
37 #include "internal.h"
38 #include "video.h"
39
40 #define R 0
41 #define G 1
42 #define B 2
43 #define A 3
44
45 enum interp_mode {
46     INTERPOLATE_NEAREST,
47     INTERPOLATE_TRILINEAR,
48     INTERPOLATE_TETRAHEDRAL,
49     NB_INTERP_MODE
50 };
51
52 struct rgbvec {
53     float r, g, b;
54 };
55
56 /* 3D LUT don't often go up to level 32, but it is common to have a Hald CLUT
57  * of 512x512 (64x64x64) */
58 #define MAX_LEVEL 64
59
60 typedef struct LUT3DContext {
61     const AVClass *class;
62     int interpolation;          ///<interp_mode
63     char *file;
64     uint8_t rgba_map[4];
65     int step;
66     avfilter_action_func *interp;
67     struct rgbvec lut[MAX_LEVEL][MAX_LEVEL][MAX_LEVEL];
68     int lutsize;
69 #if CONFIG_HALDCLUT_FILTER
70     uint8_t clut_rgba_map[4];
71     int clut_step;
72     int clut_bits;
73     int clut_planar;
74     int clut_width;
75     FFFrameSync fs;
76 #endif
77 } LUT3DContext;
78
79 typedef struct ThreadData {
80     AVFrame *in, *out;
81 } ThreadData;
82
83 #define OFFSET(x) offsetof(LUT3DContext, x)
84 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
85 #define COMMON_OPTIONS \
86     { "interp", "select interpolation mode", OFFSET(interpolation), AV_OPT_TYPE_INT, {.i64=INTERPOLATE_TETRAHEDRAL}, 0, NB_INTERP_MODE-1, FLAGS, "interp_mode" }, \
87         { "nearest",     "use values from the nearest defined points",            0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_NEAREST},     INT_MIN, INT_MAX, FLAGS, "interp_mode" }, \
88         { "trilinear",   "interpolate values using the 8 points defining a cube", 0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_TRILINEAR},   INT_MIN, INT_MAX, FLAGS, "interp_mode" }, \
89         { "tetrahedral", "interpolate values using a tetrahedron",                0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_TETRAHEDRAL}, INT_MIN, INT_MAX, FLAGS, "interp_mode" }, \
90     { NULL }
91
92 static inline float lerpf(float v0, float v1, float f)
93 {
94     return v0 + (v1 - v0) * f;
95 }
96
97 static inline struct rgbvec lerp(const struct rgbvec *v0, const struct rgbvec *v1, float f)
98 {
99     struct rgbvec v = {
100         lerpf(v0->r, v1->r, f), lerpf(v0->g, v1->g, f), lerpf(v0->b, v1->b, f)
101     };
102     return v;
103 }
104
105 #define NEAR(x) ((int)((x) + .5))
106 #define PREV(x) ((int)(x))
107 #define NEXT(x) (FFMIN((int)(x) + 1, lut3d->lutsize - 1))
108
109 /**
110  * Get the nearest defined point
111  */
112 static inline struct rgbvec interp_nearest(const LUT3DContext *lut3d,
113                                            const struct rgbvec *s)
114 {
115     return lut3d->lut[NEAR(s->r)][NEAR(s->g)][NEAR(s->b)];
116 }
117
118 /**
119  * Interpolate using the 8 vertices of a cube
120  * @see https://en.wikipedia.org/wiki/Trilinear_interpolation
121  */
122 static inline struct rgbvec interp_trilinear(const LUT3DContext *lut3d,
123                                              const struct rgbvec *s)
124 {
125     const int prev[] = {PREV(s->r), PREV(s->g), PREV(s->b)};
126     const int next[] = {NEXT(s->r), NEXT(s->g), NEXT(s->b)};
127     const struct rgbvec d = {s->r - prev[0], s->g - prev[1], s->b - prev[2]};
128     const struct rgbvec c000 = lut3d->lut[prev[0]][prev[1]][prev[2]];
129     const struct rgbvec c001 = lut3d->lut[prev[0]][prev[1]][next[2]];
130     const struct rgbvec c010 = lut3d->lut[prev[0]][next[1]][prev[2]];
131     const struct rgbvec c011 = lut3d->lut[prev[0]][next[1]][next[2]];
132     const struct rgbvec c100 = lut3d->lut[next[0]][prev[1]][prev[2]];
133     const struct rgbvec c101 = lut3d->lut[next[0]][prev[1]][next[2]];
134     const struct rgbvec c110 = lut3d->lut[next[0]][next[1]][prev[2]];
135     const struct rgbvec c111 = lut3d->lut[next[0]][next[1]][next[2]];
136     const struct rgbvec c00  = lerp(&c000, &c100, d.r);
137     const struct rgbvec c10  = lerp(&c010, &c110, d.r);
138     const struct rgbvec c01  = lerp(&c001, &c101, d.r);
139     const struct rgbvec c11  = lerp(&c011, &c111, d.r);
140     const struct rgbvec c0   = lerp(&c00,  &c10,  d.g);
141     const struct rgbvec c1   = lerp(&c01,  &c11,  d.g);
142     const struct rgbvec c    = lerp(&c0,   &c1,   d.b);
143     return c;
144 }
145
146 /**
147  * Tetrahedral interpolation. Based on code found in Truelight Software Library paper.
148  * @see http://www.filmlight.ltd.uk/pdf/whitepapers/FL-TL-TN-0057-SoftwareLib.pdf
149  */
150 static inline struct rgbvec interp_tetrahedral(const LUT3DContext *lut3d,
151                                                const struct rgbvec *s)
152 {
153     const int prev[] = {PREV(s->r), PREV(s->g), PREV(s->b)};
154     const int next[] = {NEXT(s->r), NEXT(s->g), NEXT(s->b)};
155     const struct rgbvec d = {s->r - prev[0], s->g - prev[1], s->b - prev[2]};
156     const struct rgbvec c000 = lut3d->lut[prev[0]][prev[1]][prev[2]];
157     const struct rgbvec c111 = lut3d->lut[next[0]][next[1]][next[2]];
158     struct rgbvec c;
159     if (d.r > d.g) {
160         if (d.g > d.b) {
161             const struct rgbvec c100 = lut3d->lut[next[0]][prev[1]][prev[2]];
162             const struct rgbvec c110 = lut3d->lut[next[0]][next[1]][prev[2]];
163             c.r = (1-d.r) * c000.r + (d.r-d.g) * c100.r + (d.g-d.b) * c110.r + (d.b) * c111.r;
164             c.g = (1-d.r) * c000.g + (d.r-d.g) * c100.g + (d.g-d.b) * c110.g + (d.b) * c111.g;
165             c.b = (1-d.r) * c000.b + (d.r-d.g) * c100.b + (d.g-d.b) * c110.b + (d.b) * c111.b;
166         } else if (d.r > d.b) {
167             const struct rgbvec c100 = lut3d->lut[next[0]][prev[1]][prev[2]];
168             const struct rgbvec c101 = lut3d->lut[next[0]][prev[1]][next[2]];
169             c.r = (1-d.r) * c000.r + (d.r-d.b) * c100.r + (d.b-d.g) * c101.r + (d.g) * c111.r;
170             c.g = (1-d.r) * c000.g + (d.r-d.b) * c100.g + (d.b-d.g) * c101.g + (d.g) * c111.g;
171             c.b = (1-d.r) * c000.b + (d.r-d.b) * c100.b + (d.b-d.g) * c101.b + (d.g) * c111.b;
172         } else {
173             const struct rgbvec c001 = lut3d->lut[prev[0]][prev[1]][next[2]];
174             const struct rgbvec c101 = lut3d->lut[next[0]][prev[1]][next[2]];
175             c.r = (1-d.b) * c000.r + (d.b-d.r) * c001.r + (d.r-d.g) * c101.r + (d.g) * c111.r;
176             c.g = (1-d.b) * c000.g + (d.b-d.r) * c001.g + (d.r-d.g) * c101.g + (d.g) * c111.g;
177             c.b = (1-d.b) * c000.b + (d.b-d.r) * c001.b + (d.r-d.g) * c101.b + (d.g) * c111.b;
178         }
179     } else {
180         if (d.b > d.g) {
181             const struct rgbvec c001 = lut3d->lut[prev[0]][prev[1]][next[2]];
182             const struct rgbvec c011 = lut3d->lut[prev[0]][next[1]][next[2]];
183             c.r = (1-d.b) * c000.r + (d.b-d.g) * c001.r + (d.g-d.r) * c011.r + (d.r) * c111.r;
184             c.g = (1-d.b) * c000.g + (d.b-d.g) * c001.g + (d.g-d.r) * c011.g + (d.r) * c111.g;
185             c.b = (1-d.b) * c000.b + (d.b-d.g) * c001.b + (d.g-d.r) * c011.b + (d.r) * c111.b;
186         } else if (d.b > d.r) {
187             const struct rgbvec c010 = lut3d->lut[prev[0]][next[1]][prev[2]];
188             const struct rgbvec c011 = lut3d->lut[prev[0]][next[1]][next[2]];
189             c.r = (1-d.g) * c000.r + (d.g-d.b) * c010.r + (d.b-d.r) * c011.r + (d.r) * c111.r;
190             c.g = (1-d.g) * c000.g + (d.g-d.b) * c010.g + (d.b-d.r) * c011.g + (d.r) * c111.g;
191             c.b = (1-d.g) * c000.b + (d.g-d.b) * c010.b + (d.b-d.r) * c011.b + (d.r) * c111.b;
192         } else {
193             const struct rgbvec c010 = lut3d->lut[prev[0]][next[1]][prev[2]];
194             const struct rgbvec c110 = lut3d->lut[next[0]][next[1]][prev[2]];
195             c.r = (1-d.g) * c000.r + (d.g-d.r) * c010.r + (d.r-d.b) * c110.r + (d.b) * c111.r;
196             c.g = (1-d.g) * c000.g + (d.g-d.r) * c010.g + (d.r-d.b) * c110.g + (d.b) * c111.g;
197             c.b = (1-d.g) * c000.b + (d.g-d.r) * c010.b + (d.r-d.b) * c110.b + (d.b) * c111.b;
198         }
199     }
200     return c;
201 }
202
203 #define DEFINE_INTERP_FUNC_PLANAR(name, nbits, depth)                                                  \
204 static int interp_##nbits##_##name##_p##depth(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs) \
205 {                                                                                                      \
206     int x, y;                                                                                          \
207     const LUT3DContext *lut3d = ctx->priv;                                                             \
208     const ThreadData *td = arg;                                                                        \
209     const AVFrame *in  = td->in;                                                                       \
210     const AVFrame *out = td->out;                                                                      \
211     const int direct = out == in;                                                                      \
212     const int slice_start = (in->height *  jobnr   ) / nb_jobs;                                        \
213     const int slice_end   = (in->height * (jobnr+1)) / nb_jobs;                                        \
214     uint8_t *grow = out->data[0] + slice_start * out->linesize[0];                                     \
215     uint8_t *brow = out->data[1] + slice_start * out->linesize[1];                                     \
216     uint8_t *rrow = out->data[2] + slice_start * out->linesize[2];                                     \
217     uint8_t *arow = out->data[3] + slice_start * out->linesize[3];                                     \
218     const uint8_t *srcgrow = in->data[0] + slice_start * in->linesize[0];                              \
219     const uint8_t *srcbrow = in->data[1] + slice_start * in->linesize[1];                              \
220     const uint8_t *srcrrow = in->data[2] + slice_start * in->linesize[2];                              \
221     const uint8_t *srcarow = in->data[3] + slice_start * in->linesize[3];                              \
222     const float scale = (1. / ((1<<depth) - 1)) * (lut3d->lutsize - 1);                                \
223                                                                                                        \
224     for (y = slice_start; y < slice_end; y++) {                                                        \
225         uint##nbits##_t *dstg = (uint##nbits##_t *)grow;                                               \
226         uint##nbits##_t *dstb = (uint##nbits##_t *)brow;                                               \
227         uint##nbits##_t *dstr = (uint##nbits##_t *)rrow;                                               \
228         uint##nbits##_t *dsta = (uint##nbits##_t *)arow;                                               \
229         const uint##nbits##_t *srcg = (const uint##nbits##_t *)srcgrow;                                \
230         const uint##nbits##_t *srcb = (const uint##nbits##_t *)srcbrow;                                \
231         const uint##nbits##_t *srcr = (const uint##nbits##_t *)srcrrow;                                \
232         const uint##nbits##_t *srca = (const uint##nbits##_t *)srcarow;                                \
233         for (x = 0; x < in->width; x++) {                                                              \
234             const struct rgbvec scaled_rgb = {srcr[x] * scale,                                         \
235                                               srcg[x] * scale,                                         \
236                                               srcb[x] * scale};                                        \
237             struct rgbvec vec = interp_##name(lut3d, &scaled_rgb);                                     \
238             dstr[x] = av_clip_uintp2(vec.r * (float)((1<<depth) - 1), depth);                          \
239             dstg[x] = av_clip_uintp2(vec.g * (float)((1<<depth) - 1), depth);                          \
240             dstb[x] = av_clip_uintp2(vec.b * (float)((1<<depth) - 1), depth);                          \
241             if (!direct && in->linesize[3])                                                            \
242                 dsta[x] = srca[x];                                                                     \
243         }                                                                                              \
244         grow += out->linesize[0];                                                                      \
245         brow += out->linesize[1];                                                                      \
246         rrow += out->linesize[2];                                                                      \
247         arow += out->linesize[3];                                                                      \
248         srcgrow += in->linesize[0];                                                                    \
249         srcbrow += in->linesize[1];                                                                    \
250         srcrrow += in->linesize[2];                                                                    \
251         srcarow += in->linesize[3];                                                                    \
252     }                                                                                                  \
253     return 0;                                                                                          \
254 }
255
256 DEFINE_INTERP_FUNC_PLANAR(nearest,     8, 8)
257 DEFINE_INTERP_FUNC_PLANAR(trilinear,   8, 8)
258 DEFINE_INTERP_FUNC_PLANAR(tetrahedral, 8, 8)
259
260 DEFINE_INTERP_FUNC_PLANAR(nearest,     16, 9)
261 DEFINE_INTERP_FUNC_PLANAR(trilinear,   16, 9)
262 DEFINE_INTERP_FUNC_PLANAR(tetrahedral, 16, 9)
263
264 DEFINE_INTERP_FUNC_PLANAR(nearest,     16, 10)
265 DEFINE_INTERP_FUNC_PLANAR(trilinear,   16, 10)
266 DEFINE_INTERP_FUNC_PLANAR(tetrahedral, 16, 10)
267
268 DEFINE_INTERP_FUNC_PLANAR(nearest,     16, 12)
269 DEFINE_INTERP_FUNC_PLANAR(trilinear,   16, 12)
270 DEFINE_INTERP_FUNC_PLANAR(tetrahedral, 16, 12)
271
272 DEFINE_INTERP_FUNC_PLANAR(nearest,     16, 14)
273 DEFINE_INTERP_FUNC_PLANAR(trilinear,   16, 14)
274 DEFINE_INTERP_FUNC_PLANAR(tetrahedral, 16, 14)
275
276 DEFINE_INTERP_FUNC_PLANAR(nearest,     16, 16)
277 DEFINE_INTERP_FUNC_PLANAR(trilinear,   16, 16)
278 DEFINE_INTERP_FUNC_PLANAR(tetrahedral, 16, 16)
279
280 #define DEFINE_INTERP_FUNC(name, nbits)                                                             \
281 static int interp_##nbits##_##name(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)         \
282 {                                                                                                   \
283     int x, y;                                                                                       \
284     const LUT3DContext *lut3d = ctx->priv;                                                          \
285     const ThreadData *td = arg;                                                                     \
286     const AVFrame *in  = td->in;                                                                    \
287     const AVFrame *out = td->out;                                                                   \
288     const int direct = out == in;                                                                   \
289     const int step = lut3d->step;                                                                   \
290     const uint8_t r = lut3d->rgba_map[R];                                                           \
291     const uint8_t g = lut3d->rgba_map[G];                                                           \
292     const uint8_t b = lut3d->rgba_map[B];                                                           \
293     const uint8_t a = lut3d->rgba_map[A];                                                           \
294     const int slice_start = (in->height *  jobnr   ) / nb_jobs;                                     \
295     const int slice_end   = (in->height * (jobnr+1)) / nb_jobs;                                     \
296     uint8_t       *dstrow = out->data[0] + slice_start * out->linesize[0];                          \
297     const uint8_t *srcrow = in ->data[0] + slice_start * in ->linesize[0];                          \
298     const float scale = (1. / ((1<<nbits) - 1)) * (lut3d->lutsize - 1);                             \
299                                                                                                     \
300     for (y = slice_start; y < slice_end; y++) {                                                     \
301         uint##nbits##_t *dst = (uint##nbits##_t *)dstrow;                                           \
302         const uint##nbits##_t *src = (const uint##nbits##_t *)srcrow;                               \
303         for (x = 0; x < in->width * step; x += step) {                                              \
304             const struct rgbvec scaled_rgb = {src[x + r] * scale,                                   \
305                                               src[x + g] * scale,                                   \
306                                               src[x + b] * scale};                                  \
307             struct rgbvec vec = interp_##name(lut3d, &scaled_rgb);                                  \
308             dst[x + r] = av_clip_uint##nbits(vec.r * (float)((1<<nbits) - 1));                      \
309             dst[x + g] = av_clip_uint##nbits(vec.g * (float)((1<<nbits) - 1));                      \
310             dst[x + b] = av_clip_uint##nbits(vec.b * (float)((1<<nbits) - 1));                      \
311             if (!direct && step == 4)                                                               \
312                 dst[x + a] = src[x + a];                                                            \
313         }                                                                                           \
314         dstrow += out->linesize[0];                                                                 \
315         srcrow += in ->linesize[0];                                                                 \
316     }                                                                                               \
317     return 0;                                                                                       \
318 }
319
320 DEFINE_INTERP_FUNC(nearest,     8)
321 DEFINE_INTERP_FUNC(trilinear,   8)
322 DEFINE_INTERP_FUNC(tetrahedral, 8)
323
324 DEFINE_INTERP_FUNC(nearest,     16)
325 DEFINE_INTERP_FUNC(trilinear,   16)
326 DEFINE_INTERP_FUNC(tetrahedral, 16)
327
328 #define MAX_LINE_SIZE 512
329
330 static int skip_line(const char *p)
331 {
332     while (*p && av_isspace(*p))
333         p++;
334     return !*p || *p == '#';
335 }
336
337 #define NEXT_LINE(loop_cond) do {                           \
338     if (!fgets(line, sizeof(line), f)) {                    \
339         av_log(ctx, AV_LOG_ERROR, "Unexpected EOF\n");      \
340         return AVERROR_INVALIDDATA;                         \
341     }                                                       \
342 } while (loop_cond)
343
344 /* Basically r g and b float values on each line, with a facultative 3DLUTSIZE
345  * directive; seems to be generated by Davinci */
346 static int parse_dat(AVFilterContext *ctx, FILE *f)
347 {
348     LUT3DContext *lut3d = ctx->priv;
349     char line[MAX_LINE_SIZE];
350     int i, j, k, size;
351
352     lut3d->lutsize = size = 33;
353
354     NEXT_LINE(skip_line(line));
355     if (!strncmp(line, "3DLUTSIZE ", 10)) {
356         size = strtol(line + 10, NULL, 0);
357         if (size < 2 || size > MAX_LEVEL) {
358             av_log(ctx, AV_LOG_ERROR, "Too large or invalid 3D LUT size\n");
359             return AVERROR(EINVAL);
360         }
361         lut3d->lutsize = size;
362         NEXT_LINE(skip_line(line));
363     }
364     for (k = 0; k < size; k++) {
365         for (j = 0; j < size; j++) {
366             for (i = 0; i < size; i++) {
367                 struct rgbvec *vec = &lut3d->lut[k][j][i];
368                 if (k != 0 || j != 0 || i != 0)
369                     NEXT_LINE(skip_line(line));
370                 if (sscanf(line, "%f %f %f", &vec->r, &vec->g, &vec->b) != 3)
371                     return AVERROR_INVALIDDATA;
372             }
373         }
374     }
375     return 0;
376 }
377
378 /* Iridas format */
379 static int parse_cube(AVFilterContext *ctx, FILE *f)
380 {
381     LUT3DContext *lut3d = ctx->priv;
382     char line[MAX_LINE_SIZE];
383     float min[3] = {0.0, 0.0, 0.0};
384     float max[3] = {1.0, 1.0, 1.0};
385
386     while (fgets(line, sizeof(line), f)) {
387         if (!strncmp(line, "LUT_3D_SIZE ", 12)) {
388             int i, j, k;
389             const int size = strtol(line + 12, NULL, 0);
390
391             if (size < 2 || size > MAX_LEVEL) {
392                 av_log(ctx, AV_LOG_ERROR, "Too large or invalid 3D LUT size\n");
393                 return AVERROR(EINVAL);
394             }
395             lut3d->lutsize = size;
396             for (k = 0; k < size; k++) {
397                 for (j = 0; j < size; j++) {
398                     for (i = 0; i < size; i++) {
399                         struct rgbvec *vec = &lut3d->lut[i][j][k];
400
401                         do {
402 try_again:
403                             NEXT_LINE(0);
404                             if (!strncmp(line, "DOMAIN_", 7)) {
405                                 float *vals = NULL;
406                                 if      (!strncmp(line + 7, "MIN ", 4)) vals = min;
407                                 else if (!strncmp(line + 7, "MAX ", 4)) vals = max;
408                                 if (!vals)
409                                     return AVERROR_INVALIDDATA;
410                                 sscanf(line + 11, "%f %f %f", vals, vals + 1, vals + 2);
411                                 av_log(ctx, AV_LOG_DEBUG, "min: %f %f %f | max: %f %f %f\n",
412                                        min[0], min[1], min[2], max[0], max[1], max[2]);
413                                 goto try_again;
414                             }
415                         } while (skip_line(line));
416                         if (sscanf(line, "%f %f %f", &vec->r, &vec->g, &vec->b) != 3)
417                             return AVERROR_INVALIDDATA;
418                         vec->r *= max[0] - min[0];
419                         vec->g *= max[1] - min[1];
420                         vec->b *= max[2] - min[2];
421                     }
422                 }
423             }
424             break;
425         }
426     }
427     return 0;
428 }
429
430 /* Assume 17x17x17 LUT with a 16-bit depth
431  * FIXME: it seems there are various 3dl formats */
432 static int parse_3dl(AVFilterContext *ctx, FILE *f)
433 {
434     char line[MAX_LINE_SIZE];
435     LUT3DContext *lut3d = ctx->priv;
436     int i, j, k;
437     const int size = 17;
438     const float scale = 16*16*16;
439
440     lut3d->lutsize = size;
441     NEXT_LINE(skip_line(line));
442     for (k = 0; k < size; k++) {
443         for (j = 0; j < size; j++) {
444             for (i = 0; i < size; i++) {
445                 int r, g, b;
446                 struct rgbvec *vec = &lut3d->lut[k][j][i];
447
448                 NEXT_LINE(skip_line(line));
449                 if (sscanf(line, "%d %d %d", &r, &g, &b) != 3)
450                     return AVERROR_INVALIDDATA;
451                 vec->r = r / scale;
452                 vec->g = g / scale;
453                 vec->b = b / scale;
454             }
455         }
456     }
457     return 0;
458 }
459
460 /* Pandora format */
461 static int parse_m3d(AVFilterContext *ctx, FILE *f)
462 {
463     LUT3DContext *lut3d = ctx->priv;
464     float scale;
465     int i, j, k, size, in = -1, out = -1;
466     char line[MAX_LINE_SIZE];
467     uint8_t rgb_map[3] = {0, 1, 2};
468
469     while (fgets(line, sizeof(line), f)) {
470         if      (!strncmp(line, "in",  2)) in  = strtol(line + 2, NULL, 0);
471         else if (!strncmp(line, "out", 3)) out = strtol(line + 3, NULL, 0);
472         else if (!strncmp(line, "values", 6)) {
473             const char *p = line + 6;
474 #define SET_COLOR(id) do {                  \
475     while (av_isspace(*p))                  \
476         p++;                                \
477     switch (*p) {                           \
478     case 'r': rgb_map[id] = 0; break;       \
479     case 'g': rgb_map[id] = 1; break;       \
480     case 'b': rgb_map[id] = 2; break;       \
481     }                                       \
482     while (*p && !av_isspace(*p))           \
483         p++;                                \
484 } while (0)
485             SET_COLOR(0);
486             SET_COLOR(1);
487             SET_COLOR(2);
488             break;
489         }
490     }
491
492     if (in == -1 || out == -1) {
493         av_log(ctx, AV_LOG_ERROR, "in and out must be defined\n");
494         return AVERROR_INVALIDDATA;
495     }
496     if (in < 2 || out < 2 ||
497         in  > MAX_LEVEL*MAX_LEVEL*MAX_LEVEL ||
498         out > MAX_LEVEL*MAX_LEVEL*MAX_LEVEL) {
499         av_log(ctx, AV_LOG_ERROR, "invalid in (%d) or out (%d)\n", in, out);
500         return AVERROR_INVALIDDATA;
501     }
502     for (size = 1; size*size*size < in; size++);
503     lut3d->lutsize = size;
504     scale = 1. / (out - 1);
505
506     for (k = 0; k < size; k++) {
507         for (j = 0; j < size; j++) {
508             for (i = 0; i < size; i++) {
509                 struct rgbvec *vec = &lut3d->lut[k][j][i];
510                 float val[3];
511
512                 NEXT_LINE(0);
513                 if (sscanf(line, "%f %f %f", val, val + 1, val + 2) != 3)
514                     return AVERROR_INVALIDDATA;
515                 vec->r = val[rgb_map[0]] * scale;
516                 vec->g = val[rgb_map[1]] * scale;
517                 vec->b = val[rgb_map[2]] * scale;
518             }
519         }
520     }
521     return 0;
522 }
523
524 static void set_identity_matrix(LUT3DContext *lut3d, int size)
525 {
526     int i, j, k;
527     const float c = 1. / (size - 1);
528
529     lut3d->lutsize = size;
530     for (k = 0; k < size; k++) {
531         for (j = 0; j < size; j++) {
532             for (i = 0; i < size; i++) {
533                 struct rgbvec *vec = &lut3d->lut[k][j][i];
534                 vec->r = k * c;
535                 vec->g = j * c;
536                 vec->b = i * c;
537             }
538         }
539     }
540 }
541
542 static int query_formats(AVFilterContext *ctx)
543 {
544     static const enum AVPixelFormat pix_fmts[] = {
545         AV_PIX_FMT_RGB24,  AV_PIX_FMT_BGR24,
546         AV_PIX_FMT_RGBA,   AV_PIX_FMT_BGRA,
547         AV_PIX_FMT_ARGB,   AV_PIX_FMT_ABGR,
548         AV_PIX_FMT_0RGB,   AV_PIX_FMT_0BGR,
549         AV_PIX_FMT_RGB0,   AV_PIX_FMT_BGR0,
550         AV_PIX_FMT_RGB48,  AV_PIX_FMT_BGR48,
551         AV_PIX_FMT_RGBA64, AV_PIX_FMT_BGRA64,
552         AV_PIX_FMT_GBRP,   AV_PIX_FMT_GBRAP,
553         AV_PIX_FMT_GBRP9,
554         AV_PIX_FMT_GBRP10, AV_PIX_FMT_GBRAP10,
555         AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRAP12,
556         AV_PIX_FMT_GBRP14,
557         AV_PIX_FMT_GBRP16, AV_PIX_FMT_GBRAP16,
558         AV_PIX_FMT_NONE
559     };
560     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
561     if (!fmts_list)
562         return AVERROR(ENOMEM);
563     return ff_set_common_formats(ctx, fmts_list);
564 }
565
566 static int config_input(AVFilterLink *inlink)
567 {
568     int depth, is16bit = 0, planar = 0;
569     LUT3DContext *lut3d = inlink->dst->priv;
570     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
571
572     depth = desc->comp[0].depth;
573
574     switch (inlink->format) {
575     case AV_PIX_FMT_RGB48:
576     case AV_PIX_FMT_BGR48:
577     case AV_PIX_FMT_RGBA64:
578     case AV_PIX_FMT_BGRA64:
579         is16bit = 1;
580         break;
581     case AV_PIX_FMT_GBRP9:
582     case AV_PIX_FMT_GBRP10:
583     case AV_PIX_FMT_GBRP12:
584     case AV_PIX_FMT_GBRP14:
585     case AV_PIX_FMT_GBRP16:
586     case AV_PIX_FMT_GBRAP10:
587     case AV_PIX_FMT_GBRAP12:
588     case AV_PIX_FMT_GBRAP16:
589         is16bit = 1;
590     case AV_PIX_FMT_GBRP:
591     case AV_PIX_FMT_GBRAP:
592         planar = 1;
593         break;
594     }
595
596     ff_fill_rgba_map(lut3d->rgba_map, inlink->format);
597     lut3d->step = av_get_padded_bits_per_pixel(desc) >> (3 + is16bit);
598
599 #define SET_FUNC(name) do {                                     \
600     if (planar) {                                               \
601         switch (depth) {                                        \
602         case  8: lut3d->interp = interp_8_##name##_p8;   break; \
603         case  9: lut3d->interp = interp_16_##name##_p9;  break; \
604         case 10: lut3d->interp = interp_16_##name##_p10; break; \
605         case 12: lut3d->interp = interp_16_##name##_p12; break; \
606         case 14: lut3d->interp = interp_16_##name##_p14; break; \
607         case 16: lut3d->interp = interp_16_##name##_p16; break; \
608         }                                                       \
609     } else if (is16bit) { lut3d->interp = interp_16_##name;     \
610     } else {       lut3d->interp = interp_8_##name; }           \
611 } while (0)
612
613     switch (lut3d->interpolation) {
614     case INTERPOLATE_NEAREST:     SET_FUNC(nearest);        break;
615     case INTERPOLATE_TRILINEAR:   SET_FUNC(trilinear);      break;
616     case INTERPOLATE_TETRAHEDRAL: SET_FUNC(tetrahedral);    break;
617     default:
618         av_assert0(0);
619     }
620
621     return 0;
622 }
623
624 static AVFrame *apply_lut(AVFilterLink *inlink, AVFrame *in)
625 {
626     AVFilterContext *ctx = inlink->dst;
627     LUT3DContext *lut3d = ctx->priv;
628     AVFilterLink *outlink = inlink->dst->outputs[0];
629     AVFrame *out;
630     ThreadData td;
631
632     if (av_frame_is_writable(in)) {
633         out = in;
634     } else {
635         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
636         if (!out) {
637             av_frame_free(&in);
638             return NULL;
639         }
640         av_frame_copy_props(out, in);
641     }
642
643     td.in  = in;
644     td.out = out;
645     ctx->internal->execute(ctx, lut3d->interp, &td, NULL, FFMIN(outlink->h, ff_filter_get_nb_threads(ctx)));
646
647     if (out != in)
648         av_frame_free(&in);
649
650     return out;
651 }
652
653 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
654 {
655     AVFilterLink *outlink = inlink->dst->outputs[0];
656     AVFrame *out = apply_lut(inlink, in);
657     if (!out)
658         return AVERROR(ENOMEM);
659     return ff_filter_frame(outlink, out);
660 }
661
662 #if CONFIG_LUT3D_FILTER
663 static const AVOption lut3d_options[] = {
664     { "file", "set 3D LUT file name", OFFSET(file), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
665     COMMON_OPTIONS
666 };
667
668 AVFILTER_DEFINE_CLASS(lut3d);
669
670 static av_cold int lut3d_init(AVFilterContext *ctx)
671 {
672     int ret;
673     FILE *f;
674     const char *ext;
675     LUT3DContext *lut3d = ctx->priv;
676
677     if (!lut3d->file) {
678         set_identity_matrix(lut3d, 32);
679         return 0;
680     }
681
682     f = fopen(lut3d->file, "r");
683     if (!f) {
684         ret = AVERROR(errno);
685         av_log(ctx, AV_LOG_ERROR, "%s: %s\n", lut3d->file, av_err2str(ret));
686         return ret;
687     }
688
689     ext = strrchr(lut3d->file, '.');
690     if (!ext) {
691         av_log(ctx, AV_LOG_ERROR, "Unable to guess the format from the extension\n");
692         ret = AVERROR_INVALIDDATA;
693         goto end;
694     }
695     ext++;
696
697     if (!av_strcasecmp(ext, "dat")) {
698         ret = parse_dat(ctx, f);
699     } else if (!av_strcasecmp(ext, "3dl")) {
700         ret = parse_3dl(ctx, f);
701     } else if (!av_strcasecmp(ext, "cube")) {
702         ret = parse_cube(ctx, f);
703     } else if (!av_strcasecmp(ext, "m3d")) {
704         ret = parse_m3d(ctx, f);
705     } else {
706         av_log(ctx, AV_LOG_ERROR, "Unrecognized '.%s' file type\n", ext);
707         ret = AVERROR(EINVAL);
708     }
709
710     if (!ret && !lut3d->lutsize) {
711         av_log(ctx, AV_LOG_ERROR, "3D LUT is empty\n");
712         ret = AVERROR_INVALIDDATA;
713     }
714
715 end:
716     fclose(f);
717     return ret;
718 }
719
720 static const AVFilterPad lut3d_inputs[] = {
721     {
722         .name         = "default",
723         .type         = AVMEDIA_TYPE_VIDEO,
724         .filter_frame = filter_frame,
725         .config_props = config_input,
726     },
727     { NULL }
728 };
729
730 static const AVFilterPad lut3d_outputs[] = {
731     {
732         .name = "default",
733         .type = AVMEDIA_TYPE_VIDEO,
734     },
735     { NULL }
736 };
737
738 AVFilter ff_vf_lut3d = {
739     .name          = "lut3d",
740     .description   = NULL_IF_CONFIG_SMALL("Adjust colors using a 3D LUT."),
741     .priv_size     = sizeof(LUT3DContext),
742     .init          = lut3d_init,
743     .query_formats = query_formats,
744     .inputs        = lut3d_inputs,
745     .outputs       = lut3d_outputs,
746     .priv_class    = &lut3d_class,
747     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS,
748 };
749 #endif
750
751 #if CONFIG_HALDCLUT_FILTER
752
753 static void update_clut_packed(LUT3DContext *lut3d, const AVFrame *frame)
754 {
755     const uint8_t *data = frame->data[0];
756     const int linesize  = frame->linesize[0];
757     const int w = lut3d->clut_width;
758     const int step = lut3d->clut_step;
759     const uint8_t *rgba_map = lut3d->clut_rgba_map;
760     const int level = lut3d->lutsize;
761
762 #define LOAD_CLUT(nbits) do {                                           \
763     int i, j, k, x = 0, y = 0;                                          \
764                                                                         \
765     for (k = 0; k < level; k++) {                                       \
766         for (j = 0; j < level; j++) {                                   \
767             for (i = 0; i < level; i++) {                               \
768                 const uint##nbits##_t *src = (const uint##nbits##_t *)  \
769                     (data + y*linesize + x*step);                       \
770                 struct rgbvec *vec = &lut3d->lut[i][j][k];              \
771                 vec->r = src[rgba_map[0]] / (float)((1<<(nbits)) - 1);  \
772                 vec->g = src[rgba_map[1]] / (float)((1<<(nbits)) - 1);  \
773                 vec->b = src[rgba_map[2]] / (float)((1<<(nbits)) - 1);  \
774                 if (++x == w) {                                         \
775                     x = 0;                                              \
776                     y++;                                                \
777                 }                                                       \
778             }                                                           \
779         }                                                               \
780     }                                                                   \
781 } while (0)
782
783     switch (lut3d->clut_bits) {
784     case  8: LOAD_CLUT(8);  break;
785     case 16: LOAD_CLUT(16); break;
786     }
787 }
788
789 static void update_clut_planar(LUT3DContext *lut3d, const AVFrame *frame)
790 {
791     const uint8_t *datag = frame->data[0];
792     const uint8_t *datab = frame->data[1];
793     const uint8_t *datar = frame->data[2];
794     const int glinesize  = frame->linesize[0];
795     const int blinesize  = frame->linesize[1];
796     const int rlinesize  = frame->linesize[2];
797     const int w = lut3d->clut_width;
798     const int level = lut3d->lutsize;
799
800 #define LOAD_CLUT_PLANAR(nbits, depth) do {                             \
801     int i, j, k, x = 0, y = 0;                                          \
802                                                                         \
803     for (k = 0; k < level; k++) {                                       \
804         for (j = 0; j < level; j++) {                                   \
805             for (i = 0; i < level; i++) {                               \
806                 const uint##nbits##_t *gsrc = (const uint##nbits##_t *) \
807                     (datag + y*glinesize);                              \
808                 const uint##nbits##_t *bsrc = (const uint##nbits##_t *) \
809                     (datab + y*blinesize);                              \
810                 const uint##nbits##_t *rsrc = (const uint##nbits##_t *) \
811                     (datar + y*rlinesize);                              \
812                 struct rgbvec *vec = &lut3d->lut[i][j][k];              \
813                 vec->r = gsrc[x] / (float)((1<<(depth)) - 1);           \
814                 vec->g = bsrc[x] / (float)((1<<(depth)) - 1);           \
815                 vec->b = rsrc[x] / (float)((1<<(depth)) - 1);           \
816                 if (++x == w) {                                         \
817                     x = 0;                                              \
818                     y++;                                                \
819                 }                                                       \
820             }                                                           \
821         }                                                               \
822     }                                                                   \
823 } while (0)
824
825     switch (lut3d->clut_bits) {
826     case  8: LOAD_CLUT_PLANAR(8, 8);   break;
827     case  9: LOAD_CLUT_PLANAR(16, 9);  break;
828     case 10: LOAD_CLUT_PLANAR(16, 10); break;
829     case 12: LOAD_CLUT_PLANAR(16, 12); break;
830     case 14: LOAD_CLUT_PLANAR(16, 14); break;
831     case 16: LOAD_CLUT_PLANAR(16, 16); break;
832     }
833 }
834
835 static int config_output(AVFilterLink *outlink)
836 {
837     AVFilterContext *ctx = outlink->src;
838     LUT3DContext *lut3d = ctx->priv;
839     int ret;
840
841     ret = ff_framesync_init_dualinput(&lut3d->fs, ctx);
842     if (ret < 0)
843         return ret;
844     outlink->w = ctx->inputs[0]->w;
845     outlink->h = ctx->inputs[0]->h;
846     outlink->time_base = ctx->inputs[0]->time_base;
847     if ((ret = ff_framesync_configure(&lut3d->fs)) < 0)
848         return ret;
849     return 0;
850 }
851
852 static int activate(AVFilterContext *ctx)
853 {
854     LUT3DContext *s = ctx->priv;
855     return ff_framesync_activate(&s->fs);
856 }
857
858 static int config_clut(AVFilterLink *inlink)
859 {
860     int size, level, w, h;
861     AVFilterContext *ctx = inlink->dst;
862     LUT3DContext *lut3d = ctx->priv;
863     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
864
865     av_assert0(desc);
866
867     lut3d->clut_bits = desc->comp[0].depth;
868     lut3d->clut_planar = av_pix_fmt_count_planes(inlink->format) > 1;
869
870     lut3d->clut_step = av_get_padded_bits_per_pixel(desc) >> 3;
871     ff_fill_rgba_map(lut3d->clut_rgba_map, inlink->format);
872
873     if (inlink->w > inlink->h)
874         av_log(ctx, AV_LOG_INFO, "Padding on the right (%dpx) of the "
875                "Hald CLUT will be ignored\n", inlink->w - inlink->h);
876     else if (inlink->w < inlink->h)
877         av_log(ctx, AV_LOG_INFO, "Padding at the bottom (%dpx) of the "
878                "Hald CLUT will be ignored\n", inlink->h - inlink->w);
879     lut3d->clut_width = w = h = FFMIN(inlink->w, inlink->h);
880
881     for (level = 1; level*level*level < w; level++);
882     size = level*level*level;
883     if (size != w) {
884         av_log(ctx, AV_LOG_WARNING, "The Hald CLUT width does not match the level\n");
885         return AVERROR_INVALIDDATA;
886     }
887     av_assert0(w == h && w == size);
888     level *= level;
889     if (level > MAX_LEVEL) {
890         const int max_clut_level = sqrt(MAX_LEVEL);
891         const int max_clut_size  = max_clut_level*max_clut_level*max_clut_level;
892         av_log(ctx, AV_LOG_ERROR, "Too large Hald CLUT "
893                "(maximum level is %d, or %dx%d CLUT)\n",
894                max_clut_level, max_clut_size, max_clut_size);
895         return AVERROR(EINVAL);
896     }
897     lut3d->lutsize = level;
898
899     return 0;
900 }
901
902 static int update_apply_clut(FFFrameSync *fs)
903 {
904     AVFilterContext *ctx = fs->parent;
905     LUT3DContext *lut3d = ctx->priv;
906     AVFilterLink *inlink = ctx->inputs[0];
907     AVFrame *master, *second, *out;
908     int ret;
909
910     ret = ff_framesync_dualinput_get(fs, &master, &second);
911     if (ret < 0)
912         return ret;
913     if (!second)
914         return ff_filter_frame(ctx->outputs[0], master);
915     if (lut3d->clut_planar)
916         update_clut_planar(ctx->priv, second);
917     else
918         update_clut_packed(ctx->priv, second);
919     out = apply_lut(inlink, master);
920     return ff_filter_frame(ctx->outputs[0], out);
921 }
922
923 static av_cold int haldclut_init(AVFilterContext *ctx)
924 {
925     LUT3DContext *lut3d = ctx->priv;
926     lut3d->fs.on_event = update_apply_clut;
927     return 0;
928 }
929
930 static av_cold void haldclut_uninit(AVFilterContext *ctx)
931 {
932     LUT3DContext *lut3d = ctx->priv;
933     ff_framesync_uninit(&lut3d->fs);
934 }
935
936 static const AVOption haldclut_options[] = {
937     COMMON_OPTIONS
938 };
939
940 FRAMESYNC_DEFINE_CLASS(haldclut, LUT3DContext, fs);
941
942 static const AVFilterPad haldclut_inputs[] = {
943     {
944         .name         = "main",
945         .type         = AVMEDIA_TYPE_VIDEO,
946         .config_props = config_input,
947     },{
948         .name         = "clut",
949         .type         = AVMEDIA_TYPE_VIDEO,
950         .config_props = config_clut,
951     },
952     { NULL }
953 };
954
955 static const AVFilterPad haldclut_outputs[] = {
956     {
957         .name          = "default",
958         .type          = AVMEDIA_TYPE_VIDEO,
959         .config_props  = config_output,
960     },
961     { NULL }
962 };
963
964 AVFilter ff_vf_haldclut = {
965     .name          = "haldclut",
966     .description   = NULL_IF_CONFIG_SMALL("Adjust colors using a Hald CLUT."),
967     .priv_size     = sizeof(LUT3DContext),
968     .preinit       = haldclut_framesync_preinit,
969     .init          = haldclut_init,
970     .uninit        = haldclut_uninit,
971     .query_formats = query_formats,
972     .activate      = activate,
973     .inputs        = haldclut_inputs,
974     .outputs       = haldclut_outputs,
975     .priv_class    = &haldclut_class,
976     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL | AVFILTER_FLAG_SLICE_THREADS,
977 };
978 #endif
979
980 #if CONFIG_LUT1D_FILTER
981
982 enum interp_1d_mode {
983     INTERPOLATE_1D_NEAREST,
984     INTERPOLATE_1D_LINEAR,
985     INTERPOLATE_1D_CUBIC,
986     NB_INTERP_1D_MODE
987 };
988
989 #define MAX_1D_LEVEL 65536
990
991 typedef struct LUT1DContext {
992     const AVClass *class;
993     char *file;
994     int interpolation;          ///<interp_1d_mode
995     uint8_t rgba_map[4];
996     int step;
997     float lut[3][MAX_1D_LEVEL];
998     int lutsize;
999     avfilter_action_func *interp;
1000 } LUT1DContext;
1001
1002 #undef OFFSET
1003 #define OFFSET(x) offsetof(LUT1DContext, x)
1004
1005 static void set_identity_matrix_1d(LUT1DContext *lut1d, int size)
1006 {
1007     const float c = 1. / (size - 1);
1008     int i;
1009
1010     lut1d->lutsize = size;
1011     for (i = 0; i < size; i++) {
1012         lut1d->lut[0][i] = i * c;
1013         lut1d->lut[1][i] = i * c;
1014         lut1d->lut[2][i] = i * c;
1015     }
1016 }
1017
1018 static int parse_cube_1d(AVFilterContext *ctx, FILE *f)
1019 {
1020     LUT1DContext *lut1d = ctx->priv;
1021     char line[MAX_LINE_SIZE];
1022     float min[3] = {0.0, 0.0, 0.0};
1023     float max[3] = {1.0, 1.0, 1.0};
1024
1025     while (fgets(line, sizeof(line), f)) {
1026         if (!strncmp(line, "LUT_1D_SIZE ", 12)) {
1027             const int size = strtol(line + 12, NULL, 0);
1028             int i;
1029
1030             if (size < 2 || size > MAX_1D_LEVEL) {
1031                 av_log(ctx, AV_LOG_ERROR, "Too large or invalid 1D LUT size\n");
1032                 return AVERROR(EINVAL);
1033             }
1034             lut1d->lutsize = size;
1035             for (i = 0; i < size; i++) {
1036                 do {
1037 try_again:
1038                     NEXT_LINE(0);
1039                     if (!strncmp(line, "DOMAIN_", 7)) {
1040                         float *vals = NULL;
1041                         if      (!strncmp(line + 7, "MIN ", 4)) vals = min;
1042                         else if (!strncmp(line + 7, "MAX ", 4)) vals = max;
1043                         if (!vals)
1044                             return AVERROR_INVALIDDATA;
1045                         sscanf(line + 11, "%f %f %f", vals, vals + 1, vals + 2);
1046                         av_log(ctx, AV_LOG_DEBUG, "min: %f %f %f | max: %f %f %f\n",
1047                                min[0], min[1], min[2], max[0], max[1], max[2]);
1048                         goto try_again;
1049                     } else if (!strncmp(line, "LUT_1D_INPUT_RANGE ", 19)) {
1050                         sscanf(line + 19, "%f %f", min, max);
1051                         min[1] = min[2] = min[0];
1052                         max[1] = max[2] = max[0];
1053                         goto try_again;
1054                     }
1055                 } while (skip_line(line));
1056                 if (sscanf(line, "%f %f %f", &lut1d->lut[0][i], &lut1d->lut[1][i], &lut1d->lut[2][i]) != 3)
1057                     return AVERROR_INVALIDDATA;
1058                 lut1d->lut[0][i] *= max[0] - min[0];
1059                 lut1d->lut[1][i] *= max[1] - min[1];
1060                 lut1d->lut[2][i] *= max[2] - min[2];
1061             }
1062             break;
1063         }
1064     }
1065     return 0;
1066 }
1067
1068 static const AVOption lut1d_options[] = {
1069     { "file", "set 1D LUT file name", OFFSET(file), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
1070     { "interp", "select interpolation mode", OFFSET(interpolation),    AV_OPT_TYPE_INT, {.i64=INTERPOLATE_1D_LINEAR}, 0, NB_INTERP_1D_MODE-1, FLAGS, "interp_mode" },
1071         { "nearest", "use values from the nearest defined points", 0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_1D_NEAREST},   INT_MIN, INT_MAX, FLAGS, "interp_mode" },
1072         { "linear",  "use values from the linear interpolation",   0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_1D_LINEAR},    INT_MIN, INT_MAX, FLAGS, "interp_mode" },
1073         { "cubic",   "use values from the cubic interpolation",    0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_1D_CUBIC},     INT_MIN, INT_MAX, FLAGS, "interp_mode" },
1074     { NULL }
1075 };
1076
1077 AVFILTER_DEFINE_CLASS(lut1d);
1078
1079 static inline float interp_1d_nearest(const LUT1DContext *lut1d,
1080                                       int idx, const float s)
1081 {
1082     return lut1d->lut[idx][NEAR(s)];
1083 }
1084
1085 #define NEXT1D(x) (FFMIN((int)(x) + 1, lut1d->lutsize - 1))
1086
1087 static inline float interp_1d_linear(const LUT1DContext *lut1d,
1088                                      int idx, const float s)
1089 {
1090     const int prev = PREV(s);
1091     const int next = NEXT1D(s);
1092     const float d = s - prev;
1093     const float p = lut1d->lut[idx][prev];
1094     const float n = lut1d->lut[idx][next];
1095
1096     return lerpf(p, n, d);
1097 }
1098
1099 static inline float interp_1d_cubic(const LUT1DContext *lut1d,
1100                                     int idx, const float s)
1101 {
1102     const int prev = PREV(s);
1103     const int next = NEXT1D(s);
1104     const float mu = s - prev;
1105     float a0, a1, a2, a3, mu2;
1106
1107     float y0 = lut1d->lut[idx][FFMAX(prev - 1, 0)];
1108     float y1 = lut1d->lut[idx][prev];
1109     float y2 = lut1d->lut[idx][next];
1110     float y3 = lut1d->lut[idx][FFMIN(next + 1, lut1d->lutsize - 1)];
1111
1112
1113     mu2 = mu * mu;
1114     a0 = y3 - y2 - y0 + y1;
1115     a1 = y0 - y1 - a0;
1116     a2 = y2 - y0;
1117     a3 = y1;
1118
1119     return a0 * mu * mu2 + a1 * mu2 + a2 * mu + a3;
1120 }
1121
1122 #define DEFINE_INTERP_FUNC_PLANAR_1D(name, nbits, depth)                     \
1123 static int interp_1d_##nbits##_##name##_p##depth(AVFilterContext *ctx,       \
1124                                                  void *arg, int jobnr,       \
1125                                                  int nb_jobs)                \
1126 {                                                                            \
1127     int x, y;                                                                \
1128     const LUT1DContext *lut1d = ctx->priv;                                   \
1129     const ThreadData *td = arg;                                              \
1130     const AVFrame *in  = td->in;                                             \
1131     const AVFrame *out = td->out;                                            \
1132     const int direct = out == in;                                            \
1133     const int slice_start = (in->height *  jobnr   ) / nb_jobs;              \
1134     const int slice_end   = (in->height * (jobnr+1)) / nb_jobs;              \
1135     uint8_t *grow = out->data[0] + slice_start * out->linesize[0];           \
1136     uint8_t *brow = out->data[1] + slice_start * out->linesize[1];           \
1137     uint8_t *rrow = out->data[2] + slice_start * out->linesize[2];           \
1138     uint8_t *arow = out->data[3] + slice_start * out->linesize[3];           \
1139     const uint8_t *srcgrow = in->data[0] + slice_start * in->linesize[0];    \
1140     const uint8_t *srcbrow = in->data[1] + slice_start * in->linesize[1];    \
1141     const uint8_t *srcrrow = in->data[2] + slice_start * in->linesize[2];    \
1142     const uint8_t *srcarow = in->data[3] + slice_start * in->linesize[3];    \
1143     const float factor = (1 << depth) - 1;                                   \
1144     const float scale = (1. / factor) * (lut1d->lutsize - 1);                \
1145                                                                              \
1146     for (y = slice_start; y < slice_end; y++) {                              \
1147         uint##nbits##_t *dstg = (uint##nbits##_t *)grow;                     \
1148         uint##nbits##_t *dstb = (uint##nbits##_t *)brow;                     \
1149         uint##nbits##_t *dstr = (uint##nbits##_t *)rrow;                     \
1150         uint##nbits##_t *dsta = (uint##nbits##_t *)arow;                     \
1151         const uint##nbits##_t *srcg = (const uint##nbits##_t *)srcgrow;      \
1152         const uint##nbits##_t *srcb = (const uint##nbits##_t *)srcbrow;      \
1153         const uint##nbits##_t *srcr = (const uint##nbits##_t *)srcrrow;      \
1154         const uint##nbits##_t *srca = (const uint##nbits##_t *)srcarow;      \
1155         for (x = 0; x < in->width; x++) {                                    \
1156             float r = srcr[x] * scale;                                       \
1157             float g = srcg[x] * scale;                                       \
1158             float b = srcb[x] * scale;                                       \
1159             r = interp_1d_##name(lut1d, 0, r);                               \
1160             g = interp_1d_##name(lut1d, 1, g);                               \
1161             b = interp_1d_##name(lut1d, 2, b);                               \
1162             dstr[x] = av_clip_uintp2(r * factor, depth);                     \
1163             dstg[x] = av_clip_uintp2(g * factor, depth);                     \
1164             dstb[x] = av_clip_uintp2(b * factor, depth);                     \
1165             if (!direct && in->linesize[3])                                  \
1166                 dsta[x] = srca[x];                                           \
1167         }                                                                    \
1168         grow += out->linesize[0];                                            \
1169         brow += out->linesize[1];                                            \
1170         rrow += out->linesize[2];                                            \
1171         arow += out->linesize[3];                                            \
1172         srcgrow += in->linesize[0];                                          \
1173         srcbrow += in->linesize[1];                                          \
1174         srcrrow += in->linesize[2];                                          \
1175         srcarow += in->linesize[3];                                          \
1176     }                                                                        \
1177     return 0;                                                                \
1178 }
1179
1180 DEFINE_INTERP_FUNC_PLANAR_1D(nearest,     8, 8)
1181 DEFINE_INTERP_FUNC_PLANAR_1D(linear,      8, 8)
1182 DEFINE_INTERP_FUNC_PLANAR_1D(cubic,       8, 8)
1183
1184 DEFINE_INTERP_FUNC_PLANAR_1D(nearest,     16, 9)
1185 DEFINE_INTERP_FUNC_PLANAR_1D(linear,      16, 9)
1186 DEFINE_INTERP_FUNC_PLANAR_1D(cubic,       16, 9)
1187
1188 DEFINE_INTERP_FUNC_PLANAR_1D(nearest,     16, 10)
1189 DEFINE_INTERP_FUNC_PLANAR_1D(linear,      16, 10)
1190 DEFINE_INTERP_FUNC_PLANAR_1D(cubic,       16, 10)
1191
1192 DEFINE_INTERP_FUNC_PLANAR_1D(nearest,     16, 12)
1193 DEFINE_INTERP_FUNC_PLANAR_1D(linear,      16, 12)
1194 DEFINE_INTERP_FUNC_PLANAR_1D(cubic,       16, 12)
1195
1196 DEFINE_INTERP_FUNC_PLANAR_1D(nearest,     16, 14)
1197 DEFINE_INTERP_FUNC_PLANAR_1D(linear,      16, 14)
1198 DEFINE_INTERP_FUNC_PLANAR_1D(cubic,       16, 14)
1199
1200 DEFINE_INTERP_FUNC_PLANAR_1D(nearest,     16, 16)
1201 DEFINE_INTERP_FUNC_PLANAR_1D(linear,      16, 16)
1202 DEFINE_INTERP_FUNC_PLANAR_1D(cubic,       16, 16)
1203
1204 #define DEFINE_INTERP_FUNC_1D(name, nbits)                                   \
1205 static int interp_1d_##nbits##_##name(AVFilterContext *ctx, void *arg,       \
1206                                       int jobnr, int nb_jobs)                \
1207 {                                                                            \
1208     int x, y;                                                                \
1209     const LUT1DContext *lut1d = ctx->priv;                                   \
1210     const ThreadData *td = arg;                                              \
1211     const AVFrame *in  = td->in;                                             \
1212     const AVFrame *out = td->out;                                            \
1213     const int direct = out == in;                                            \
1214     const int step = lut1d->step;                                            \
1215     const uint8_t r = lut1d->rgba_map[R];                                    \
1216     const uint8_t g = lut1d->rgba_map[G];                                    \
1217     const uint8_t b = lut1d->rgba_map[B];                                    \
1218     const uint8_t a = lut1d->rgba_map[A];                                    \
1219     const int slice_start = (in->height *  jobnr   ) / nb_jobs;              \
1220     const int slice_end   = (in->height * (jobnr+1)) / nb_jobs;              \
1221     uint8_t       *dstrow = out->data[0] + slice_start * out->linesize[0];   \
1222     const uint8_t *srcrow = in ->data[0] + slice_start * in ->linesize[0];   \
1223     const float factor = (1 << nbits) - 1;                                   \
1224     const float scale = (1. / factor) * (lut1d->lutsize - 1);                \
1225                                                                              \
1226     for (y = slice_start; y < slice_end; y++) {                              \
1227         uint##nbits##_t *dst = (uint##nbits##_t *)dstrow;                    \
1228         const uint##nbits##_t *src = (const uint##nbits##_t *)srcrow;        \
1229         for (x = 0; x < in->width * step; x += step) {                       \
1230             float rr = src[x + r] * scale;                                   \
1231             float gg = src[x + g] * scale;                                   \
1232             float bb = src[x + b] * scale;                                   \
1233             rr = interp_1d_##name(lut1d, 0, rr);                             \
1234             gg = interp_1d_##name(lut1d, 1, gg);                             \
1235             bb = interp_1d_##name(lut1d, 2, bb);                             \
1236             dst[x + r] = av_clip_uint##nbits(rr * factor);                   \
1237             dst[x + g] = av_clip_uint##nbits(gg * factor);                   \
1238             dst[x + b] = av_clip_uint##nbits(bb * factor);                   \
1239             if (!direct && step == 4)                                        \
1240                 dst[x + a] = src[x + a];                                     \
1241         }                                                                    \
1242         dstrow += out->linesize[0];                                          \
1243         srcrow += in ->linesize[0];                                          \
1244     }                                                                        \
1245     return 0;                                                                \
1246 }
1247
1248 DEFINE_INTERP_FUNC_1D(nearest,     8)
1249 DEFINE_INTERP_FUNC_1D(linear,      8)
1250 DEFINE_INTERP_FUNC_1D(cubic,       8)
1251
1252 DEFINE_INTERP_FUNC_1D(nearest,     16)
1253 DEFINE_INTERP_FUNC_1D(linear,      16)
1254 DEFINE_INTERP_FUNC_1D(cubic,       16)
1255
1256 static int config_input_1d(AVFilterLink *inlink)
1257 {
1258     int depth, is16bit = 0, planar = 0;
1259     LUT1DContext *lut1d = inlink->dst->priv;
1260     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
1261
1262     depth = desc->comp[0].depth;
1263
1264     switch (inlink->format) {
1265     case AV_PIX_FMT_RGB48:
1266     case AV_PIX_FMT_BGR48:
1267     case AV_PIX_FMT_RGBA64:
1268     case AV_PIX_FMT_BGRA64:
1269         is16bit = 1;
1270         break;
1271     case AV_PIX_FMT_GBRP9:
1272     case AV_PIX_FMT_GBRP10:
1273     case AV_PIX_FMT_GBRP12:
1274     case AV_PIX_FMT_GBRP14:
1275     case AV_PIX_FMT_GBRP16:
1276     case AV_PIX_FMT_GBRAP10:
1277     case AV_PIX_FMT_GBRAP12:
1278     case AV_PIX_FMT_GBRAP16:
1279         is16bit = 1;
1280     case AV_PIX_FMT_GBRP:
1281     case AV_PIX_FMT_GBRAP:
1282         planar = 1;
1283         break;
1284     }
1285
1286     ff_fill_rgba_map(lut1d->rgba_map, inlink->format);
1287     lut1d->step = av_get_padded_bits_per_pixel(desc) >> (3 + is16bit);
1288
1289 #define SET_FUNC_1D(name) do {                                     \
1290     if (planar) {                                                  \
1291         switch (depth) {                                           \
1292         case  8: lut1d->interp = interp_1d_8_##name##_p8;   break; \
1293         case  9: lut1d->interp = interp_1d_16_##name##_p9;  break; \
1294         case 10: lut1d->interp = interp_1d_16_##name##_p10; break; \
1295         case 12: lut1d->interp = interp_1d_16_##name##_p12; break; \
1296         case 14: lut1d->interp = interp_1d_16_##name##_p14; break; \
1297         case 16: lut1d->interp = interp_1d_16_##name##_p16; break; \
1298         }                                                          \
1299     } else if (is16bit) { lut1d->interp = interp_1d_16_##name;     \
1300     } else {              lut1d->interp = interp_1d_8_##name; }    \
1301 } while (0)
1302
1303     switch (lut1d->interpolation) {
1304     case INTERPOLATE_1D_NEAREST:     SET_FUNC_1D(nearest);  break;
1305     case INTERPOLATE_1D_LINEAR:      SET_FUNC_1D(linear);   break;
1306     case INTERPOLATE_1D_CUBIC:       SET_FUNC_1D(cubic);    break;
1307     default:
1308         av_assert0(0);
1309     }
1310
1311     return 0;
1312 }
1313
1314 static av_cold int lut1d_init(AVFilterContext *ctx)
1315 {
1316     int ret;
1317     FILE *f;
1318     const char *ext;
1319     LUT1DContext *lut1d = ctx->priv;
1320
1321     if (!lut1d->file) {
1322         set_identity_matrix_1d(lut1d, 32);
1323         return 0;
1324     }
1325
1326     f = fopen(lut1d->file, "r");
1327     if (!f) {
1328         ret = AVERROR(errno);
1329         av_log(ctx, AV_LOG_ERROR, "%s: %s\n", lut1d->file, av_err2str(ret));
1330         return ret;
1331     }
1332
1333     ext = strrchr(lut1d->file, '.');
1334     if (!ext) {
1335         av_log(ctx, AV_LOG_ERROR, "Unable to guess the format from the extension\n");
1336         ret = AVERROR_INVALIDDATA;
1337         goto end;
1338     }
1339     ext++;
1340
1341     if (!av_strcasecmp(ext, "cube") || !av_strcasecmp(ext, "1dlut")) {
1342         ret = parse_cube_1d(ctx, f);
1343     } else {
1344         av_log(ctx, AV_LOG_ERROR, "Unrecognized '.%s' file type\n", ext);
1345         ret = AVERROR(EINVAL);
1346     }
1347
1348     if (!ret && !lut1d->lutsize) {
1349         av_log(ctx, AV_LOG_ERROR, "1D LUT is empty\n");
1350         ret = AVERROR_INVALIDDATA;
1351     }
1352
1353 end:
1354     fclose(f);
1355     return ret;
1356 }
1357
1358 static AVFrame *apply_1d_lut(AVFilterLink *inlink, AVFrame *in)
1359 {
1360     AVFilterContext *ctx = inlink->dst;
1361     LUT1DContext *lut1d = ctx->priv;
1362     AVFilterLink *outlink = inlink->dst->outputs[0];
1363     AVFrame *out;
1364     ThreadData td;
1365
1366     if (av_frame_is_writable(in)) {
1367         out = in;
1368     } else {
1369         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
1370         if (!out) {
1371             av_frame_free(&in);
1372             return NULL;
1373         }
1374         av_frame_copy_props(out, in);
1375     }
1376
1377     td.in  = in;
1378     td.out = out;
1379     ctx->internal->execute(ctx, lut1d->interp, &td, NULL, FFMIN(outlink->h, ff_filter_get_nb_threads(ctx)));
1380
1381     if (out != in)
1382         av_frame_free(&in);
1383
1384     return out;
1385 }
1386
1387 static int filter_frame_1d(AVFilterLink *inlink, AVFrame *in)
1388 {
1389     AVFilterLink *outlink = inlink->dst->outputs[0];
1390     AVFrame *out = apply_1d_lut(inlink, in);
1391     if (!out)
1392         return AVERROR(ENOMEM);
1393     return ff_filter_frame(outlink, out);
1394 }
1395
1396 static const AVFilterPad lut1d_inputs[] = {
1397     {
1398         .name         = "default",
1399         .type         = AVMEDIA_TYPE_VIDEO,
1400         .filter_frame = filter_frame_1d,
1401         .config_props = config_input_1d,
1402     },
1403     { NULL }
1404 };
1405
1406 static const AVFilterPad lut1d_outputs[] = {
1407     {
1408         .name = "default",
1409         .type = AVMEDIA_TYPE_VIDEO,
1410     },
1411     { NULL }
1412 };
1413
1414 AVFilter ff_vf_lut1d = {
1415     .name          = "lut1d",
1416     .description   = NULL_IF_CONFIG_SMALL("Adjust colors using a 1D LUT."),
1417     .priv_size     = sizeof(LUT1DContext),
1418     .init          = lut1d_init,
1419     .query_formats = query_formats,
1420     .inputs        = lut1d_inputs,
1421     .outputs       = lut1d_outputs,
1422     .priv_class    = &lut1d_class,
1423     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS,
1424 };
1425 #endif