]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_lut3d.c
avfilter/vf_lut3d: add cineSpace 3D lut support
[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 (av_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", 11)) {
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                                 av_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                             } else if (!strncmp(line, "TITLE", 5)) {
415                                 goto try_again;
416                             }
417                         } while (skip_line(line));
418                         if (av_sscanf(line, "%f %f %f", &vec->r, &vec->g, &vec->b) != 3)
419                             return AVERROR_INVALIDDATA;
420                         vec->r *= max[0] - min[0];
421                         vec->g *= max[1] - min[1];
422                         vec->b *= max[2] - min[2];
423                     }
424                 }
425             }
426             break;
427         }
428     }
429     return 0;
430 }
431
432 /* Assume 17x17x17 LUT with a 16-bit depth
433  * FIXME: it seems there are various 3dl formats */
434 static int parse_3dl(AVFilterContext *ctx, FILE *f)
435 {
436     char line[MAX_LINE_SIZE];
437     LUT3DContext *lut3d = ctx->priv;
438     int i, j, k;
439     const int size = 17;
440     const float scale = 16*16*16;
441
442     lut3d->lutsize = size;
443     NEXT_LINE(skip_line(line));
444     for (k = 0; k < size; k++) {
445         for (j = 0; j < size; j++) {
446             for (i = 0; i < size; i++) {
447                 int r, g, b;
448                 struct rgbvec *vec = &lut3d->lut[k][j][i];
449
450                 NEXT_LINE(skip_line(line));
451                 if (av_sscanf(line, "%d %d %d", &r, &g, &b) != 3)
452                     return AVERROR_INVALIDDATA;
453                 vec->r = r / scale;
454                 vec->g = g / scale;
455                 vec->b = b / scale;
456             }
457         }
458     }
459     return 0;
460 }
461
462 /* Pandora format */
463 static int parse_m3d(AVFilterContext *ctx, FILE *f)
464 {
465     LUT3DContext *lut3d = ctx->priv;
466     float scale;
467     int i, j, k, size, in = -1, out = -1;
468     char line[MAX_LINE_SIZE];
469     uint8_t rgb_map[3] = {0, 1, 2};
470
471     while (fgets(line, sizeof(line), f)) {
472         if      (!strncmp(line, "in",  2)) in  = strtol(line + 2, NULL, 0);
473         else if (!strncmp(line, "out", 3)) out = strtol(line + 3, NULL, 0);
474         else if (!strncmp(line, "values", 6)) {
475             const char *p = line + 6;
476 #define SET_COLOR(id) do {                  \
477     while (av_isspace(*p))                  \
478         p++;                                \
479     switch (*p) {                           \
480     case 'r': rgb_map[id] = 0; break;       \
481     case 'g': rgb_map[id] = 1; break;       \
482     case 'b': rgb_map[id] = 2; break;       \
483     }                                       \
484     while (*p && !av_isspace(*p))           \
485         p++;                                \
486 } while (0)
487             SET_COLOR(0);
488             SET_COLOR(1);
489             SET_COLOR(2);
490             break;
491         }
492     }
493
494     if (in == -1 || out == -1) {
495         av_log(ctx, AV_LOG_ERROR, "in and out must be defined\n");
496         return AVERROR_INVALIDDATA;
497     }
498     if (in < 2 || out < 2 ||
499         in  > MAX_LEVEL*MAX_LEVEL*MAX_LEVEL ||
500         out > MAX_LEVEL*MAX_LEVEL*MAX_LEVEL) {
501         av_log(ctx, AV_LOG_ERROR, "invalid in (%d) or out (%d)\n", in, out);
502         return AVERROR_INVALIDDATA;
503     }
504     for (size = 1; size*size*size < in; size++);
505     lut3d->lutsize = size;
506     scale = 1. / (out - 1);
507
508     for (k = 0; k < size; k++) {
509         for (j = 0; j < size; j++) {
510             for (i = 0; i < size; i++) {
511                 struct rgbvec *vec = &lut3d->lut[k][j][i];
512                 float val[3];
513
514                 NEXT_LINE(0);
515                 if (av_sscanf(line, "%f %f %f", val, val + 1, val + 2) != 3)
516                     return AVERROR_INVALIDDATA;
517                 vec->r = val[rgb_map[0]] * scale;
518                 vec->g = val[rgb_map[1]] * scale;
519                 vec->b = val[rgb_map[2]] * scale;
520             }
521         }
522     }
523     return 0;
524 }
525
526 static int parse_cinespace(AVFilterContext *ctx, FILE *f)
527 {
528     LUT3DContext *lut3d = ctx->priv;
529     char line[MAX_LINE_SIZE];
530     float in_min[3]  = {0.0, 0.0, 0.0};
531     float in_max[3]  = {1.0, 1.0, 1.0};
532     float out_min[3] = {0.0, 0.0, 0.0};
533     float out_max[3] = {1.0, 1.0, 1.0};
534     int inside_metadata = 0, size;
535
536     NEXT_LINE(skip_line(line));
537     if (strncmp(line, "CSPLUTV100", 10)) {
538         av_log(ctx, AV_LOG_ERROR, "Not cineSpace LUT format\n");
539         return AVERROR(EINVAL);
540     }
541
542     NEXT_LINE(skip_line(line));
543     if (strncmp(line, "3D", 2)) {
544         av_log(ctx, AV_LOG_ERROR, "Not 3D LUT format\n");
545         return AVERROR(EINVAL);
546     }
547
548     while (1) {
549         NEXT_LINE(skip_line(line));
550
551         if (!strncmp(line, "BEGIN METADATA", 14)) {
552             inside_metadata = 1;
553             continue;
554         }
555         if (!strncmp(line, "END METADATA", 12)) {
556             inside_metadata = 0;
557             continue;
558         }
559         if (inside_metadata == 0) {
560             int size_r, size_g, size_b;
561
562             for (int i = 0; i < 3; i++) {
563                 int npoints = strtol(line, NULL, 0);
564
565                 if (npoints != 2) {
566                     av_log(ctx, AV_LOG_ERROR, "Unsupported number of pre-lut points.\n");
567                     return AVERROR_PATCHWELCOME;
568                 }
569
570                 NEXT_LINE(skip_line(line));
571                 if (av_sscanf(line, "%f %f", &in_min[i], &in_max[i]) != 2)
572                     return AVERROR_INVALIDDATA;
573                 NEXT_LINE(skip_line(line));
574                 if (av_sscanf(line, "%f %f", &out_min[i], &out_max[i]) != 2)
575                     return AVERROR_INVALIDDATA;
576                 NEXT_LINE(skip_line(line));
577             }
578
579             if (av_sscanf(line, "%d %d %d", &size_r, &size_g, &size_b) != 3)
580                 return AVERROR(EINVAL);
581             if (size_r != size_g || size_r != size_b) {
582                 av_log(ctx, AV_LOG_ERROR, "Unsupported size combination: %dx%dx%d.\n", size_r, size_g, size_b);
583                 return AVERROR_PATCHWELCOME;
584             }
585
586             size = size_r;
587             if (size < 2 || size > MAX_LEVEL) {
588                 av_log(ctx, AV_LOG_ERROR, "Too large or invalid 3D LUT size\n");
589                 return AVERROR(EINVAL);
590             }
591
592             lut3d->lutsize = size;
593
594             for (int k = 0; k < size; k++) {
595                 for (int j = 0; j < size; j++) {
596                     for (int i = 0; i < size; i++) {
597                         struct rgbvec *vec = &lut3d->lut[i][j][k];
598                         if (k != 0 || j != 0 || i != 0)
599                             NEXT_LINE(skip_line(line));
600                         if (av_sscanf(line, "%f %f %f", &vec->r, &vec->g, &vec->b) != 3)
601                             return AVERROR_INVALIDDATA;
602                         vec->r *= out_max[0] - out_min[0];
603                         vec->g *= out_max[1] - out_min[1];
604                         vec->b *= out_max[2] - out_min[2];
605                     }
606                 }
607             }
608
609             break;
610         }
611     }
612     return 0;
613 }
614
615 static void set_identity_matrix(LUT3DContext *lut3d, int size)
616 {
617     int i, j, k;
618     const float c = 1. / (size - 1);
619
620     lut3d->lutsize = size;
621     for (k = 0; k < size; k++) {
622         for (j = 0; j < size; j++) {
623             for (i = 0; i < size; i++) {
624                 struct rgbvec *vec = &lut3d->lut[k][j][i];
625                 vec->r = k * c;
626                 vec->g = j * c;
627                 vec->b = i * c;
628             }
629         }
630     }
631 }
632
633 static int query_formats(AVFilterContext *ctx)
634 {
635     static const enum AVPixelFormat pix_fmts[] = {
636         AV_PIX_FMT_RGB24,  AV_PIX_FMT_BGR24,
637         AV_PIX_FMT_RGBA,   AV_PIX_FMT_BGRA,
638         AV_PIX_FMT_ARGB,   AV_PIX_FMT_ABGR,
639         AV_PIX_FMT_0RGB,   AV_PIX_FMT_0BGR,
640         AV_PIX_FMT_RGB0,   AV_PIX_FMT_BGR0,
641         AV_PIX_FMT_RGB48,  AV_PIX_FMT_BGR48,
642         AV_PIX_FMT_RGBA64, AV_PIX_FMT_BGRA64,
643         AV_PIX_FMT_GBRP,   AV_PIX_FMT_GBRAP,
644         AV_PIX_FMT_GBRP9,
645         AV_PIX_FMT_GBRP10, AV_PIX_FMT_GBRAP10,
646         AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRAP12,
647         AV_PIX_FMT_GBRP14,
648         AV_PIX_FMT_GBRP16, AV_PIX_FMT_GBRAP16,
649         AV_PIX_FMT_NONE
650     };
651     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
652     if (!fmts_list)
653         return AVERROR(ENOMEM);
654     return ff_set_common_formats(ctx, fmts_list);
655 }
656
657 static int config_input(AVFilterLink *inlink)
658 {
659     int depth, is16bit = 0, planar = 0;
660     LUT3DContext *lut3d = inlink->dst->priv;
661     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
662
663     depth = desc->comp[0].depth;
664
665     switch (inlink->format) {
666     case AV_PIX_FMT_RGB48:
667     case AV_PIX_FMT_BGR48:
668     case AV_PIX_FMT_RGBA64:
669     case AV_PIX_FMT_BGRA64:
670         is16bit = 1;
671         break;
672     case AV_PIX_FMT_GBRP9:
673     case AV_PIX_FMT_GBRP10:
674     case AV_PIX_FMT_GBRP12:
675     case AV_PIX_FMT_GBRP14:
676     case AV_PIX_FMT_GBRP16:
677     case AV_PIX_FMT_GBRAP10:
678     case AV_PIX_FMT_GBRAP12:
679     case AV_PIX_FMT_GBRAP16:
680         is16bit = 1;
681     case AV_PIX_FMT_GBRP:
682     case AV_PIX_FMT_GBRAP:
683         planar = 1;
684         break;
685     }
686
687     ff_fill_rgba_map(lut3d->rgba_map, inlink->format);
688     lut3d->step = av_get_padded_bits_per_pixel(desc) >> (3 + is16bit);
689
690 #define SET_FUNC(name) do {                                     \
691     if (planar) {                                               \
692         switch (depth) {                                        \
693         case  8: lut3d->interp = interp_8_##name##_p8;   break; \
694         case  9: lut3d->interp = interp_16_##name##_p9;  break; \
695         case 10: lut3d->interp = interp_16_##name##_p10; break; \
696         case 12: lut3d->interp = interp_16_##name##_p12; break; \
697         case 14: lut3d->interp = interp_16_##name##_p14; break; \
698         case 16: lut3d->interp = interp_16_##name##_p16; break; \
699         }                                                       \
700     } else if (is16bit) { lut3d->interp = interp_16_##name;     \
701     } else {       lut3d->interp = interp_8_##name; }           \
702 } while (0)
703
704     switch (lut3d->interpolation) {
705     case INTERPOLATE_NEAREST:     SET_FUNC(nearest);        break;
706     case INTERPOLATE_TRILINEAR:   SET_FUNC(trilinear);      break;
707     case INTERPOLATE_TETRAHEDRAL: SET_FUNC(tetrahedral);    break;
708     default:
709         av_assert0(0);
710     }
711
712     return 0;
713 }
714
715 static AVFrame *apply_lut(AVFilterLink *inlink, AVFrame *in)
716 {
717     AVFilterContext *ctx = inlink->dst;
718     LUT3DContext *lut3d = ctx->priv;
719     AVFilterLink *outlink = inlink->dst->outputs[0];
720     AVFrame *out;
721     ThreadData td;
722
723     if (av_frame_is_writable(in)) {
724         out = in;
725     } else {
726         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
727         if (!out) {
728             av_frame_free(&in);
729             return NULL;
730         }
731         av_frame_copy_props(out, in);
732     }
733
734     td.in  = in;
735     td.out = out;
736     ctx->internal->execute(ctx, lut3d->interp, &td, NULL, FFMIN(outlink->h, ff_filter_get_nb_threads(ctx)));
737
738     if (out != in)
739         av_frame_free(&in);
740
741     return out;
742 }
743
744 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
745 {
746     AVFilterLink *outlink = inlink->dst->outputs[0];
747     AVFrame *out = apply_lut(inlink, in);
748     if (!out)
749         return AVERROR(ENOMEM);
750     return ff_filter_frame(outlink, out);
751 }
752
753 #if CONFIG_LUT3D_FILTER
754 static const AVOption lut3d_options[] = {
755     { "file", "set 3D LUT file name", OFFSET(file), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
756     COMMON_OPTIONS
757 };
758
759 AVFILTER_DEFINE_CLASS(lut3d);
760
761 static av_cold int lut3d_init(AVFilterContext *ctx)
762 {
763     int ret;
764     FILE *f;
765     const char *ext;
766     LUT3DContext *lut3d = ctx->priv;
767
768     if (!lut3d->file) {
769         set_identity_matrix(lut3d, 32);
770         return 0;
771     }
772
773     f = fopen(lut3d->file, "r");
774     if (!f) {
775         ret = AVERROR(errno);
776         av_log(ctx, AV_LOG_ERROR, "%s: %s\n", lut3d->file, av_err2str(ret));
777         return ret;
778     }
779
780     ext = strrchr(lut3d->file, '.');
781     if (!ext) {
782         av_log(ctx, AV_LOG_ERROR, "Unable to guess the format from the extension\n");
783         ret = AVERROR_INVALIDDATA;
784         goto end;
785     }
786     ext++;
787
788     if (!av_strcasecmp(ext, "dat")) {
789         ret = parse_dat(ctx, f);
790     } else if (!av_strcasecmp(ext, "3dl")) {
791         ret = parse_3dl(ctx, f);
792     } else if (!av_strcasecmp(ext, "cube")) {
793         ret = parse_cube(ctx, f);
794     } else if (!av_strcasecmp(ext, "m3d")) {
795         ret = parse_m3d(ctx, f);
796     } else if (!av_strcasecmp(ext, "csp")) {
797         ret = parse_cinespace(ctx, f);
798     } else {
799         av_log(ctx, AV_LOG_ERROR, "Unrecognized '.%s' file type\n", ext);
800         ret = AVERROR(EINVAL);
801     }
802
803     if (!ret && !lut3d->lutsize) {
804         av_log(ctx, AV_LOG_ERROR, "3D LUT is empty\n");
805         ret = AVERROR_INVALIDDATA;
806     }
807
808 end:
809     fclose(f);
810     return ret;
811 }
812
813 static const AVFilterPad lut3d_inputs[] = {
814     {
815         .name         = "default",
816         .type         = AVMEDIA_TYPE_VIDEO,
817         .filter_frame = filter_frame,
818         .config_props = config_input,
819     },
820     { NULL }
821 };
822
823 static const AVFilterPad lut3d_outputs[] = {
824     {
825         .name = "default",
826         .type = AVMEDIA_TYPE_VIDEO,
827     },
828     { NULL }
829 };
830
831 AVFilter ff_vf_lut3d = {
832     .name          = "lut3d",
833     .description   = NULL_IF_CONFIG_SMALL("Adjust colors using a 3D LUT."),
834     .priv_size     = sizeof(LUT3DContext),
835     .init          = lut3d_init,
836     .query_formats = query_formats,
837     .inputs        = lut3d_inputs,
838     .outputs       = lut3d_outputs,
839     .priv_class    = &lut3d_class,
840     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS,
841 };
842 #endif
843
844 #if CONFIG_HALDCLUT_FILTER
845
846 static void update_clut_packed(LUT3DContext *lut3d, const AVFrame *frame)
847 {
848     const uint8_t *data = frame->data[0];
849     const int linesize  = frame->linesize[0];
850     const int w = lut3d->clut_width;
851     const int step = lut3d->clut_step;
852     const uint8_t *rgba_map = lut3d->clut_rgba_map;
853     const int level = lut3d->lutsize;
854
855 #define LOAD_CLUT(nbits) do {                                           \
856     int i, j, k, x = 0, y = 0;                                          \
857                                                                         \
858     for (k = 0; k < level; k++) {                                       \
859         for (j = 0; j < level; j++) {                                   \
860             for (i = 0; i < level; i++) {                               \
861                 const uint##nbits##_t *src = (const uint##nbits##_t *)  \
862                     (data + y*linesize + x*step);                       \
863                 struct rgbvec *vec = &lut3d->lut[i][j][k];              \
864                 vec->r = src[rgba_map[0]] / (float)((1<<(nbits)) - 1);  \
865                 vec->g = src[rgba_map[1]] / (float)((1<<(nbits)) - 1);  \
866                 vec->b = src[rgba_map[2]] / (float)((1<<(nbits)) - 1);  \
867                 if (++x == w) {                                         \
868                     x = 0;                                              \
869                     y++;                                                \
870                 }                                                       \
871             }                                                           \
872         }                                                               \
873     }                                                                   \
874 } while (0)
875
876     switch (lut3d->clut_bits) {
877     case  8: LOAD_CLUT(8);  break;
878     case 16: LOAD_CLUT(16); break;
879     }
880 }
881
882 static void update_clut_planar(LUT3DContext *lut3d, const AVFrame *frame)
883 {
884     const uint8_t *datag = frame->data[0];
885     const uint8_t *datab = frame->data[1];
886     const uint8_t *datar = frame->data[2];
887     const int glinesize  = frame->linesize[0];
888     const int blinesize  = frame->linesize[1];
889     const int rlinesize  = frame->linesize[2];
890     const int w = lut3d->clut_width;
891     const int level = lut3d->lutsize;
892
893 #define LOAD_CLUT_PLANAR(nbits, depth) do {                             \
894     int i, j, k, x = 0, y = 0;                                          \
895                                                                         \
896     for (k = 0; k < level; k++) {                                       \
897         for (j = 0; j < level; j++) {                                   \
898             for (i = 0; i < level; i++) {                               \
899                 const uint##nbits##_t *gsrc = (const uint##nbits##_t *) \
900                     (datag + y*glinesize);                              \
901                 const uint##nbits##_t *bsrc = (const uint##nbits##_t *) \
902                     (datab + y*blinesize);                              \
903                 const uint##nbits##_t *rsrc = (const uint##nbits##_t *) \
904                     (datar + y*rlinesize);                              \
905                 struct rgbvec *vec = &lut3d->lut[i][j][k];              \
906                 vec->r = gsrc[x] / (float)((1<<(depth)) - 1);           \
907                 vec->g = bsrc[x] / (float)((1<<(depth)) - 1);           \
908                 vec->b = rsrc[x] / (float)((1<<(depth)) - 1);           \
909                 if (++x == w) {                                         \
910                     x = 0;                                              \
911                     y++;                                                \
912                 }                                                       \
913             }                                                           \
914         }                                                               \
915     }                                                                   \
916 } while (0)
917
918     switch (lut3d->clut_bits) {
919     case  8: LOAD_CLUT_PLANAR(8, 8);   break;
920     case  9: LOAD_CLUT_PLANAR(16, 9);  break;
921     case 10: LOAD_CLUT_PLANAR(16, 10); break;
922     case 12: LOAD_CLUT_PLANAR(16, 12); break;
923     case 14: LOAD_CLUT_PLANAR(16, 14); break;
924     case 16: LOAD_CLUT_PLANAR(16, 16); break;
925     }
926 }
927
928 static int config_output(AVFilterLink *outlink)
929 {
930     AVFilterContext *ctx = outlink->src;
931     LUT3DContext *lut3d = ctx->priv;
932     int ret;
933
934     ret = ff_framesync_init_dualinput(&lut3d->fs, ctx);
935     if (ret < 0)
936         return ret;
937     outlink->w = ctx->inputs[0]->w;
938     outlink->h = ctx->inputs[0]->h;
939     outlink->time_base = ctx->inputs[0]->time_base;
940     if ((ret = ff_framesync_configure(&lut3d->fs)) < 0)
941         return ret;
942     return 0;
943 }
944
945 static int activate(AVFilterContext *ctx)
946 {
947     LUT3DContext *s = ctx->priv;
948     return ff_framesync_activate(&s->fs);
949 }
950
951 static int config_clut(AVFilterLink *inlink)
952 {
953     int size, level, w, h;
954     AVFilterContext *ctx = inlink->dst;
955     LUT3DContext *lut3d = ctx->priv;
956     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
957
958     av_assert0(desc);
959
960     lut3d->clut_bits = desc->comp[0].depth;
961     lut3d->clut_planar = av_pix_fmt_count_planes(inlink->format) > 1;
962
963     lut3d->clut_step = av_get_padded_bits_per_pixel(desc) >> 3;
964     ff_fill_rgba_map(lut3d->clut_rgba_map, inlink->format);
965
966     if (inlink->w > inlink->h)
967         av_log(ctx, AV_LOG_INFO, "Padding on the right (%dpx) of the "
968                "Hald CLUT will be ignored\n", inlink->w - inlink->h);
969     else if (inlink->w < inlink->h)
970         av_log(ctx, AV_LOG_INFO, "Padding at the bottom (%dpx) of the "
971                "Hald CLUT will be ignored\n", inlink->h - inlink->w);
972     lut3d->clut_width = w = h = FFMIN(inlink->w, inlink->h);
973
974     for (level = 1; level*level*level < w; level++);
975     size = level*level*level;
976     if (size != w) {
977         av_log(ctx, AV_LOG_WARNING, "The Hald CLUT width does not match the level\n");
978         return AVERROR_INVALIDDATA;
979     }
980     av_assert0(w == h && w == size);
981     level *= level;
982     if (level > MAX_LEVEL) {
983         const int max_clut_level = sqrt(MAX_LEVEL);
984         const int max_clut_size  = max_clut_level*max_clut_level*max_clut_level;
985         av_log(ctx, AV_LOG_ERROR, "Too large Hald CLUT "
986                "(maximum level is %d, or %dx%d CLUT)\n",
987                max_clut_level, max_clut_size, max_clut_size);
988         return AVERROR(EINVAL);
989     }
990     lut3d->lutsize = level;
991
992     return 0;
993 }
994
995 static int update_apply_clut(FFFrameSync *fs)
996 {
997     AVFilterContext *ctx = fs->parent;
998     LUT3DContext *lut3d = ctx->priv;
999     AVFilterLink *inlink = ctx->inputs[0];
1000     AVFrame *master, *second, *out;
1001     int ret;
1002
1003     ret = ff_framesync_dualinput_get(fs, &master, &second);
1004     if (ret < 0)
1005         return ret;
1006     if (!second)
1007         return ff_filter_frame(ctx->outputs[0], master);
1008     if (lut3d->clut_planar)
1009         update_clut_planar(ctx->priv, second);
1010     else
1011         update_clut_packed(ctx->priv, second);
1012     out = apply_lut(inlink, master);
1013     return ff_filter_frame(ctx->outputs[0], out);
1014 }
1015
1016 static av_cold int haldclut_init(AVFilterContext *ctx)
1017 {
1018     LUT3DContext *lut3d = ctx->priv;
1019     lut3d->fs.on_event = update_apply_clut;
1020     return 0;
1021 }
1022
1023 static av_cold void haldclut_uninit(AVFilterContext *ctx)
1024 {
1025     LUT3DContext *lut3d = ctx->priv;
1026     ff_framesync_uninit(&lut3d->fs);
1027 }
1028
1029 static const AVOption haldclut_options[] = {
1030     COMMON_OPTIONS
1031 };
1032
1033 FRAMESYNC_DEFINE_CLASS(haldclut, LUT3DContext, fs);
1034
1035 static const AVFilterPad haldclut_inputs[] = {
1036     {
1037         .name         = "main",
1038         .type         = AVMEDIA_TYPE_VIDEO,
1039         .config_props = config_input,
1040     },{
1041         .name         = "clut",
1042         .type         = AVMEDIA_TYPE_VIDEO,
1043         .config_props = config_clut,
1044     },
1045     { NULL }
1046 };
1047
1048 static const AVFilterPad haldclut_outputs[] = {
1049     {
1050         .name          = "default",
1051         .type          = AVMEDIA_TYPE_VIDEO,
1052         .config_props  = config_output,
1053     },
1054     { NULL }
1055 };
1056
1057 AVFilter ff_vf_haldclut = {
1058     .name          = "haldclut",
1059     .description   = NULL_IF_CONFIG_SMALL("Adjust colors using a Hald CLUT."),
1060     .priv_size     = sizeof(LUT3DContext),
1061     .preinit       = haldclut_framesync_preinit,
1062     .init          = haldclut_init,
1063     .uninit        = haldclut_uninit,
1064     .query_formats = query_formats,
1065     .activate      = activate,
1066     .inputs        = haldclut_inputs,
1067     .outputs       = haldclut_outputs,
1068     .priv_class    = &haldclut_class,
1069     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL | AVFILTER_FLAG_SLICE_THREADS,
1070 };
1071 #endif
1072
1073 #if CONFIG_LUT1D_FILTER
1074
1075 enum interp_1d_mode {
1076     INTERPOLATE_1D_NEAREST,
1077     INTERPOLATE_1D_LINEAR,
1078     INTERPOLATE_1D_CUBIC,
1079     INTERPOLATE_1D_COSINE,
1080     INTERPOLATE_1D_SPLINE,
1081     NB_INTERP_1D_MODE
1082 };
1083
1084 #define MAX_1D_LEVEL 65536
1085
1086 typedef struct LUT1DContext {
1087     const AVClass *class;
1088     char *file;
1089     int interpolation;          ///<interp_1d_mode
1090     uint8_t rgba_map[4];
1091     int step;
1092     float lut[3][MAX_1D_LEVEL];
1093     int lutsize;
1094     avfilter_action_func *interp;
1095 } LUT1DContext;
1096
1097 #undef OFFSET
1098 #define OFFSET(x) offsetof(LUT1DContext, x)
1099
1100 static void set_identity_matrix_1d(LUT1DContext *lut1d, int size)
1101 {
1102     const float c = 1. / (size - 1);
1103     int i;
1104
1105     lut1d->lutsize = size;
1106     for (i = 0; i < size; i++) {
1107         lut1d->lut[0][i] = i * c;
1108         lut1d->lut[1][i] = i * c;
1109         lut1d->lut[2][i] = i * c;
1110     }
1111 }
1112
1113 static int parse_cinespace_1d(AVFilterContext *ctx, FILE *f)
1114 {
1115     LUT1DContext *lut1d = ctx->priv;
1116     char line[MAX_LINE_SIZE];
1117     float in_min[3]  = {0.0, 0.0, 0.0};
1118     float in_max[3]  = {1.0, 1.0, 1.0};
1119     float out_min[3] = {0.0, 0.0, 0.0};
1120     float out_max[3] = {1.0, 1.0, 1.0};
1121     int inside_metadata = 0, size;
1122
1123     NEXT_LINE(skip_line(line));
1124     if (strncmp(line, "CSPLUTV100", 10)) {
1125         av_log(ctx, AV_LOG_ERROR, "Not cineSpace LUT format\n");
1126         return AVERROR(EINVAL);
1127     }
1128
1129     NEXT_LINE(skip_line(line));
1130     if (strncmp(line, "1D", 2)) {
1131         av_log(ctx, AV_LOG_ERROR, "Not 1D LUT format\n");
1132         return AVERROR(EINVAL);
1133     }
1134
1135     while (1) {
1136         NEXT_LINE(skip_line(line));
1137
1138         if (!strncmp(line, "BEGIN METADATA", 14)) {
1139             inside_metadata = 1;
1140             continue;
1141         }
1142         if (!strncmp(line, "END METADATA", 12)) {
1143             inside_metadata = 0;
1144             continue;
1145         }
1146         if (inside_metadata == 0) {
1147             for (int i = 0; i < 3; i++) {
1148                 int npoints = strtol(line, NULL, 0);
1149
1150                 if (npoints != 2) {
1151                     av_log(ctx, AV_LOG_ERROR, "Unsupported number of pre-lut points.\n");
1152                     return AVERROR_PATCHWELCOME;
1153                 }
1154
1155                 NEXT_LINE(skip_line(line));
1156                 if (av_sscanf(line, "%f %f", &in_min[i], &in_max[i]) != 2)
1157                     return AVERROR_INVALIDDATA;
1158                 NEXT_LINE(skip_line(line));
1159                 if (av_sscanf(line, "%f %f", &out_min[i], &out_max[i]) != 2)
1160                     return AVERROR_INVALIDDATA;
1161                 NEXT_LINE(skip_line(line));
1162             }
1163
1164             size = strtol(line, NULL, 0);
1165
1166             if (size < 2 || size > MAX_1D_LEVEL) {
1167                 av_log(ctx, AV_LOG_ERROR, "Too large or invalid 1D LUT size\n");
1168                 return AVERROR(EINVAL);
1169             }
1170
1171             lut1d->lutsize = size;
1172
1173             for (int i = 0; i < size; i++) {
1174                 NEXT_LINE(skip_line(line));
1175                 if (av_sscanf(line, "%f %f %f", &lut1d->lut[0][i], &lut1d->lut[1][i], &lut1d->lut[2][i]) != 3)
1176                     return AVERROR_INVALIDDATA;
1177                 lut1d->lut[0][i] *= out_max[0] - out_min[0];
1178                 lut1d->lut[1][i] *= out_max[1] - out_min[1];
1179                 lut1d->lut[2][i] *= out_max[2] - out_min[2];
1180             }
1181
1182             break;
1183         }
1184     }
1185     return 0;
1186 }
1187
1188 static int parse_cube_1d(AVFilterContext *ctx, FILE *f)
1189 {
1190     LUT1DContext *lut1d = ctx->priv;
1191     char line[MAX_LINE_SIZE];
1192     float min[3] = {0.0, 0.0, 0.0};
1193     float max[3] = {1.0, 1.0, 1.0};
1194
1195     while (fgets(line, sizeof(line), f)) {
1196         if (!strncmp(line, "LUT_1D_SIZE", 11)) {
1197             const int size = strtol(line + 12, NULL, 0);
1198             int i;
1199
1200             if (size < 2 || size > MAX_1D_LEVEL) {
1201                 av_log(ctx, AV_LOG_ERROR, "Too large or invalid 1D LUT size\n");
1202                 return AVERROR(EINVAL);
1203             }
1204             lut1d->lutsize = size;
1205             for (i = 0; i < size; i++) {
1206                 do {
1207 try_again:
1208                     NEXT_LINE(0);
1209                     if (!strncmp(line, "DOMAIN_", 7)) {
1210                         float *vals = NULL;
1211                         if      (!strncmp(line + 7, "MIN ", 4)) vals = min;
1212                         else if (!strncmp(line + 7, "MAX ", 4)) vals = max;
1213                         if (!vals)
1214                             return AVERROR_INVALIDDATA;
1215                         av_sscanf(line + 11, "%f %f %f", vals, vals + 1, vals + 2);
1216                         av_log(ctx, AV_LOG_DEBUG, "min: %f %f %f | max: %f %f %f\n",
1217                                min[0], min[1], min[2], max[0], max[1], max[2]);
1218                         goto try_again;
1219                     } else if (!strncmp(line, "LUT_1D_INPUT_RANGE ", 19)) {
1220                         av_sscanf(line + 19, "%f %f", min, max);
1221                         min[1] = min[2] = min[0];
1222                         max[1] = max[2] = max[0];
1223                         goto try_again;
1224                     } else if (!strncmp(line, "TITLE", 5)) {
1225                         goto try_again;
1226                     }
1227                 } while (skip_line(line));
1228                 if (av_sscanf(line, "%f %f %f", &lut1d->lut[0][i], &lut1d->lut[1][i], &lut1d->lut[2][i]) != 3)
1229                     return AVERROR_INVALIDDATA;
1230                 lut1d->lut[0][i] *= max[0] - min[0];
1231                 lut1d->lut[1][i] *= max[1] - min[1];
1232                 lut1d->lut[2][i] *= max[2] - min[2];
1233             }
1234             break;
1235         }
1236     }
1237     return 0;
1238 }
1239
1240 static const AVOption lut1d_options[] = {
1241     { "file", "set 1D LUT file name", OFFSET(file), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
1242     { "interp", "select interpolation mode", OFFSET(interpolation),    AV_OPT_TYPE_INT, {.i64=INTERPOLATE_1D_LINEAR}, 0, NB_INTERP_1D_MODE-1, FLAGS, "interp_mode" },
1243         { "nearest", "use values from the nearest defined points", 0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_1D_NEAREST},   INT_MIN, INT_MAX, FLAGS, "interp_mode" },
1244         { "linear",  "use values from the linear interpolation",   0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_1D_LINEAR},    INT_MIN, INT_MAX, FLAGS, "interp_mode" },
1245         { "cosine",  "use values from the cosine interpolation",   0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_1D_COSINE},    INT_MIN, INT_MAX, FLAGS, "interp_mode" },
1246         { "cubic",   "use values from the cubic interpolation",    0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_1D_CUBIC},     INT_MIN, INT_MAX, FLAGS, "interp_mode" },
1247         { "spline",  "use values from the spline interpolation",   0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_1D_SPLINE},    INT_MIN, INT_MAX, FLAGS, "interp_mode" },
1248     { NULL }
1249 };
1250
1251 AVFILTER_DEFINE_CLASS(lut1d);
1252
1253 static inline float interp_1d_nearest(const LUT1DContext *lut1d,
1254                                       int idx, const float s)
1255 {
1256     return lut1d->lut[idx][NEAR(s)];
1257 }
1258
1259 #define NEXT1D(x) (FFMIN((int)(x) + 1, lut1d->lutsize - 1))
1260
1261 static inline float interp_1d_linear(const LUT1DContext *lut1d,
1262                                      int idx, const float s)
1263 {
1264     const int prev = PREV(s);
1265     const int next = NEXT1D(s);
1266     const float d = s - prev;
1267     const float p = lut1d->lut[idx][prev];
1268     const float n = lut1d->lut[idx][next];
1269
1270     return lerpf(p, n, d);
1271 }
1272
1273 static inline float interp_1d_cosine(const LUT1DContext *lut1d,
1274                                      int idx, const float s)
1275 {
1276     const int prev = PREV(s);
1277     const int next = NEXT1D(s);
1278     const float d = s - prev;
1279     const float p = lut1d->lut[idx][prev];
1280     const float n = lut1d->lut[idx][next];
1281     const float m = (1.f - cosf(d * M_PI)) * .5f;
1282
1283     return lerpf(p, n, m);
1284 }
1285
1286 static inline float interp_1d_cubic(const LUT1DContext *lut1d,
1287                                     int idx, const float s)
1288 {
1289     const int prev = PREV(s);
1290     const int next = NEXT1D(s);
1291     const float mu = s - prev;
1292     float a0, a1, a2, a3, mu2;
1293
1294     float y0 = lut1d->lut[idx][FFMAX(prev - 1, 0)];
1295     float y1 = lut1d->lut[idx][prev];
1296     float y2 = lut1d->lut[idx][next];
1297     float y3 = lut1d->lut[idx][FFMIN(next + 1, lut1d->lutsize - 1)];
1298
1299
1300     mu2 = mu * mu;
1301     a0 = y3 - y2 - y0 + y1;
1302     a1 = y0 - y1 - a0;
1303     a2 = y2 - y0;
1304     a3 = y1;
1305
1306     return a0 * mu * mu2 + a1 * mu2 + a2 * mu + a3;
1307 }
1308
1309 static inline float interp_1d_spline(const LUT1DContext *lut1d,
1310                                      int idx, const float s)
1311 {
1312     const int prev = PREV(s);
1313     const int next = NEXT1D(s);
1314     const float x = s - prev;
1315     float c0, c1, c2, c3;
1316
1317     float y0 = lut1d->lut[idx][FFMAX(prev - 1, 0)];
1318     float y1 = lut1d->lut[idx][prev];
1319     float y2 = lut1d->lut[idx][next];
1320     float y3 = lut1d->lut[idx][FFMIN(next + 1, lut1d->lutsize - 1)];
1321
1322     c0 = y1;
1323     c1 = .5f * (y2 - y0);
1324     c2 = y0 - 2.5f * y1 + 2.f * y2 - .5f * y3;
1325     c3 = .5f * (y3 - y0) + 1.5f * (y1 - y2);
1326
1327     return ((c3 * x + c2) * x + c1) * x + c0;
1328 }
1329
1330 #define DEFINE_INTERP_FUNC_PLANAR_1D(name, nbits, depth)                     \
1331 static int interp_1d_##nbits##_##name##_p##depth(AVFilterContext *ctx,       \
1332                                                  void *arg, int jobnr,       \
1333                                                  int nb_jobs)                \
1334 {                                                                            \
1335     int x, y;                                                                \
1336     const LUT1DContext *lut1d = ctx->priv;                                   \
1337     const ThreadData *td = arg;                                              \
1338     const AVFrame *in  = td->in;                                             \
1339     const AVFrame *out = td->out;                                            \
1340     const int direct = out == in;                                            \
1341     const int slice_start = (in->height *  jobnr   ) / nb_jobs;              \
1342     const int slice_end   = (in->height * (jobnr+1)) / nb_jobs;              \
1343     uint8_t *grow = out->data[0] + slice_start * out->linesize[0];           \
1344     uint8_t *brow = out->data[1] + slice_start * out->linesize[1];           \
1345     uint8_t *rrow = out->data[2] + slice_start * out->linesize[2];           \
1346     uint8_t *arow = out->data[3] + slice_start * out->linesize[3];           \
1347     const uint8_t *srcgrow = in->data[0] + slice_start * in->linesize[0];    \
1348     const uint8_t *srcbrow = in->data[1] + slice_start * in->linesize[1];    \
1349     const uint8_t *srcrrow = in->data[2] + slice_start * in->linesize[2];    \
1350     const uint8_t *srcarow = in->data[3] + slice_start * in->linesize[3];    \
1351     const float factor = (1 << depth) - 1;                                   \
1352     const float scale = (1. / factor) * (lut1d->lutsize - 1);                \
1353                                                                              \
1354     for (y = slice_start; y < slice_end; y++) {                              \
1355         uint##nbits##_t *dstg = (uint##nbits##_t *)grow;                     \
1356         uint##nbits##_t *dstb = (uint##nbits##_t *)brow;                     \
1357         uint##nbits##_t *dstr = (uint##nbits##_t *)rrow;                     \
1358         uint##nbits##_t *dsta = (uint##nbits##_t *)arow;                     \
1359         const uint##nbits##_t *srcg = (const uint##nbits##_t *)srcgrow;      \
1360         const uint##nbits##_t *srcb = (const uint##nbits##_t *)srcbrow;      \
1361         const uint##nbits##_t *srcr = (const uint##nbits##_t *)srcrrow;      \
1362         const uint##nbits##_t *srca = (const uint##nbits##_t *)srcarow;      \
1363         for (x = 0; x < in->width; x++) {                                    \
1364             float r = srcr[x] * scale;                                       \
1365             float g = srcg[x] * scale;                                       \
1366             float b = srcb[x] * scale;                                       \
1367             r = interp_1d_##name(lut1d, 0, r);                               \
1368             g = interp_1d_##name(lut1d, 1, g);                               \
1369             b = interp_1d_##name(lut1d, 2, b);                               \
1370             dstr[x] = av_clip_uintp2(r * factor, depth);                     \
1371             dstg[x] = av_clip_uintp2(g * factor, depth);                     \
1372             dstb[x] = av_clip_uintp2(b * factor, depth);                     \
1373             if (!direct && in->linesize[3])                                  \
1374                 dsta[x] = srca[x];                                           \
1375         }                                                                    \
1376         grow += out->linesize[0];                                            \
1377         brow += out->linesize[1];                                            \
1378         rrow += out->linesize[2];                                            \
1379         arow += out->linesize[3];                                            \
1380         srcgrow += in->linesize[0];                                          \
1381         srcbrow += in->linesize[1];                                          \
1382         srcrrow += in->linesize[2];                                          \
1383         srcarow += in->linesize[3];                                          \
1384     }                                                                        \
1385     return 0;                                                                \
1386 }
1387
1388 DEFINE_INTERP_FUNC_PLANAR_1D(nearest,     8, 8)
1389 DEFINE_INTERP_FUNC_PLANAR_1D(linear,      8, 8)
1390 DEFINE_INTERP_FUNC_PLANAR_1D(cosine,      8, 8)
1391 DEFINE_INTERP_FUNC_PLANAR_1D(cubic,       8, 8)
1392 DEFINE_INTERP_FUNC_PLANAR_1D(spline,      8, 8)
1393
1394 DEFINE_INTERP_FUNC_PLANAR_1D(nearest,     16, 9)
1395 DEFINE_INTERP_FUNC_PLANAR_1D(linear,      16, 9)
1396 DEFINE_INTERP_FUNC_PLANAR_1D(cosine,      16, 9)
1397 DEFINE_INTERP_FUNC_PLANAR_1D(cubic,       16, 9)
1398 DEFINE_INTERP_FUNC_PLANAR_1D(spline,      16, 9)
1399
1400 DEFINE_INTERP_FUNC_PLANAR_1D(nearest,     16, 10)
1401 DEFINE_INTERP_FUNC_PLANAR_1D(linear,      16, 10)
1402 DEFINE_INTERP_FUNC_PLANAR_1D(cosine,      16, 10)
1403 DEFINE_INTERP_FUNC_PLANAR_1D(cubic,       16, 10)
1404 DEFINE_INTERP_FUNC_PLANAR_1D(spline,      16, 10)
1405
1406 DEFINE_INTERP_FUNC_PLANAR_1D(nearest,     16, 12)
1407 DEFINE_INTERP_FUNC_PLANAR_1D(linear,      16, 12)
1408 DEFINE_INTERP_FUNC_PLANAR_1D(cosine,      16, 12)
1409 DEFINE_INTERP_FUNC_PLANAR_1D(cubic,       16, 12)
1410 DEFINE_INTERP_FUNC_PLANAR_1D(spline,      16, 12)
1411
1412 DEFINE_INTERP_FUNC_PLANAR_1D(nearest,     16, 14)
1413 DEFINE_INTERP_FUNC_PLANAR_1D(linear,      16, 14)
1414 DEFINE_INTERP_FUNC_PLANAR_1D(cosine,      16, 14)
1415 DEFINE_INTERP_FUNC_PLANAR_1D(cubic,       16, 14)
1416 DEFINE_INTERP_FUNC_PLANAR_1D(spline,      16, 14)
1417
1418 DEFINE_INTERP_FUNC_PLANAR_1D(nearest,     16, 16)
1419 DEFINE_INTERP_FUNC_PLANAR_1D(linear,      16, 16)
1420 DEFINE_INTERP_FUNC_PLANAR_1D(cosine,      16, 16)
1421 DEFINE_INTERP_FUNC_PLANAR_1D(cubic,       16, 16)
1422 DEFINE_INTERP_FUNC_PLANAR_1D(spline,      16, 16)
1423
1424 #define DEFINE_INTERP_FUNC_1D(name, nbits)                                   \
1425 static int interp_1d_##nbits##_##name(AVFilterContext *ctx, void *arg,       \
1426                                       int jobnr, int nb_jobs)                \
1427 {                                                                            \
1428     int x, y;                                                                \
1429     const LUT1DContext *lut1d = ctx->priv;                                   \
1430     const ThreadData *td = arg;                                              \
1431     const AVFrame *in  = td->in;                                             \
1432     const AVFrame *out = td->out;                                            \
1433     const int direct = out == in;                                            \
1434     const int step = lut1d->step;                                            \
1435     const uint8_t r = lut1d->rgba_map[R];                                    \
1436     const uint8_t g = lut1d->rgba_map[G];                                    \
1437     const uint8_t b = lut1d->rgba_map[B];                                    \
1438     const uint8_t a = lut1d->rgba_map[A];                                    \
1439     const int slice_start = (in->height *  jobnr   ) / nb_jobs;              \
1440     const int slice_end   = (in->height * (jobnr+1)) / nb_jobs;              \
1441     uint8_t       *dstrow = out->data[0] + slice_start * out->linesize[0];   \
1442     const uint8_t *srcrow = in ->data[0] + slice_start * in ->linesize[0];   \
1443     const float factor = (1 << nbits) - 1;                                   \
1444     const float scale = (1. / factor) * (lut1d->lutsize - 1);                \
1445                                                                              \
1446     for (y = slice_start; y < slice_end; y++) {                              \
1447         uint##nbits##_t *dst = (uint##nbits##_t *)dstrow;                    \
1448         const uint##nbits##_t *src = (const uint##nbits##_t *)srcrow;        \
1449         for (x = 0; x < in->width * step; x += step) {                       \
1450             float rr = src[x + r] * scale;                                   \
1451             float gg = src[x + g] * scale;                                   \
1452             float bb = src[x + b] * scale;                                   \
1453             rr = interp_1d_##name(lut1d, 0, rr);                             \
1454             gg = interp_1d_##name(lut1d, 1, gg);                             \
1455             bb = interp_1d_##name(lut1d, 2, bb);                             \
1456             dst[x + r] = av_clip_uint##nbits(rr * factor);                   \
1457             dst[x + g] = av_clip_uint##nbits(gg * factor);                   \
1458             dst[x + b] = av_clip_uint##nbits(bb * factor);                   \
1459             if (!direct && step == 4)                                        \
1460                 dst[x + a] = src[x + a];                                     \
1461         }                                                                    \
1462         dstrow += out->linesize[0];                                          \
1463         srcrow += in ->linesize[0];                                          \
1464     }                                                                        \
1465     return 0;                                                                \
1466 }
1467
1468 DEFINE_INTERP_FUNC_1D(nearest,     8)
1469 DEFINE_INTERP_FUNC_1D(linear,      8)
1470 DEFINE_INTERP_FUNC_1D(cosine,      8)
1471 DEFINE_INTERP_FUNC_1D(cubic,       8)
1472 DEFINE_INTERP_FUNC_1D(spline,      8)
1473
1474 DEFINE_INTERP_FUNC_1D(nearest,     16)
1475 DEFINE_INTERP_FUNC_1D(linear,      16)
1476 DEFINE_INTERP_FUNC_1D(cosine,      16)
1477 DEFINE_INTERP_FUNC_1D(cubic,       16)
1478 DEFINE_INTERP_FUNC_1D(spline,      16)
1479
1480 static int config_input_1d(AVFilterLink *inlink)
1481 {
1482     int depth, is16bit = 0, planar = 0;
1483     LUT1DContext *lut1d = inlink->dst->priv;
1484     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
1485
1486     depth = desc->comp[0].depth;
1487
1488     switch (inlink->format) {
1489     case AV_PIX_FMT_RGB48:
1490     case AV_PIX_FMT_BGR48:
1491     case AV_PIX_FMT_RGBA64:
1492     case AV_PIX_FMT_BGRA64:
1493         is16bit = 1;
1494         break;
1495     case AV_PIX_FMT_GBRP9:
1496     case AV_PIX_FMT_GBRP10:
1497     case AV_PIX_FMT_GBRP12:
1498     case AV_PIX_FMT_GBRP14:
1499     case AV_PIX_FMT_GBRP16:
1500     case AV_PIX_FMT_GBRAP10:
1501     case AV_PIX_FMT_GBRAP12:
1502     case AV_PIX_FMT_GBRAP16:
1503         is16bit = 1;
1504     case AV_PIX_FMT_GBRP:
1505     case AV_PIX_FMT_GBRAP:
1506         planar = 1;
1507         break;
1508     }
1509
1510     ff_fill_rgba_map(lut1d->rgba_map, inlink->format);
1511     lut1d->step = av_get_padded_bits_per_pixel(desc) >> (3 + is16bit);
1512
1513 #define SET_FUNC_1D(name) do {                                     \
1514     if (planar) {                                                  \
1515         switch (depth) {                                           \
1516         case  8: lut1d->interp = interp_1d_8_##name##_p8;   break; \
1517         case  9: lut1d->interp = interp_1d_16_##name##_p9;  break; \
1518         case 10: lut1d->interp = interp_1d_16_##name##_p10; break; \
1519         case 12: lut1d->interp = interp_1d_16_##name##_p12; break; \
1520         case 14: lut1d->interp = interp_1d_16_##name##_p14; break; \
1521         case 16: lut1d->interp = interp_1d_16_##name##_p16; break; \
1522         }                                                          \
1523     } else if (is16bit) { lut1d->interp = interp_1d_16_##name;     \
1524     } else {              lut1d->interp = interp_1d_8_##name; }    \
1525 } while (0)
1526
1527     switch (lut1d->interpolation) {
1528     case INTERPOLATE_1D_NEAREST:     SET_FUNC_1D(nearest);  break;
1529     case INTERPOLATE_1D_LINEAR:      SET_FUNC_1D(linear);   break;
1530     case INTERPOLATE_1D_COSINE:      SET_FUNC_1D(cosine);   break;
1531     case INTERPOLATE_1D_CUBIC:       SET_FUNC_1D(cubic);    break;
1532     case INTERPOLATE_1D_SPLINE:      SET_FUNC_1D(spline);   break;
1533     default:
1534         av_assert0(0);
1535     }
1536
1537     return 0;
1538 }
1539
1540 static av_cold int lut1d_init(AVFilterContext *ctx)
1541 {
1542     int ret;
1543     FILE *f;
1544     const char *ext;
1545     LUT1DContext *lut1d = ctx->priv;
1546
1547     if (!lut1d->file) {
1548         set_identity_matrix_1d(lut1d, 32);
1549         return 0;
1550     }
1551
1552     f = fopen(lut1d->file, "r");
1553     if (!f) {
1554         ret = AVERROR(errno);
1555         av_log(ctx, AV_LOG_ERROR, "%s: %s\n", lut1d->file, av_err2str(ret));
1556         return ret;
1557     }
1558
1559     ext = strrchr(lut1d->file, '.');
1560     if (!ext) {
1561         av_log(ctx, AV_LOG_ERROR, "Unable to guess the format from the extension\n");
1562         ret = AVERROR_INVALIDDATA;
1563         goto end;
1564     }
1565     ext++;
1566
1567     if (!av_strcasecmp(ext, "cube") || !av_strcasecmp(ext, "1dlut")) {
1568         ret = parse_cube_1d(ctx, f);
1569     } else if (!av_strcasecmp(ext, "csp")) {
1570         ret = parse_cinespace_1d(ctx, f);
1571     } else {
1572         av_log(ctx, AV_LOG_ERROR, "Unrecognized '.%s' file type\n", ext);
1573         ret = AVERROR(EINVAL);
1574     }
1575
1576     if (!ret && !lut1d->lutsize) {
1577         av_log(ctx, AV_LOG_ERROR, "1D LUT is empty\n");
1578         ret = AVERROR_INVALIDDATA;
1579     }
1580
1581 end:
1582     fclose(f);
1583     return ret;
1584 }
1585
1586 static AVFrame *apply_1d_lut(AVFilterLink *inlink, AVFrame *in)
1587 {
1588     AVFilterContext *ctx = inlink->dst;
1589     LUT1DContext *lut1d = ctx->priv;
1590     AVFilterLink *outlink = inlink->dst->outputs[0];
1591     AVFrame *out;
1592     ThreadData td;
1593
1594     if (av_frame_is_writable(in)) {
1595         out = in;
1596     } else {
1597         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
1598         if (!out) {
1599             av_frame_free(&in);
1600             return NULL;
1601         }
1602         av_frame_copy_props(out, in);
1603     }
1604
1605     td.in  = in;
1606     td.out = out;
1607     ctx->internal->execute(ctx, lut1d->interp, &td, NULL, FFMIN(outlink->h, ff_filter_get_nb_threads(ctx)));
1608
1609     if (out != in)
1610         av_frame_free(&in);
1611
1612     return out;
1613 }
1614
1615 static int filter_frame_1d(AVFilterLink *inlink, AVFrame *in)
1616 {
1617     AVFilterLink *outlink = inlink->dst->outputs[0];
1618     AVFrame *out = apply_1d_lut(inlink, in);
1619     if (!out)
1620         return AVERROR(ENOMEM);
1621     return ff_filter_frame(outlink, out);
1622 }
1623
1624 static const AVFilterPad lut1d_inputs[] = {
1625     {
1626         .name         = "default",
1627         .type         = AVMEDIA_TYPE_VIDEO,
1628         .filter_frame = filter_frame_1d,
1629         .config_props = config_input_1d,
1630     },
1631     { NULL }
1632 };
1633
1634 static const AVFilterPad lut1d_outputs[] = {
1635     {
1636         .name = "default",
1637         .type = AVMEDIA_TYPE_VIDEO,
1638     },
1639     { NULL }
1640 };
1641
1642 AVFilter ff_vf_lut1d = {
1643     .name          = "lut1d",
1644     .description   = NULL_IF_CONFIG_SMALL("Adjust colors using a 1D LUT."),
1645     .priv_size     = sizeof(LUT1DContext),
1646     .init          = lut1d_init,
1647     .query_formats = query_formats,
1648     .inputs        = lut1d_inputs,
1649     .outputs       = lut1d_outputs,
1650     .priv_class    = &lut1d_class,
1651     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS,
1652 };
1653 #endif