]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_lut3d.c
12eb15fe6715254d000671ccab070b510ae5ab23
[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 "float.h"
28
29 #include "libavutil/opt.h"
30 #include "libavutil/file.h"
31 #include "libavutil/intreadwrite.h"
32 #include "libavutil/intfloat.h"
33 #include "libavutil/avassert.h"
34 #include "libavutil/pixdesc.h"
35 #include "libavutil/avstring.h"
36 #include "avfilter.h"
37 #include "drawutils.h"
38 #include "formats.h"
39 #include "framesync.h"
40 #include "internal.h"
41 #include "video.h"
42
43 #define R 0
44 #define G 1
45 #define B 2
46 #define A 3
47
48 enum interp_mode {
49     INTERPOLATE_NEAREST,
50     INTERPOLATE_TRILINEAR,
51     INTERPOLATE_TETRAHEDRAL,
52     INTERPOLATE_PYRAMID,
53     NB_INTERP_MODE
54 };
55
56 struct rgbvec {
57     float r, g, b;
58 };
59
60 /* 3D LUT don't often go up to level 32, but it is common to have a Hald CLUT
61  * of 512x512 (64x64x64) */
62 #define MAX_LEVEL 256
63 #define PRELUT_SIZE 65536
64
65 typedef struct Lut3DPreLut {
66     int size;
67     float min[3];
68     float max[3];
69     float scale[3];
70     float* lut[3];
71 } Lut3DPreLut;
72
73 typedef struct LUT3DContext {
74     const AVClass *class;
75     int interpolation;          ///<interp_mode
76     char *file;
77     uint8_t rgba_map[4];
78     int step;
79     avfilter_action_func *interp;
80     struct rgbvec scale;
81     struct rgbvec *lut;
82     int lutsize;
83     int lutsize2;
84     Lut3DPreLut prelut;
85 #if CONFIG_HALDCLUT_FILTER
86     uint8_t clut_rgba_map[4];
87     int clut_step;
88     int clut_bits;
89     int clut_planar;
90     int clut_float;
91     int clut_width;
92     FFFrameSync fs;
93 #endif
94 } LUT3DContext;
95
96 typedef struct ThreadData {
97     AVFrame *in, *out;
98 } ThreadData;
99
100 #define OFFSET(x) offsetof(LUT3DContext, x)
101 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
102 #define COMMON_OPTIONS \
103     { "interp", "select interpolation mode", OFFSET(interpolation), AV_OPT_TYPE_INT, {.i64=INTERPOLATE_TETRAHEDRAL}, 0, NB_INTERP_MODE-1, FLAGS, "interp_mode" }, \
104         { "nearest",     "use values from the nearest defined points",            0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_NEAREST},     INT_MIN, INT_MAX, FLAGS, "interp_mode" }, \
105         { "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" }, \
106         { "tetrahedral", "interpolate values using a tetrahedron",                0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_TETRAHEDRAL}, INT_MIN, INT_MAX, FLAGS, "interp_mode" }, \
107         { "pyramid",     "interpolate values using a pyramid",                    0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_PYRAMID},     INT_MIN, INT_MAX, FLAGS, "interp_mode" }, \
108     { NULL }
109
110 #define EXPONENT_MASK 0x7F800000
111 #define MANTISSA_MASK 0x007FFFFF
112 #define SIGN_MASK     0x80000000
113
114 static inline float sanitizef(float f)
115 {
116     union av_intfloat32 t;
117     t.f = f;
118
119     if ((t.i & EXPONENT_MASK) == EXPONENT_MASK) {
120         if ((t.i & MANTISSA_MASK) != 0) {
121             // NAN
122             return 0.0f;
123         } else if (t.i & SIGN_MASK) {
124             // -INF
125             return -FLT_MAX;
126         } else {
127             // +INF
128             return FLT_MAX;
129         }
130     }
131     return f;
132 }
133
134 static inline float lerpf(float v0, float v1, float f)
135 {
136     return v0 + (v1 - v0) * f;
137 }
138
139 static inline struct rgbvec lerp(const struct rgbvec *v0, const struct rgbvec *v1, float f)
140 {
141     struct rgbvec v = {
142         lerpf(v0->r, v1->r, f), lerpf(v0->g, v1->g, f), lerpf(v0->b, v1->b, f)
143     };
144     return v;
145 }
146
147 #define NEAR(x) ((int)((x) + .5))
148 #define PREV(x) ((int)(x))
149 #define NEXT(x) (FFMIN((int)(x) + 1, lut3d->lutsize - 1))
150
151 /**
152  * Get the nearest defined point
153  */
154 static inline struct rgbvec interp_nearest(const LUT3DContext *lut3d,
155                                            const struct rgbvec *s)
156 {
157     return lut3d->lut[NEAR(s->r) * lut3d->lutsize2 + NEAR(s->g) * lut3d->lutsize + NEAR(s->b)];
158 }
159
160 /**
161  * Interpolate using the 8 vertices of a cube
162  * @see https://en.wikipedia.org/wiki/Trilinear_interpolation
163  */
164 static inline struct rgbvec interp_trilinear(const LUT3DContext *lut3d,
165                                              const struct rgbvec *s)
166 {
167     const int lutsize2 = lut3d->lutsize2;
168     const int lutsize  = lut3d->lutsize;
169     const int prev[] = {PREV(s->r), PREV(s->g), PREV(s->b)};
170     const int next[] = {NEXT(s->r), NEXT(s->g), NEXT(s->b)};
171     const struct rgbvec d = {s->r - prev[0], s->g - prev[1], s->b - prev[2]};
172     const struct rgbvec c000 = lut3d->lut[prev[0] * lutsize2 + prev[1] * lutsize + prev[2]];
173     const struct rgbvec c001 = lut3d->lut[prev[0] * lutsize2 + prev[1] * lutsize + next[2]];
174     const struct rgbvec c010 = lut3d->lut[prev[0] * lutsize2 + next[1] * lutsize + prev[2]];
175     const struct rgbvec c011 = lut3d->lut[prev[0] * lutsize2 + next[1] * lutsize + next[2]];
176     const struct rgbvec c100 = lut3d->lut[next[0] * lutsize2 + prev[1] * lutsize + prev[2]];
177     const struct rgbvec c101 = lut3d->lut[next[0] * lutsize2 + prev[1] * lutsize + next[2]];
178     const struct rgbvec c110 = lut3d->lut[next[0] * lutsize2 + next[1] * lutsize + prev[2]];
179     const struct rgbvec c111 = lut3d->lut[next[0] * lutsize2 + next[1] * lutsize + next[2]];
180     const struct rgbvec c00  = lerp(&c000, &c100, d.r);
181     const struct rgbvec c10  = lerp(&c010, &c110, d.r);
182     const struct rgbvec c01  = lerp(&c001, &c101, d.r);
183     const struct rgbvec c11  = lerp(&c011, &c111, d.r);
184     const struct rgbvec c0   = lerp(&c00,  &c10,  d.g);
185     const struct rgbvec c1   = lerp(&c01,  &c11,  d.g);
186     const struct rgbvec c    = lerp(&c0,   &c1,   d.b);
187     return c;
188 }
189
190 static inline struct rgbvec interp_pyramid(const LUT3DContext *lut3d,
191                                            const struct rgbvec *s)
192 {
193     const int lutsize2 = lut3d->lutsize2;
194     const int lutsize  = lut3d->lutsize;
195     const int prev[] = {PREV(s->r), PREV(s->g), PREV(s->b)};
196     const int next[] = {NEXT(s->r), NEXT(s->g), NEXT(s->b)};
197     const struct rgbvec d = {s->r - prev[0], s->g - prev[1], s->b - prev[2]};
198     const struct rgbvec c000 = lut3d->lut[prev[0] * lutsize2 + prev[1] * lutsize + prev[2]];
199     const struct rgbvec c111 = lut3d->lut[next[0] * lutsize2 + next[1] * lutsize + next[2]];
200     struct rgbvec c;
201
202     if (d.g > d.r && d.b > d.r) {
203         const struct rgbvec c001 = lut3d->lut[prev[0] * lutsize2 + prev[1] * lutsize + next[2]];
204         const struct rgbvec c010 = lut3d->lut[prev[0] * lutsize2 + next[1] * lutsize + prev[2]];
205         const struct rgbvec c011 = lut3d->lut[prev[0] * lutsize2 + next[1] * lutsize + next[2]];
206
207         c.r = c000.r + (c111.r - c011.r) * d.r + (c010.r - c000.r) * d.g + (c001.r - c000.r) * d.b +
208               (c011.r - c001.r - c010.r + c000.r) * d.g * d.b;
209         c.g = c000.g + (c111.g - c011.g) * d.r + (c010.g - c000.g) * d.g + (c001.g - c000.g) * d.b +
210               (c011.g - c001.g - c010.g + c000.g) * d.g * d.b;
211         c.b = c000.b + (c111.b - c011.b) * d.r + (c010.b - c000.b) * d.g + (c001.b - c000.b) * d.b +
212               (c011.b - c001.b - c010.b + c000.b) * d.g * d.b;
213     } else if (d.r > d.g && d.b > d.g) {
214         const struct rgbvec c001 = lut3d->lut[prev[0] * lutsize2 + prev[1] * lutsize + next[2]];
215         const struct rgbvec c100 = lut3d->lut[next[0] * lutsize2 + prev[1] * lutsize + prev[2]];
216         const struct rgbvec c101 = lut3d->lut[next[0] * lutsize2 + prev[1] * lutsize + next[2]];
217
218         c.r = c000.r + (c100.r - c000.r) * d.r + (c111.r - c101.r) * d.g + (c001.r - c000.r) * d.b +
219               (c101.r - c001.r - c100.r + c000.r) * d.r * d.b;
220         c.g = c000.g + (c100.g - c000.g) * d.r + (c111.g - c101.g) * d.g + (c001.g - c000.g) * d.b +
221               (c101.g - c001.g - c100.g + c000.g) * d.r * d.b;
222         c.b = c000.b + (c100.b - c000.b) * d.r + (c111.b - c101.b) * d.g + (c001.b - c000.b) * d.b +
223               (c101.b - c001.b - c100.b + c000.b) * d.r * d.b;
224     } else {
225         const struct rgbvec c010 = lut3d->lut[prev[0] * lutsize2 + next[1] * lutsize + prev[2]];
226         const struct rgbvec c110 = lut3d->lut[next[0] * lutsize2 + next[1] * lutsize + prev[2]];
227         const struct rgbvec c100 = lut3d->lut[next[0] * lutsize2 + prev[1] * lutsize + prev[2]];
228
229         c.r = c000.r + (c100.r - c000.r) * d.r + (c010.r - c000.r) * d.g + (c111.r - c110.r) * d.b +
230               (c110.r - c100.r - c010.r + c000.r) * d.r * d.g;
231         c.g = c000.g + (c100.g - c000.g) * d.r + (c010.g - c000.g) * d.g + (c111.g - c110.g) * d.b +
232               (c110.g - c100.g - c010.g + c000.g) * d.r * d.g;
233         c.b = c000.b + (c100.b - c000.b) * d.r + (c010.b - c000.b) * d.g + (c111.b - c110.b) * d.b +
234               (c110.b - c100.b - c010.b + c000.b) * d.r * d.g;
235     }
236
237     return c;
238 }
239
240 /**
241  * Tetrahedral interpolation. Based on code found in Truelight Software Library paper.
242  * @see http://www.filmlight.ltd.uk/pdf/whitepapers/FL-TL-TN-0057-SoftwareLib.pdf
243  */
244 static inline struct rgbvec interp_tetrahedral(const LUT3DContext *lut3d,
245                                                const struct rgbvec *s)
246 {
247     const int lutsize2 = lut3d->lutsize2;
248     const int lutsize  = lut3d->lutsize;
249     const int prev[] = {PREV(s->r), PREV(s->g), PREV(s->b)};
250     const int next[] = {NEXT(s->r), NEXT(s->g), NEXT(s->b)};
251     const struct rgbvec d = {s->r - prev[0], s->g - prev[1], s->b - prev[2]};
252     const struct rgbvec c000 = lut3d->lut[prev[0] * lutsize2 + prev[1] * lutsize + prev[2]];
253     const struct rgbvec c111 = lut3d->lut[next[0] * lutsize2 + next[1] * lutsize + next[2]];
254     struct rgbvec c;
255     if (d.r > d.g) {
256         if (d.g > d.b) {
257             const struct rgbvec c100 = lut3d->lut[next[0] * lutsize2 + prev[1] * lutsize + prev[2]];
258             const struct rgbvec c110 = lut3d->lut[next[0] * lutsize2 + next[1] * lutsize + prev[2]];
259             c.r = (1-d.r) * c000.r + (d.r-d.g) * c100.r + (d.g-d.b) * c110.r + (d.b) * c111.r;
260             c.g = (1-d.r) * c000.g + (d.r-d.g) * c100.g + (d.g-d.b) * c110.g + (d.b) * c111.g;
261             c.b = (1-d.r) * c000.b + (d.r-d.g) * c100.b + (d.g-d.b) * c110.b + (d.b) * c111.b;
262         } else if (d.r > d.b) {
263             const struct rgbvec c100 = lut3d->lut[next[0] * lutsize2 + prev[1] * lutsize + prev[2]];
264             const struct rgbvec c101 = lut3d->lut[next[0] * lutsize2 + prev[1] * lutsize + next[2]];
265             c.r = (1-d.r) * c000.r + (d.r-d.b) * c100.r + (d.b-d.g) * c101.r + (d.g) * c111.r;
266             c.g = (1-d.r) * c000.g + (d.r-d.b) * c100.g + (d.b-d.g) * c101.g + (d.g) * c111.g;
267             c.b = (1-d.r) * c000.b + (d.r-d.b) * c100.b + (d.b-d.g) * c101.b + (d.g) * c111.b;
268         } else {
269             const struct rgbvec c001 = lut3d->lut[prev[0] * lutsize2 + prev[1] * lutsize + next[2]];
270             const struct rgbvec c101 = lut3d->lut[next[0] * lutsize2 + prev[1] * lutsize + next[2]];
271             c.r = (1-d.b) * c000.r + (d.b-d.r) * c001.r + (d.r-d.g) * c101.r + (d.g) * c111.r;
272             c.g = (1-d.b) * c000.g + (d.b-d.r) * c001.g + (d.r-d.g) * c101.g + (d.g) * c111.g;
273             c.b = (1-d.b) * c000.b + (d.b-d.r) * c001.b + (d.r-d.g) * c101.b + (d.g) * c111.b;
274         }
275     } else {
276         if (d.b > d.g) {
277             const struct rgbvec c001 = lut3d->lut[prev[0] * lutsize2 + prev[1] * lutsize + next[2]];
278             const struct rgbvec c011 = lut3d->lut[prev[0] * lutsize2 + next[1] * lutsize + next[2]];
279             c.r = (1-d.b) * c000.r + (d.b-d.g) * c001.r + (d.g-d.r) * c011.r + (d.r) * c111.r;
280             c.g = (1-d.b) * c000.g + (d.b-d.g) * c001.g + (d.g-d.r) * c011.g + (d.r) * c111.g;
281             c.b = (1-d.b) * c000.b + (d.b-d.g) * c001.b + (d.g-d.r) * c011.b + (d.r) * c111.b;
282         } else if (d.b > d.r) {
283             const struct rgbvec c010 = lut3d->lut[prev[0] * lutsize2 + next[1] * lutsize + prev[2]];
284             const struct rgbvec c011 = lut3d->lut[prev[0] * lutsize2 + next[1] * lutsize + next[2]];
285             c.r = (1-d.g) * c000.r + (d.g-d.b) * c010.r + (d.b-d.r) * c011.r + (d.r) * c111.r;
286             c.g = (1-d.g) * c000.g + (d.g-d.b) * c010.g + (d.b-d.r) * c011.g + (d.r) * c111.g;
287             c.b = (1-d.g) * c000.b + (d.g-d.b) * c010.b + (d.b-d.r) * c011.b + (d.r) * c111.b;
288         } else {
289             const struct rgbvec c010 = lut3d->lut[prev[0] * lutsize2 + next[1] * lutsize + prev[2]];
290             const struct rgbvec c110 = lut3d->lut[next[0] * lutsize2 + next[1] * lutsize + prev[2]];
291             c.r = (1-d.g) * c000.r + (d.g-d.r) * c010.r + (d.r-d.b) * c110.r + (d.b) * c111.r;
292             c.g = (1-d.g) * c000.g + (d.g-d.r) * c010.g + (d.r-d.b) * c110.g + (d.b) * c111.g;
293             c.b = (1-d.g) * c000.b + (d.g-d.r) * c010.b + (d.r-d.b) * c110.b + (d.b) * c111.b;
294         }
295     }
296     return c;
297 }
298
299 static inline float prelut_interp_1d_linear(const Lut3DPreLut *prelut,
300                                             int idx, const float s)
301 {
302     const int lut_max = prelut->size - 1;
303     const float scaled = (s - prelut->min[idx]) * prelut->scale[idx];
304     const float x = av_clipf(scaled, 0.0f, lut_max);
305     const int prev = PREV(x);
306     const int next = FFMIN((int)(x) + 1, lut_max);
307     const float p = prelut->lut[idx][prev];
308     const float n = prelut->lut[idx][next];
309     const float d = x - (float)prev;
310     return lerpf(p, n, d);
311 }
312
313 static inline struct rgbvec apply_prelut(const Lut3DPreLut *prelut,
314                                          const struct rgbvec *s)
315 {
316     struct rgbvec c;
317
318     if (prelut->size <= 0)
319         return *s;
320
321     c.r = prelut_interp_1d_linear(prelut, 0, s->r);
322     c.g = prelut_interp_1d_linear(prelut, 1, s->g);
323     c.b = prelut_interp_1d_linear(prelut, 2, s->b);
324     return c;
325 }
326
327 #define DEFINE_INTERP_FUNC_PLANAR(name, nbits, depth)                                                  \
328 static int interp_##nbits##_##name##_p##depth(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs) \
329 {                                                                                                      \
330     int x, y;                                                                                          \
331     const LUT3DContext *lut3d = ctx->priv;                                                             \
332     const Lut3DPreLut *prelut = &lut3d->prelut;                                                        \
333     const ThreadData *td = arg;                                                                        \
334     const AVFrame *in  = td->in;                                                                       \
335     const AVFrame *out = td->out;                                                                      \
336     const int direct = out == in;                                                                      \
337     const int slice_start = (in->height *  jobnr   ) / nb_jobs;                                        \
338     const int slice_end   = (in->height * (jobnr+1)) / nb_jobs;                                        \
339     uint8_t *grow = out->data[0] + slice_start * out->linesize[0];                                     \
340     uint8_t *brow = out->data[1] + slice_start * out->linesize[1];                                     \
341     uint8_t *rrow = out->data[2] + slice_start * out->linesize[2];                                     \
342     uint8_t *arow = out->data[3] + slice_start * out->linesize[3];                                     \
343     const uint8_t *srcgrow = in->data[0] + slice_start * in->linesize[0];                              \
344     const uint8_t *srcbrow = in->data[1] + slice_start * in->linesize[1];                              \
345     const uint8_t *srcrrow = in->data[2] + slice_start * in->linesize[2];                              \
346     const uint8_t *srcarow = in->data[3] + slice_start * in->linesize[3];                              \
347     const float lut_max = lut3d->lutsize - 1;                                                          \
348     const float scale_f = 1.0f / ((1<<depth) - 1);                                                     \
349     const float scale_r = lut3d->scale.r * lut_max;                                                    \
350     const float scale_g = lut3d->scale.g * lut_max;                                                    \
351     const float scale_b = lut3d->scale.b * lut_max;                                                    \
352                                                                                                        \
353     for (y = slice_start; y < slice_end; y++) {                                                        \
354         uint##nbits##_t *dstg = (uint##nbits##_t *)grow;                                               \
355         uint##nbits##_t *dstb = (uint##nbits##_t *)brow;                                               \
356         uint##nbits##_t *dstr = (uint##nbits##_t *)rrow;                                               \
357         uint##nbits##_t *dsta = (uint##nbits##_t *)arow;                                               \
358         const uint##nbits##_t *srcg = (const uint##nbits##_t *)srcgrow;                                \
359         const uint##nbits##_t *srcb = (const uint##nbits##_t *)srcbrow;                                \
360         const uint##nbits##_t *srcr = (const uint##nbits##_t *)srcrrow;                                \
361         const uint##nbits##_t *srca = (const uint##nbits##_t *)srcarow;                                \
362         for (x = 0; x < in->width; x++) {                                                              \
363             const struct rgbvec rgb = {srcr[x] * scale_f,                                              \
364                                        srcg[x] * scale_f,                                              \
365                                        srcb[x] * scale_f};                                             \
366             const struct rgbvec prelut_rgb = apply_prelut(prelut, &rgb);                               \
367             const struct rgbvec scaled_rgb = {av_clipf(prelut_rgb.r * scale_r, 0, lut_max),            \
368                                               av_clipf(prelut_rgb.g * scale_g, 0, lut_max),            \
369                                               av_clipf(prelut_rgb.b * scale_b, 0, lut_max)};           \
370             struct rgbvec vec = interp_##name(lut3d, &scaled_rgb);                                     \
371             dstr[x] = av_clip_uintp2(vec.r * (float)((1<<depth) - 1), depth);                          \
372             dstg[x] = av_clip_uintp2(vec.g * (float)((1<<depth) - 1), depth);                          \
373             dstb[x] = av_clip_uintp2(vec.b * (float)((1<<depth) - 1), depth);                          \
374             if (!direct && in->linesize[3])                                                            \
375                 dsta[x] = srca[x];                                                                     \
376         }                                                                                              \
377         grow += out->linesize[0];                                                                      \
378         brow += out->linesize[1];                                                                      \
379         rrow += out->linesize[2];                                                                      \
380         arow += out->linesize[3];                                                                      \
381         srcgrow += in->linesize[0];                                                                    \
382         srcbrow += in->linesize[1];                                                                    \
383         srcrrow += in->linesize[2];                                                                    \
384         srcarow += in->linesize[3];                                                                    \
385     }                                                                                                  \
386     return 0;                                                                                          \
387 }
388
389 DEFINE_INTERP_FUNC_PLANAR(nearest,     8, 8)
390 DEFINE_INTERP_FUNC_PLANAR(trilinear,   8, 8)
391 DEFINE_INTERP_FUNC_PLANAR(tetrahedral, 8, 8)
392 DEFINE_INTERP_FUNC_PLANAR(pyramid,     8, 8)
393
394 DEFINE_INTERP_FUNC_PLANAR(nearest,     16, 9)
395 DEFINE_INTERP_FUNC_PLANAR(trilinear,   16, 9)
396 DEFINE_INTERP_FUNC_PLANAR(tetrahedral, 16, 9)
397 DEFINE_INTERP_FUNC_PLANAR(pyramid,     16, 9)
398
399 DEFINE_INTERP_FUNC_PLANAR(nearest,     16, 10)
400 DEFINE_INTERP_FUNC_PLANAR(trilinear,   16, 10)
401 DEFINE_INTERP_FUNC_PLANAR(tetrahedral, 16, 10)
402 DEFINE_INTERP_FUNC_PLANAR(pyramid,     16, 10)
403
404 DEFINE_INTERP_FUNC_PLANAR(nearest,     16, 12)
405 DEFINE_INTERP_FUNC_PLANAR(trilinear,   16, 12)
406 DEFINE_INTERP_FUNC_PLANAR(tetrahedral, 16, 12)
407 DEFINE_INTERP_FUNC_PLANAR(pyramid,     16, 12)
408
409 DEFINE_INTERP_FUNC_PLANAR(nearest,     16, 14)
410 DEFINE_INTERP_FUNC_PLANAR(trilinear,   16, 14)
411 DEFINE_INTERP_FUNC_PLANAR(tetrahedral, 16, 14)
412 DEFINE_INTERP_FUNC_PLANAR(pyramid,     16, 14)
413
414 DEFINE_INTERP_FUNC_PLANAR(nearest,     16, 16)
415 DEFINE_INTERP_FUNC_PLANAR(trilinear,   16, 16)
416 DEFINE_INTERP_FUNC_PLANAR(tetrahedral, 16, 16)
417 DEFINE_INTERP_FUNC_PLANAR(pyramid,     16, 16)
418
419 #define DEFINE_INTERP_FUNC_PLANAR_FLOAT(name, depth)                                                   \
420 static int interp_##name##_pf##depth(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)          \
421 {                                                                                                      \
422     int x, y;                                                                                          \
423     const LUT3DContext *lut3d = ctx->priv;                                                             \
424     const Lut3DPreLut *prelut = &lut3d->prelut;                                                        \
425     const ThreadData *td = arg;                                                                        \
426     const AVFrame *in  = td->in;                                                                       \
427     const AVFrame *out = td->out;                                                                      \
428     const int direct = out == in;                                                                      \
429     const int slice_start = (in->height *  jobnr   ) / nb_jobs;                                        \
430     const int slice_end   = (in->height * (jobnr+1)) / nb_jobs;                                        \
431     uint8_t *grow = out->data[0] + slice_start * out->linesize[0];                                     \
432     uint8_t *brow = out->data[1] + slice_start * out->linesize[1];                                     \
433     uint8_t *rrow = out->data[2] + slice_start * out->linesize[2];                                     \
434     uint8_t *arow = out->data[3] + slice_start * out->linesize[3];                                     \
435     const uint8_t *srcgrow = in->data[0] + slice_start * in->linesize[0];                              \
436     const uint8_t *srcbrow = in->data[1] + slice_start * in->linesize[1];                              \
437     const uint8_t *srcrrow = in->data[2] + slice_start * in->linesize[2];                              \
438     const uint8_t *srcarow = in->data[3] + slice_start * in->linesize[3];                              \
439     const float lut_max = lut3d->lutsize - 1;                                                          \
440     const float scale_r = lut3d->scale.r * lut_max;                                                    \
441     const float scale_g = lut3d->scale.g * lut_max;                                                    \
442     const float scale_b = lut3d->scale.b * lut_max;                                                    \
443                                                                                                        \
444     for (y = slice_start; y < slice_end; y++) {                                                        \
445         float *dstg = (float *)grow;                                                                   \
446         float *dstb = (float *)brow;                                                                   \
447         float *dstr = (float *)rrow;                                                                   \
448         float *dsta = (float *)arow;                                                                   \
449         const float *srcg = (const float *)srcgrow;                                                    \
450         const float *srcb = (const float *)srcbrow;                                                    \
451         const float *srcr = (const float *)srcrrow;                                                    \
452         const float *srca = (const float *)srcarow;                                                    \
453         for (x = 0; x < in->width; x++) {                                                              \
454             const struct rgbvec rgb = {sanitizef(srcr[x]),                                             \
455                                        sanitizef(srcg[x]),                                             \
456                                        sanitizef(srcb[x])};                                            \
457             const struct rgbvec prelut_rgb = apply_prelut(prelut, &rgb);                               \
458             const struct rgbvec scaled_rgb = {av_clipf(prelut_rgb.r * scale_r, 0, lut_max),            \
459                                               av_clipf(prelut_rgb.g * scale_g, 0, lut_max),            \
460                                               av_clipf(prelut_rgb.b * scale_b, 0, lut_max)};           \
461             struct rgbvec vec = interp_##name(lut3d, &scaled_rgb);                                     \
462             dstr[x] = vec.r;                                                                           \
463             dstg[x] = vec.g;                                                                           \
464             dstb[x] = vec.b;                                                                           \
465             if (!direct && in->linesize[3])                                                            \
466                 dsta[x] = srca[x];                                                                     \
467         }                                                                                              \
468         grow += out->linesize[0];                                                                      \
469         brow += out->linesize[1];                                                                      \
470         rrow += out->linesize[2];                                                                      \
471         arow += out->linesize[3];                                                                      \
472         srcgrow += in->linesize[0];                                                                    \
473         srcbrow += in->linesize[1];                                                                    \
474         srcrrow += in->linesize[2];                                                                    \
475         srcarow += in->linesize[3];                                                                    \
476     }                                                                                                  \
477     return 0;                                                                                          \
478 }
479
480 DEFINE_INTERP_FUNC_PLANAR_FLOAT(nearest,     32)
481 DEFINE_INTERP_FUNC_PLANAR_FLOAT(trilinear,   32)
482 DEFINE_INTERP_FUNC_PLANAR_FLOAT(tetrahedral, 32)
483 DEFINE_INTERP_FUNC_PLANAR_FLOAT(pyramid,     32)
484
485 #define DEFINE_INTERP_FUNC(name, nbits)                                                             \
486 static int interp_##nbits##_##name(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)         \
487 {                                                                                                   \
488     int x, y;                                                                                       \
489     const LUT3DContext *lut3d = ctx->priv;                                                          \
490     const Lut3DPreLut *prelut = &lut3d->prelut;                                                     \
491     const ThreadData *td = arg;                                                                     \
492     const AVFrame *in  = td->in;                                                                    \
493     const AVFrame *out = td->out;                                                                   \
494     const int direct = out == in;                                                                   \
495     const int step = lut3d->step;                                                                   \
496     const uint8_t r = lut3d->rgba_map[R];                                                           \
497     const uint8_t g = lut3d->rgba_map[G];                                                           \
498     const uint8_t b = lut3d->rgba_map[B];                                                           \
499     const uint8_t a = lut3d->rgba_map[A];                                                           \
500     const int slice_start = (in->height *  jobnr   ) / nb_jobs;                                     \
501     const int slice_end   = (in->height * (jobnr+1)) / nb_jobs;                                     \
502     uint8_t       *dstrow = out->data[0] + slice_start * out->linesize[0];                          \
503     const uint8_t *srcrow = in ->data[0] + slice_start * in ->linesize[0];                          \
504     const float lut_max = lut3d->lutsize - 1;                                                       \
505     const float scale_f = 1.0f / ((1<<nbits) - 1);                                                  \
506     const float scale_r = lut3d->scale.r * lut_max;                                                 \
507     const float scale_g = lut3d->scale.g * lut_max;                                                 \
508     const float scale_b = lut3d->scale.b * lut_max;                                                 \
509                                                                                                     \
510     for (y = slice_start; y < slice_end; y++) {                                                     \
511         uint##nbits##_t *dst = (uint##nbits##_t *)dstrow;                                           \
512         const uint##nbits##_t *src = (const uint##nbits##_t *)srcrow;                               \
513         for (x = 0; x < in->width * step; x += step) {                                              \
514             const struct rgbvec rgb = {src[x + r] * scale_f,                                        \
515                                        src[x + g] * scale_f,                                        \
516                                        src[x + b] * scale_f};                                       \
517             const struct rgbvec prelut_rgb = apply_prelut(prelut, &rgb);                            \
518             const struct rgbvec scaled_rgb = {av_clipf(prelut_rgb.r * scale_r, 0, lut_max),         \
519                                               av_clipf(prelut_rgb.g * scale_g, 0, lut_max),         \
520                                               av_clipf(prelut_rgb.b * scale_b, 0, lut_max)};        \
521             struct rgbvec vec = interp_##name(lut3d, &scaled_rgb);                                  \
522             dst[x + r] = av_clip_uint##nbits(vec.r * (float)((1<<nbits) - 1));                      \
523             dst[x + g] = av_clip_uint##nbits(vec.g * (float)((1<<nbits) - 1));                      \
524             dst[x + b] = av_clip_uint##nbits(vec.b * (float)((1<<nbits) - 1));                      \
525             if (!direct && step == 4)                                                               \
526                 dst[x + a] = src[x + a];                                                            \
527         }                                                                                           \
528         dstrow += out->linesize[0];                                                                 \
529         srcrow += in ->linesize[0];                                                                 \
530     }                                                                                               \
531     return 0;                                                                                       \
532 }
533
534 DEFINE_INTERP_FUNC(nearest,     8)
535 DEFINE_INTERP_FUNC(trilinear,   8)
536 DEFINE_INTERP_FUNC(tetrahedral, 8)
537 DEFINE_INTERP_FUNC(pyramid,     8)
538
539 DEFINE_INTERP_FUNC(nearest,     16)
540 DEFINE_INTERP_FUNC(trilinear,   16)
541 DEFINE_INTERP_FUNC(tetrahedral, 16)
542 DEFINE_INTERP_FUNC(pyramid,     16)
543
544 #define MAX_LINE_SIZE 512
545
546 static int skip_line(const char *p)
547 {
548     while (*p && av_isspace(*p))
549         p++;
550     return !*p || *p == '#';
551 }
552
553 static char* fget_next_word(char* dst, int max, FILE* f)
554 {
555     int c;
556     char *p = dst;
557
558     /* for null */
559     max--;
560     /* skip until next non whitespace char */
561     while ((c = fgetc(f)) != EOF) {
562         if (av_isspace(c))
563             continue;
564
565         *p++ = c;
566         max--;
567         break;
568     }
569
570     /* get max bytes or up until next whitespace char */
571     for (; max > 0; max--) {
572         if ((c = fgetc(f)) == EOF)
573             break;
574
575         if (av_isspace(c))
576             break;
577
578         *p++ = c;
579     }
580
581     *p = 0;
582     if (p == dst)
583         return NULL;
584     return p;
585 }
586
587 #define NEXT_LINE(loop_cond) do {                           \
588     if (!fgets(line, sizeof(line), f)) {                    \
589         av_log(ctx, AV_LOG_ERROR, "Unexpected EOF\n");      \
590         return AVERROR_INVALIDDATA;                         \
591     }                                                       \
592 } while (loop_cond)
593
594 #define NEXT_LINE_OR_GOTO(loop_cond, label) do {            \
595     if (!fgets(line, sizeof(line), f)) {                    \
596         av_log(ctx, AV_LOG_ERROR, "Unexpected EOF\n");      \
597         ret = AVERROR_INVALIDDATA;                          \
598         goto label;                                         \
599     }                                                       \
600 } while (loop_cond)
601
602 static int allocate_3dlut(AVFilterContext *ctx, int lutsize, int prelut)
603 {
604     LUT3DContext *lut3d = ctx->priv;
605     int i;
606     if (lutsize < 2 || lutsize > MAX_LEVEL) {
607         av_log(ctx, AV_LOG_ERROR, "Too large or invalid 3D LUT size\n");
608         return AVERROR(EINVAL);
609     }
610
611     av_freep(&lut3d->lut);
612     lut3d->lut = av_malloc_array(lutsize * lutsize * lutsize, sizeof(*lut3d->lut));
613     if (!lut3d->lut)
614         return AVERROR(ENOMEM);
615
616     if (prelut) {
617         lut3d->prelut.size = PRELUT_SIZE;
618         for (i = 0; i < 3; i++) {
619             av_freep(&lut3d->prelut.lut[i]);
620             lut3d->prelut.lut[i] = av_malloc_array(PRELUT_SIZE, sizeof(*lut3d->prelut.lut[0]));
621             if (!lut3d->prelut.lut[i])
622                 return AVERROR(ENOMEM);
623         }
624     } else {
625         lut3d->prelut.size = 0;
626         for (i = 0; i < 3; i++) {
627             av_freep(&lut3d->prelut.lut[i]);
628         }
629     }
630     lut3d->lutsize = lutsize;
631     lut3d->lutsize2 = lutsize * lutsize;
632     return 0;
633 }
634
635 /* Basically r g and b float values on each line, with a facultative 3DLUTSIZE
636  * directive; seems to be generated by Davinci */
637 static int parse_dat(AVFilterContext *ctx, FILE *f)
638 {
639     LUT3DContext *lut3d = ctx->priv;
640     char line[MAX_LINE_SIZE];
641     int ret, i, j, k, size, size2;
642
643     lut3d->lutsize = size = 33;
644     size2 = size * size;
645
646     NEXT_LINE(skip_line(line));
647     if (!strncmp(line, "3DLUTSIZE ", 10)) {
648         size = strtol(line + 10, NULL, 0);
649
650         NEXT_LINE(skip_line(line));
651     }
652
653     ret = allocate_3dlut(ctx, size, 0);
654     if (ret < 0)
655         return ret;
656
657     for (k = 0; k < size; k++) {
658         for (j = 0; j < size; j++) {
659             for (i = 0; i < size; i++) {
660                 struct rgbvec *vec = &lut3d->lut[k * size2 + j * size + i];
661                 if (k != 0 || j != 0 || i != 0)
662                     NEXT_LINE(skip_line(line));
663                 if (av_sscanf(line, "%f %f %f", &vec->r, &vec->g, &vec->b) != 3)
664                     return AVERROR_INVALIDDATA;
665             }
666         }
667     }
668     return 0;
669 }
670
671 /* Iridas format */
672 static int parse_cube(AVFilterContext *ctx, FILE *f)
673 {
674     LUT3DContext *lut3d = ctx->priv;
675     char line[MAX_LINE_SIZE];
676     float min[3] = {0.0, 0.0, 0.0};
677     float max[3] = {1.0, 1.0, 1.0};
678
679     while (fgets(line, sizeof(line), f)) {
680         if (!strncmp(line, "LUT_3D_SIZE", 11)) {
681             int ret, i, j, k;
682             const int size = strtol(line + 12, NULL, 0);
683             const int size2 = size * size;
684
685             ret = allocate_3dlut(ctx, size, 0);
686             if (ret < 0)
687                 return ret;
688
689             for (k = 0; k < size; k++) {
690                 for (j = 0; j < size; j++) {
691                     for (i = 0; i < size; i++) {
692                         struct rgbvec *vec = &lut3d->lut[i * size2 + j * size + k];
693
694                         do {
695 try_again:
696                             NEXT_LINE(0);
697                             if (!strncmp(line, "DOMAIN_", 7)) {
698                                 float *vals = NULL;
699                                 if      (!strncmp(line + 7, "MIN ", 4)) vals = min;
700                                 else if (!strncmp(line + 7, "MAX ", 4)) vals = max;
701                                 if (!vals)
702                                     return AVERROR_INVALIDDATA;
703                                 av_sscanf(line + 11, "%f %f %f", vals, vals + 1, vals + 2);
704                                 av_log(ctx, AV_LOG_DEBUG, "min: %f %f %f | max: %f %f %f\n",
705                                        min[0], min[1], min[2], max[0], max[1], max[2]);
706                                 goto try_again;
707                             } else if (!strncmp(line, "TITLE", 5)) {
708                                 goto try_again;
709                             }
710                         } while (skip_line(line));
711                         if (av_sscanf(line, "%f %f %f", &vec->r, &vec->g, &vec->b) != 3)
712                             return AVERROR_INVALIDDATA;
713                     }
714                 }
715             }
716             break;
717         }
718     }
719
720     lut3d->scale.r = av_clipf(1. / (max[0] - min[0]), 0.f, 1.f);
721     lut3d->scale.g = av_clipf(1. / (max[1] - min[1]), 0.f, 1.f);
722     lut3d->scale.b = av_clipf(1. / (max[2] - min[2]), 0.f, 1.f);
723
724     return 0;
725 }
726
727 /* Assume 17x17x17 LUT with a 16-bit depth
728  * FIXME: it seems there are various 3dl formats */
729 static int parse_3dl(AVFilterContext *ctx, FILE *f)
730 {
731     char line[MAX_LINE_SIZE];
732     LUT3DContext *lut3d = ctx->priv;
733     int ret, i, j, k;
734     const int size = 17;
735     const int size2 = 17 * 17;
736     const float scale = 16*16*16;
737
738     lut3d->lutsize = size;
739
740     ret = allocate_3dlut(ctx, size, 0);
741     if (ret < 0)
742         return ret;
743
744     NEXT_LINE(skip_line(line));
745     for (k = 0; k < size; k++) {
746         for (j = 0; j < size; j++) {
747             for (i = 0; i < size; i++) {
748                 int r, g, b;
749                 struct rgbvec *vec = &lut3d->lut[k * size2 + j * size + i];
750
751                 NEXT_LINE(skip_line(line));
752                 if (av_sscanf(line, "%d %d %d", &r, &g, &b) != 3)
753                     return AVERROR_INVALIDDATA;
754                 vec->r = r / scale;
755                 vec->g = g / scale;
756                 vec->b = b / scale;
757             }
758         }
759     }
760     return 0;
761 }
762
763 /* Pandora format */
764 static int parse_m3d(AVFilterContext *ctx, FILE *f)
765 {
766     LUT3DContext *lut3d = ctx->priv;
767     float scale;
768     int ret, i, j, k, size, size2, in = -1, out = -1;
769     char line[MAX_LINE_SIZE];
770     uint8_t rgb_map[3] = {0, 1, 2};
771
772     while (fgets(line, sizeof(line), f)) {
773         if      (!strncmp(line, "in",  2)) in  = strtol(line + 2, NULL, 0);
774         else if (!strncmp(line, "out", 3)) out = strtol(line + 3, NULL, 0);
775         else if (!strncmp(line, "values", 6)) {
776             const char *p = line + 6;
777 #define SET_COLOR(id) do {                  \
778     while (av_isspace(*p))                  \
779         p++;                                \
780     switch (*p) {                           \
781     case 'r': rgb_map[id] = 0; break;       \
782     case 'g': rgb_map[id] = 1; break;       \
783     case 'b': rgb_map[id] = 2; break;       \
784     }                                       \
785     while (*p && !av_isspace(*p))           \
786         p++;                                \
787 } while (0)
788             SET_COLOR(0);
789             SET_COLOR(1);
790             SET_COLOR(2);
791             break;
792         }
793     }
794
795     if (in == -1 || out == -1) {
796         av_log(ctx, AV_LOG_ERROR, "in and out must be defined\n");
797         return AVERROR_INVALIDDATA;
798     }
799     if (in < 2 || out < 2 ||
800         in  > MAX_LEVEL*MAX_LEVEL*MAX_LEVEL ||
801         out > MAX_LEVEL*MAX_LEVEL*MAX_LEVEL) {
802         av_log(ctx, AV_LOG_ERROR, "invalid in (%d) or out (%d)\n", in, out);
803         return AVERROR_INVALIDDATA;
804     }
805     for (size = 1; size*size*size < in; size++);
806     lut3d->lutsize = size;
807     size2 = size * size;
808
809     ret = allocate_3dlut(ctx, size, 0);
810     if (ret < 0)
811         return ret;
812
813     scale = 1. / (out - 1);
814
815     for (k = 0; k < size; k++) {
816         for (j = 0; j < size; j++) {
817             for (i = 0; i < size; i++) {
818                 struct rgbvec *vec = &lut3d->lut[k * size2 + j * size + i];
819                 float val[3];
820
821                 NEXT_LINE(0);
822                 if (av_sscanf(line, "%f %f %f", val, val + 1, val + 2) != 3)
823                     return AVERROR_INVALIDDATA;
824                 vec->r = val[rgb_map[0]] * scale;
825                 vec->g = val[rgb_map[1]] * scale;
826                 vec->b = val[rgb_map[2]] * scale;
827             }
828         }
829     }
830     return 0;
831 }
832
833 static int nearest_sample_index(float *data, float x, int low, int hi)
834 {
835     int mid;
836     if (x < data[low])
837         return low;
838
839     if (x > data[hi])
840         return hi;
841
842     for (;;) {
843         av_assert0(x >= data[low]);
844         av_assert0(x <= data[hi]);
845         av_assert0((hi-low) > 0);
846
847         if (hi - low == 1)
848             return low;
849
850         mid = (low + hi) / 2;
851
852         if (x < data[mid])
853             hi = mid;
854         else
855             low = mid;
856     }
857
858     return 0;
859 }
860
861 #define NEXT_FLOAT_OR_GOTO(value, label)                    \
862     if (!fget_next_word(line, sizeof(line) ,f)) {           \
863         ret = AVERROR_INVALIDDATA;                          \
864         goto label;                                         \
865     }                                                       \
866     if (av_sscanf(line, "%f", &value) != 1) {               \
867         ret = AVERROR_INVALIDDATA;                          \
868         goto label;                                         \
869     }
870
871 static int parse_cinespace(AVFilterContext *ctx, FILE *f)
872 {
873     LUT3DContext *lut3d = ctx->priv;
874     char line[MAX_LINE_SIZE];
875     float in_min[3]  = {0.0, 0.0, 0.0};
876     float in_max[3]  = {1.0, 1.0, 1.0};
877     float out_min[3] = {0.0, 0.0, 0.0};
878     float out_max[3] = {1.0, 1.0, 1.0};
879     int inside_metadata = 0, size, size2;
880     int prelut = 0;
881     int ret = 0;
882
883     int prelut_sizes[3] = {0, 0, 0};
884     float *in_prelut[3]  = {NULL, NULL, NULL};
885     float *out_prelut[3] = {NULL, NULL, NULL};
886
887     NEXT_LINE_OR_GOTO(skip_line(line), end);
888     if (strncmp(line, "CSPLUTV100", 10)) {
889         av_log(ctx, AV_LOG_ERROR, "Not cineSpace LUT format\n");
890         ret = AVERROR(EINVAL);
891         goto end;
892     }
893
894     NEXT_LINE_OR_GOTO(skip_line(line), end);
895     if (strncmp(line, "3D", 2)) {
896         av_log(ctx, AV_LOG_ERROR, "Not 3D LUT format\n");
897         ret = AVERROR(EINVAL);
898         goto end;
899     }
900
901     while (1) {
902         NEXT_LINE_OR_GOTO(skip_line(line), end);
903
904         if (!strncmp(line, "BEGIN METADATA", 14)) {
905             inside_metadata = 1;
906             continue;
907         }
908         if (!strncmp(line, "END METADATA", 12)) {
909             inside_metadata = 0;
910             continue;
911         }
912         if (inside_metadata == 0) {
913             int size_r, size_g, size_b;
914
915             for (int i = 0; i < 3; i++) {
916                 int npoints = strtol(line, NULL, 0);
917
918                 if (npoints > 2) {
919                     float v,last;
920
921                     if (npoints > PRELUT_SIZE) {
922                         av_log(ctx, AV_LOG_ERROR, "Prelut size too large.\n");
923                         ret = AVERROR_INVALIDDATA;
924                         goto end;
925                     }
926
927                     if (in_prelut[i] || out_prelut[i]) {
928                         av_log(ctx, AV_LOG_ERROR, "Invalid file has multiple preluts.\n");
929                         ret = AVERROR_INVALIDDATA;
930                         goto end;
931                     }
932
933                     in_prelut[i]  = (float*)av_malloc(npoints * sizeof(float));
934                     out_prelut[i] = (float*)av_malloc(npoints * sizeof(float));
935                     if (!in_prelut[i] || !out_prelut[i]) {
936                         ret = AVERROR(ENOMEM);
937                         goto end;
938                     }
939
940                     prelut_sizes[i] = npoints;
941                     in_min[i] = FLT_MAX;
942                     in_max[i] = -FLT_MAX;
943                     out_min[i] = FLT_MAX;
944                     out_max[i] = -FLT_MAX;
945
946                     for (int j = 0; j < npoints; j++) {
947                         NEXT_FLOAT_OR_GOTO(v, end)
948                         in_min[i] = FFMIN(in_min[i], v);
949                         in_max[i] = FFMAX(in_max[i], v);
950                         in_prelut[i][j] = v;
951                         if (j > 0 && v < last) {
952                             av_log(ctx, AV_LOG_ERROR, "Invalid file, non increasing prelut.\n");
953                             ret = AVERROR(ENOMEM);
954                             goto end;
955                         }
956                         last = v;
957                     }
958
959                     for (int j = 0; j < npoints; j++) {
960                         NEXT_FLOAT_OR_GOTO(v, end)
961                         out_min[i] = FFMIN(out_min[i], v);
962                         out_max[i] = FFMAX(out_max[i], v);
963                         out_prelut[i][j] = v;
964                     }
965
966                 } else if (npoints == 2)  {
967                     NEXT_LINE_OR_GOTO(skip_line(line), end);
968                     if (av_sscanf(line, "%f %f", &in_min[i], &in_max[i]) != 2) {
969                         ret = AVERROR_INVALIDDATA;
970                         goto end;
971                     }
972                     NEXT_LINE_OR_GOTO(skip_line(line), end);
973                     if (av_sscanf(line, "%f %f", &out_min[i], &out_max[i]) != 2) {
974                         ret = AVERROR_INVALIDDATA;
975                         goto end;
976                     }
977
978                 } else {
979                     av_log(ctx, AV_LOG_ERROR, "Unsupported number of pre-lut points.\n");
980                     ret = AVERROR_PATCHWELCOME;
981                     goto end;
982                 }
983
984                 NEXT_LINE_OR_GOTO(skip_line(line), end);
985             }
986
987             if (av_sscanf(line, "%d %d %d", &size_r, &size_g, &size_b) != 3) {
988                 ret = AVERROR(EINVAL);
989                 goto end;
990             }
991             if (size_r != size_g || size_r != size_b) {
992                 av_log(ctx, AV_LOG_ERROR, "Unsupported size combination: %dx%dx%d.\n", size_r, size_g, size_b);
993                 ret = AVERROR_PATCHWELCOME;
994                 goto end;
995             }
996
997             size = size_r;
998             size2 = size * size;
999
1000             if (prelut_sizes[0] && prelut_sizes[1] && prelut_sizes[2])
1001                 prelut = 1;
1002
1003             ret = allocate_3dlut(ctx, size, prelut);
1004             if (ret < 0)
1005                 return ret;
1006
1007             for (int k = 0; k < size; k++) {
1008                 for (int j = 0; j < size; j++) {
1009                     for (int i = 0; i < size; i++) {
1010                         struct rgbvec *vec = &lut3d->lut[i * size2 + j * size + k];
1011
1012                         NEXT_LINE_OR_GOTO(skip_line(line), end);
1013                         if (av_sscanf(line, "%f %f %f", &vec->r, &vec->g, &vec->b) != 3) {
1014                             ret = AVERROR_INVALIDDATA;
1015                             goto end;
1016                         }
1017
1018                         vec->r *= out_max[0] - out_min[0];
1019                         vec->g *= out_max[1] - out_min[1];
1020                         vec->b *= out_max[2] - out_min[2];
1021                     }
1022                 }
1023             }
1024
1025             break;
1026         }
1027     }
1028
1029     if (prelut) {
1030         for (int c = 0; c < 3; c++) {
1031
1032             lut3d->prelut.min[c] = in_min[c];
1033             lut3d->prelut.max[c] = in_max[c];
1034             lut3d->prelut.scale[c] =  (1.0f / (float)(in_max[c] - in_min[c])) * (lut3d->prelut.size - 1);
1035
1036             for (int i = 0; i < lut3d->prelut.size; ++i) {
1037                 float mix = (float) i / (float)(lut3d->prelut.size - 1);
1038                 float x = lerpf(in_min[c], in_max[c], mix), a, b;
1039
1040                 int idx = nearest_sample_index(in_prelut[c], x, 0, prelut_sizes[c]-1);
1041                 av_assert0(idx + 1 < prelut_sizes[c]);
1042
1043                 a   = out_prelut[c][idx + 0];
1044                 b   = out_prelut[c][idx + 1];
1045                 mix = x - in_prelut[c][idx];
1046
1047                 lut3d->prelut.lut[c][i] = sanitizef(lerpf(a, b, mix));
1048             }
1049         }
1050         lut3d->scale.r = 1.00f;
1051         lut3d->scale.g = 1.00f;
1052         lut3d->scale.b = 1.00f;
1053
1054     } else {
1055         lut3d->scale.r = av_clipf(1. / (in_max[0] - in_min[0]), 0.f, 1.f);
1056         lut3d->scale.g = av_clipf(1. / (in_max[1] - in_min[1]), 0.f, 1.f);
1057         lut3d->scale.b = av_clipf(1. / (in_max[2] - in_min[2]), 0.f, 1.f);
1058     }
1059
1060 end:
1061     for (int c = 0; c < 3; c++) {
1062         av_freep(&in_prelut[c]);
1063         av_freep(&out_prelut[c]);
1064     }
1065     return ret;
1066 }
1067
1068 static int set_identity_matrix(AVFilterContext *ctx, int size)
1069 {
1070     LUT3DContext *lut3d = ctx->priv;
1071     int ret, i, j, k;
1072     const int size2 = size * size;
1073     const float c = 1. / (size - 1);
1074
1075     ret = allocate_3dlut(ctx, size, 0);
1076     if (ret < 0)
1077         return ret;
1078
1079     for (k = 0; k < size; k++) {
1080         for (j = 0; j < size; j++) {
1081             for (i = 0; i < size; i++) {
1082                 struct rgbvec *vec = &lut3d->lut[k * size2 + j * size + i];
1083                 vec->r = k * c;
1084                 vec->g = j * c;
1085                 vec->b = i * c;
1086             }
1087         }
1088     }
1089
1090     return 0;
1091 }
1092
1093 static int query_formats(AVFilterContext *ctx)
1094 {
1095     static const enum AVPixelFormat pix_fmts[] = {
1096         AV_PIX_FMT_RGB24,  AV_PIX_FMT_BGR24,
1097         AV_PIX_FMT_RGBA,   AV_PIX_FMT_BGRA,
1098         AV_PIX_FMT_ARGB,   AV_PIX_FMT_ABGR,
1099         AV_PIX_FMT_0RGB,   AV_PIX_FMT_0BGR,
1100         AV_PIX_FMT_RGB0,   AV_PIX_FMT_BGR0,
1101         AV_PIX_FMT_RGB48,  AV_PIX_FMT_BGR48,
1102         AV_PIX_FMT_RGBA64, AV_PIX_FMT_BGRA64,
1103         AV_PIX_FMT_GBRP,   AV_PIX_FMT_GBRAP,
1104         AV_PIX_FMT_GBRP9,
1105         AV_PIX_FMT_GBRP10, AV_PIX_FMT_GBRAP10,
1106         AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRAP12,
1107         AV_PIX_FMT_GBRP14,
1108         AV_PIX_FMT_GBRP16,  AV_PIX_FMT_GBRAP16,
1109         AV_PIX_FMT_GBRPF32, AV_PIX_FMT_GBRAPF32,
1110         AV_PIX_FMT_NONE
1111     };
1112     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
1113     if (!fmts_list)
1114         return AVERROR(ENOMEM);
1115     return ff_set_common_formats(ctx, fmts_list);
1116 }
1117
1118 static int config_input(AVFilterLink *inlink)
1119 {
1120     int depth, is16bit, isfloat, planar;
1121     LUT3DContext *lut3d = inlink->dst->priv;
1122     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
1123
1124     depth = desc->comp[0].depth;
1125     is16bit = desc->comp[0].depth > 8;
1126     planar = desc->flags & AV_PIX_FMT_FLAG_PLANAR;
1127     isfloat = desc->flags & AV_PIX_FMT_FLAG_FLOAT;
1128     ff_fill_rgba_map(lut3d->rgba_map, inlink->format);
1129     lut3d->step = av_get_padded_bits_per_pixel(desc) >> (3 + is16bit);
1130
1131 #define SET_FUNC(name) do {                                     \
1132     if (planar && !isfloat) {                                   \
1133         switch (depth) {                                        \
1134         case  8: lut3d->interp = interp_8_##name##_p8;   break; \
1135         case  9: lut3d->interp = interp_16_##name##_p9;  break; \
1136         case 10: lut3d->interp = interp_16_##name##_p10; break; \
1137         case 12: lut3d->interp = interp_16_##name##_p12; break; \
1138         case 14: lut3d->interp = interp_16_##name##_p14; break; \
1139         case 16: lut3d->interp = interp_16_##name##_p16; break; \
1140         }                                                       \
1141     } else if (isfloat) { lut3d->interp = interp_##name##_pf32; \
1142     } else if (is16bit) { lut3d->interp = interp_16_##name;     \
1143     } else {       lut3d->interp = interp_8_##name; }           \
1144 } while (0)
1145
1146     switch (lut3d->interpolation) {
1147     case INTERPOLATE_NEAREST:     SET_FUNC(nearest);        break;
1148     case INTERPOLATE_TRILINEAR:   SET_FUNC(trilinear);      break;
1149     case INTERPOLATE_TETRAHEDRAL: SET_FUNC(tetrahedral);    break;
1150     case INTERPOLATE_PYRAMID:     SET_FUNC(pyramid);        break;
1151     default:
1152         av_assert0(0);
1153     }
1154
1155     return 0;
1156 }
1157
1158 static AVFrame *apply_lut(AVFilterLink *inlink, AVFrame *in)
1159 {
1160     AVFilterContext *ctx = inlink->dst;
1161     LUT3DContext *lut3d = ctx->priv;
1162     AVFilterLink *outlink = inlink->dst->outputs[0];
1163     AVFrame *out;
1164     ThreadData td;
1165
1166     if (av_frame_is_writable(in)) {
1167         out = in;
1168     } else {
1169         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
1170         if (!out) {
1171             av_frame_free(&in);
1172             return NULL;
1173         }
1174         av_frame_copy_props(out, in);
1175     }
1176
1177     td.in  = in;
1178     td.out = out;
1179     ctx->internal->execute(ctx, lut3d->interp, &td, NULL, FFMIN(outlink->h, ff_filter_get_nb_threads(ctx)));
1180
1181     if (out != in)
1182         av_frame_free(&in);
1183
1184     return out;
1185 }
1186
1187 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
1188 {
1189     AVFilterLink *outlink = inlink->dst->outputs[0];
1190     AVFrame *out = apply_lut(inlink, in);
1191     if (!out)
1192         return AVERROR(ENOMEM);
1193     return ff_filter_frame(outlink, out);
1194 }
1195
1196 #if CONFIG_LUT3D_FILTER
1197 static const AVOption lut3d_options[] = {
1198     { "file", "set 3D LUT file name", OFFSET(file), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
1199     COMMON_OPTIONS
1200 };
1201
1202 AVFILTER_DEFINE_CLASS(lut3d);
1203
1204 static av_cold int lut3d_init(AVFilterContext *ctx)
1205 {
1206     int ret;
1207     FILE *f;
1208     const char *ext;
1209     LUT3DContext *lut3d = ctx->priv;
1210
1211     lut3d->scale.r = lut3d->scale.g = lut3d->scale.b = 1.f;
1212
1213     if (!lut3d->file) {
1214         return set_identity_matrix(ctx, 32);
1215     }
1216
1217     f = av_fopen_utf8(lut3d->file, "r");
1218     if (!f) {
1219         ret = AVERROR(errno);
1220         av_log(ctx, AV_LOG_ERROR, "%s: %s\n", lut3d->file, av_err2str(ret));
1221         return ret;
1222     }
1223
1224     ext = strrchr(lut3d->file, '.');
1225     if (!ext) {
1226         av_log(ctx, AV_LOG_ERROR, "Unable to guess the format from the extension\n");
1227         ret = AVERROR_INVALIDDATA;
1228         goto end;
1229     }
1230     ext++;
1231
1232     if (!av_strcasecmp(ext, "dat")) {
1233         ret = parse_dat(ctx, f);
1234     } else if (!av_strcasecmp(ext, "3dl")) {
1235         ret = parse_3dl(ctx, f);
1236     } else if (!av_strcasecmp(ext, "cube")) {
1237         ret = parse_cube(ctx, f);
1238     } else if (!av_strcasecmp(ext, "m3d")) {
1239         ret = parse_m3d(ctx, f);
1240     } else if (!av_strcasecmp(ext, "csp")) {
1241         ret = parse_cinespace(ctx, f);
1242     } else {
1243         av_log(ctx, AV_LOG_ERROR, "Unrecognized '.%s' file type\n", ext);
1244         ret = AVERROR(EINVAL);
1245     }
1246
1247     if (!ret && !lut3d->lutsize) {
1248         av_log(ctx, AV_LOG_ERROR, "3D LUT is empty\n");
1249         ret = AVERROR_INVALIDDATA;
1250     }
1251
1252 end:
1253     fclose(f);
1254     return ret;
1255 }
1256
1257 static av_cold void lut3d_uninit(AVFilterContext *ctx)
1258 {
1259     LUT3DContext *lut3d = ctx->priv;
1260     int i;
1261     av_freep(&lut3d->lut);
1262
1263     for (i = 0; i < 3; i++) {
1264         av_freep(&lut3d->prelut.lut[i]);
1265     }
1266 }
1267
1268 static const AVFilterPad lut3d_inputs[] = {
1269     {
1270         .name         = "default",
1271         .type         = AVMEDIA_TYPE_VIDEO,
1272         .filter_frame = filter_frame,
1273         .config_props = config_input,
1274     },
1275     { NULL }
1276 };
1277
1278 static const AVFilterPad lut3d_outputs[] = {
1279     {
1280         .name = "default",
1281         .type = AVMEDIA_TYPE_VIDEO,
1282     },
1283     { NULL }
1284 };
1285
1286 AVFilter ff_vf_lut3d = {
1287     .name          = "lut3d",
1288     .description   = NULL_IF_CONFIG_SMALL("Adjust colors using a 3D LUT."),
1289     .priv_size     = sizeof(LUT3DContext),
1290     .init          = lut3d_init,
1291     .uninit        = lut3d_uninit,
1292     .query_formats = query_formats,
1293     .inputs        = lut3d_inputs,
1294     .outputs       = lut3d_outputs,
1295     .priv_class    = &lut3d_class,
1296     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS,
1297 };
1298 #endif
1299
1300 #if CONFIG_HALDCLUT_FILTER
1301
1302 static void update_clut_packed(LUT3DContext *lut3d, const AVFrame *frame)
1303 {
1304     const uint8_t *data = frame->data[0];
1305     const int linesize  = frame->linesize[0];
1306     const int w = lut3d->clut_width;
1307     const int step = lut3d->clut_step;
1308     const uint8_t *rgba_map = lut3d->clut_rgba_map;
1309     const int level = lut3d->lutsize;
1310     const int level2 = lut3d->lutsize2;
1311
1312 #define LOAD_CLUT(nbits) do {                                           \
1313     int i, j, k, x = 0, y = 0;                                          \
1314                                                                         \
1315     for (k = 0; k < level; k++) {                                       \
1316         for (j = 0; j < level; j++) {                                   \
1317             for (i = 0; i < level; i++) {                               \
1318                 const uint##nbits##_t *src = (const uint##nbits##_t *)  \
1319                     (data + y*linesize + x*step);                       \
1320                 struct rgbvec *vec = &lut3d->lut[i * level2 + j * level + k]; \
1321                 vec->r = src[rgba_map[0]] / (float)((1<<(nbits)) - 1);  \
1322                 vec->g = src[rgba_map[1]] / (float)((1<<(nbits)) - 1);  \
1323                 vec->b = src[rgba_map[2]] / (float)((1<<(nbits)) - 1);  \
1324                 if (++x == w) {                                         \
1325                     x = 0;                                              \
1326                     y++;                                                \
1327                 }                                                       \
1328             }                                                           \
1329         }                                                               \
1330     }                                                                   \
1331 } while (0)
1332
1333     switch (lut3d->clut_bits) {
1334     case  8: LOAD_CLUT(8);  break;
1335     case 16: LOAD_CLUT(16); break;
1336     }
1337 }
1338
1339 static void update_clut_planar(LUT3DContext *lut3d, const AVFrame *frame)
1340 {
1341     const uint8_t *datag = frame->data[0];
1342     const uint8_t *datab = frame->data[1];
1343     const uint8_t *datar = frame->data[2];
1344     const int glinesize  = frame->linesize[0];
1345     const int blinesize  = frame->linesize[1];
1346     const int rlinesize  = frame->linesize[2];
1347     const int w = lut3d->clut_width;
1348     const int level = lut3d->lutsize;
1349     const int level2 = lut3d->lutsize2;
1350
1351 #define LOAD_CLUT_PLANAR(nbits, depth) do {                             \
1352     int i, j, k, x = 0, y = 0;                                          \
1353                                                                         \
1354     for (k = 0; k < level; k++) {                                       \
1355         for (j = 0; j < level; j++) {                                   \
1356             for (i = 0; i < level; i++) {                               \
1357                 const uint##nbits##_t *gsrc = (const uint##nbits##_t *) \
1358                     (datag + y*glinesize);                              \
1359                 const uint##nbits##_t *bsrc = (const uint##nbits##_t *) \
1360                     (datab + y*blinesize);                              \
1361                 const uint##nbits##_t *rsrc = (const uint##nbits##_t *) \
1362                     (datar + y*rlinesize);                              \
1363                 struct rgbvec *vec = &lut3d->lut[i * level2 + j * level + k]; \
1364                 vec->r = gsrc[x] / (float)((1<<(depth)) - 1);           \
1365                 vec->g = bsrc[x] / (float)((1<<(depth)) - 1);           \
1366                 vec->b = rsrc[x] / (float)((1<<(depth)) - 1);           \
1367                 if (++x == w) {                                         \
1368                     x = 0;                                              \
1369                     y++;                                                \
1370                 }                                                       \
1371             }                                                           \
1372         }                                                               \
1373     }                                                                   \
1374 } while (0)
1375
1376     switch (lut3d->clut_bits) {
1377     case  8: LOAD_CLUT_PLANAR(8, 8);   break;
1378     case  9: LOAD_CLUT_PLANAR(16, 9);  break;
1379     case 10: LOAD_CLUT_PLANAR(16, 10); break;
1380     case 12: LOAD_CLUT_PLANAR(16, 12); break;
1381     case 14: LOAD_CLUT_PLANAR(16, 14); break;
1382     case 16: LOAD_CLUT_PLANAR(16, 16); break;
1383     }
1384 }
1385
1386 static void update_clut_float(LUT3DContext *lut3d, const AVFrame *frame)
1387 {
1388     const uint8_t *datag = frame->data[0];
1389     const uint8_t *datab = frame->data[1];
1390     const uint8_t *datar = frame->data[2];
1391     const int glinesize  = frame->linesize[0];
1392     const int blinesize  = frame->linesize[1];
1393     const int rlinesize  = frame->linesize[2];
1394     const int w = lut3d->clut_width;
1395     const int level = lut3d->lutsize;
1396     const int level2 = lut3d->lutsize2;
1397
1398     int i, j, k, x = 0, y = 0;
1399
1400     for (k = 0; k < level; k++) {
1401         for (j = 0; j < level; j++) {
1402             for (i = 0; i < level; i++) {
1403                 const float *gsrc = (const float *)(datag + y*glinesize);
1404                 const float *bsrc = (const float *)(datab + y*blinesize);
1405                 const float *rsrc = (const float *)(datar + y*rlinesize);
1406                 struct rgbvec *vec = &lut3d->lut[i * level2 + j * level + k];
1407                 vec->r = rsrc[x];
1408                 vec->g = gsrc[x];
1409                 vec->b = bsrc[x];
1410                 if (++x == w) {
1411                     x = 0;
1412                     y++;
1413                 }
1414             }
1415         }
1416     }
1417 }
1418
1419 static int config_output(AVFilterLink *outlink)
1420 {
1421     AVFilterContext *ctx = outlink->src;
1422     LUT3DContext *lut3d = ctx->priv;
1423     int ret;
1424
1425     ret = ff_framesync_init_dualinput(&lut3d->fs, ctx);
1426     if (ret < 0)
1427         return ret;
1428     outlink->w = ctx->inputs[0]->w;
1429     outlink->h = ctx->inputs[0]->h;
1430     outlink->time_base = ctx->inputs[0]->time_base;
1431     if ((ret = ff_framesync_configure(&lut3d->fs)) < 0)
1432         return ret;
1433     return 0;
1434 }
1435
1436 static int activate(AVFilterContext *ctx)
1437 {
1438     LUT3DContext *s = ctx->priv;
1439     return ff_framesync_activate(&s->fs);
1440 }
1441
1442 static int config_clut(AVFilterLink *inlink)
1443 {
1444     int size, level, w, h;
1445     AVFilterContext *ctx = inlink->dst;
1446     LUT3DContext *lut3d = ctx->priv;
1447     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
1448
1449     av_assert0(desc);
1450
1451     lut3d->clut_bits = desc->comp[0].depth;
1452     lut3d->clut_planar = av_pix_fmt_count_planes(inlink->format) > 1;
1453     lut3d->clut_float = desc->flags & AV_PIX_FMT_FLAG_FLOAT;
1454
1455     lut3d->clut_step = av_get_padded_bits_per_pixel(desc) >> 3;
1456     ff_fill_rgba_map(lut3d->clut_rgba_map, inlink->format);
1457
1458     if (inlink->w > inlink->h)
1459         av_log(ctx, AV_LOG_INFO, "Padding on the right (%dpx) of the "
1460                "Hald CLUT will be ignored\n", inlink->w - inlink->h);
1461     else if (inlink->w < inlink->h)
1462         av_log(ctx, AV_LOG_INFO, "Padding at the bottom (%dpx) of the "
1463                "Hald CLUT will be ignored\n", inlink->h - inlink->w);
1464     lut3d->clut_width = w = h = FFMIN(inlink->w, inlink->h);
1465
1466     for (level = 1; level*level*level < w; level++);
1467     size = level*level*level;
1468     if (size != w) {
1469         av_log(ctx, AV_LOG_WARNING, "The Hald CLUT width does not match the level\n");
1470         return AVERROR_INVALIDDATA;
1471     }
1472     av_assert0(w == h && w == size);
1473     level *= level;
1474     if (level > MAX_LEVEL) {
1475         const int max_clut_level = sqrt(MAX_LEVEL);
1476         const int max_clut_size  = max_clut_level*max_clut_level*max_clut_level;
1477         av_log(ctx, AV_LOG_ERROR, "Too large Hald CLUT "
1478                "(maximum level is %d, or %dx%d CLUT)\n",
1479                max_clut_level, max_clut_size, max_clut_size);
1480         return AVERROR(EINVAL);
1481     }
1482
1483     return allocate_3dlut(ctx, level, 0);
1484 }
1485
1486 static int update_apply_clut(FFFrameSync *fs)
1487 {
1488     AVFilterContext *ctx = fs->parent;
1489     LUT3DContext *lut3d = ctx->priv;
1490     AVFilterLink *inlink = ctx->inputs[0];
1491     AVFrame *master, *second, *out;
1492     int ret;
1493
1494     ret = ff_framesync_dualinput_get(fs, &master, &second);
1495     if (ret < 0)
1496         return ret;
1497     if (!second)
1498         return ff_filter_frame(ctx->outputs[0], master);
1499     if (lut3d->clut_float)
1500         update_clut_float(ctx->priv, second);
1501     else if (lut3d->clut_planar)
1502         update_clut_planar(ctx->priv, second);
1503     else
1504         update_clut_packed(ctx->priv, second);
1505     out = apply_lut(inlink, master);
1506     return ff_filter_frame(ctx->outputs[0], out);
1507 }
1508
1509 static av_cold int haldclut_init(AVFilterContext *ctx)
1510 {
1511     LUT3DContext *lut3d = ctx->priv;
1512     lut3d->scale.r = lut3d->scale.g = lut3d->scale.b = 1.f;
1513     lut3d->fs.on_event = update_apply_clut;
1514     return 0;
1515 }
1516
1517 static av_cold void haldclut_uninit(AVFilterContext *ctx)
1518 {
1519     LUT3DContext *lut3d = ctx->priv;
1520     ff_framesync_uninit(&lut3d->fs);
1521     av_freep(&lut3d->lut);
1522 }
1523
1524 static const AVOption haldclut_options[] = {
1525     COMMON_OPTIONS
1526 };
1527
1528 FRAMESYNC_DEFINE_CLASS(haldclut, LUT3DContext, fs);
1529
1530 static const AVFilterPad haldclut_inputs[] = {
1531     {
1532         .name         = "main",
1533         .type         = AVMEDIA_TYPE_VIDEO,
1534         .config_props = config_input,
1535     },{
1536         .name         = "clut",
1537         .type         = AVMEDIA_TYPE_VIDEO,
1538         .config_props = config_clut,
1539     },
1540     { NULL }
1541 };
1542
1543 static const AVFilterPad haldclut_outputs[] = {
1544     {
1545         .name          = "default",
1546         .type          = AVMEDIA_TYPE_VIDEO,
1547         .config_props  = config_output,
1548     },
1549     { NULL }
1550 };
1551
1552 AVFilter ff_vf_haldclut = {
1553     .name          = "haldclut",
1554     .description   = NULL_IF_CONFIG_SMALL("Adjust colors using a Hald CLUT."),
1555     .priv_size     = sizeof(LUT3DContext),
1556     .preinit       = haldclut_framesync_preinit,
1557     .init          = haldclut_init,
1558     .uninit        = haldclut_uninit,
1559     .query_formats = query_formats,
1560     .activate      = activate,
1561     .inputs        = haldclut_inputs,
1562     .outputs       = haldclut_outputs,
1563     .priv_class    = &haldclut_class,
1564     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL | AVFILTER_FLAG_SLICE_THREADS,
1565 };
1566 #endif
1567
1568 #if CONFIG_LUT1D_FILTER
1569
1570 enum interp_1d_mode {
1571     INTERPOLATE_1D_NEAREST,
1572     INTERPOLATE_1D_LINEAR,
1573     INTERPOLATE_1D_CUBIC,
1574     INTERPOLATE_1D_COSINE,
1575     INTERPOLATE_1D_SPLINE,
1576     NB_INTERP_1D_MODE
1577 };
1578
1579 #define MAX_1D_LEVEL 65536
1580
1581 typedef struct LUT1DContext {
1582     const AVClass *class;
1583     char *file;
1584     int interpolation;          ///<interp_1d_mode
1585     struct rgbvec scale;
1586     uint8_t rgba_map[4];
1587     int step;
1588     float lut[3][MAX_1D_LEVEL];
1589     int lutsize;
1590     avfilter_action_func *interp;
1591 } LUT1DContext;
1592
1593 #undef OFFSET
1594 #define OFFSET(x) offsetof(LUT1DContext, x)
1595
1596 static void set_identity_matrix_1d(LUT1DContext *lut1d, int size)
1597 {
1598     const float c = 1. / (size - 1);
1599     int i;
1600
1601     lut1d->lutsize = size;
1602     for (i = 0; i < size; i++) {
1603         lut1d->lut[0][i] = i * c;
1604         lut1d->lut[1][i] = i * c;
1605         lut1d->lut[2][i] = i * c;
1606     }
1607 }
1608
1609 static int parse_cinespace_1d(AVFilterContext *ctx, FILE *f)
1610 {
1611     LUT1DContext *lut1d = ctx->priv;
1612     char line[MAX_LINE_SIZE];
1613     float in_min[3]  = {0.0, 0.0, 0.0};
1614     float in_max[3]  = {1.0, 1.0, 1.0};
1615     float out_min[3] = {0.0, 0.0, 0.0};
1616     float out_max[3] = {1.0, 1.0, 1.0};
1617     int inside_metadata = 0, size;
1618
1619     NEXT_LINE(skip_line(line));
1620     if (strncmp(line, "CSPLUTV100", 10)) {
1621         av_log(ctx, AV_LOG_ERROR, "Not cineSpace LUT format\n");
1622         return AVERROR(EINVAL);
1623     }
1624
1625     NEXT_LINE(skip_line(line));
1626     if (strncmp(line, "1D", 2)) {
1627         av_log(ctx, AV_LOG_ERROR, "Not 1D LUT format\n");
1628         return AVERROR(EINVAL);
1629     }
1630
1631     while (1) {
1632         NEXT_LINE(skip_line(line));
1633
1634         if (!strncmp(line, "BEGIN METADATA", 14)) {
1635             inside_metadata = 1;
1636             continue;
1637         }
1638         if (!strncmp(line, "END METADATA", 12)) {
1639             inside_metadata = 0;
1640             continue;
1641         }
1642         if (inside_metadata == 0) {
1643             for (int i = 0; i < 3; i++) {
1644                 int npoints = strtol(line, NULL, 0);
1645
1646                 if (npoints != 2) {
1647                     av_log(ctx, AV_LOG_ERROR, "Unsupported number of pre-lut points.\n");
1648                     return AVERROR_PATCHWELCOME;
1649                 }
1650
1651                 NEXT_LINE(skip_line(line));
1652                 if (av_sscanf(line, "%f %f", &in_min[i], &in_max[i]) != 2)
1653                     return AVERROR_INVALIDDATA;
1654                 NEXT_LINE(skip_line(line));
1655                 if (av_sscanf(line, "%f %f", &out_min[i], &out_max[i]) != 2)
1656                     return AVERROR_INVALIDDATA;
1657                 NEXT_LINE(skip_line(line));
1658             }
1659
1660             size = strtol(line, NULL, 0);
1661
1662             if (size < 2 || size > MAX_1D_LEVEL) {
1663                 av_log(ctx, AV_LOG_ERROR, "Too large or invalid 1D LUT size\n");
1664                 return AVERROR(EINVAL);
1665             }
1666
1667             lut1d->lutsize = size;
1668
1669             for (int i = 0; i < size; i++) {
1670                 NEXT_LINE(skip_line(line));
1671                 if (av_sscanf(line, "%f %f %f", &lut1d->lut[0][i], &lut1d->lut[1][i], &lut1d->lut[2][i]) != 3)
1672                     return AVERROR_INVALIDDATA;
1673                 lut1d->lut[0][i] *= out_max[0] - out_min[0];
1674                 lut1d->lut[1][i] *= out_max[1] - out_min[1];
1675                 lut1d->lut[2][i] *= out_max[2] - out_min[2];
1676             }
1677
1678             break;
1679         }
1680     }
1681
1682     lut1d->scale.r = av_clipf(1. / (in_max[0] - in_min[0]), 0.f, 1.f);
1683     lut1d->scale.g = av_clipf(1. / (in_max[1] - in_min[1]), 0.f, 1.f);
1684     lut1d->scale.b = av_clipf(1. / (in_max[2] - in_min[2]), 0.f, 1.f);
1685
1686     return 0;
1687 }
1688
1689 static int parse_cube_1d(AVFilterContext *ctx, FILE *f)
1690 {
1691     LUT1DContext *lut1d = ctx->priv;
1692     char line[MAX_LINE_SIZE];
1693     float min[3] = {0.0, 0.0, 0.0};
1694     float max[3] = {1.0, 1.0, 1.0};
1695
1696     while (fgets(line, sizeof(line), f)) {
1697         if (!strncmp(line, "LUT_1D_SIZE", 11)) {
1698             const int size = strtol(line + 12, NULL, 0);
1699             int i;
1700
1701             if (size < 2 || size > MAX_1D_LEVEL) {
1702                 av_log(ctx, AV_LOG_ERROR, "Too large or invalid 1D LUT size\n");
1703                 return AVERROR(EINVAL);
1704             }
1705             lut1d->lutsize = size;
1706             for (i = 0; i < size; i++) {
1707                 do {
1708 try_again:
1709                     NEXT_LINE(0);
1710                     if (!strncmp(line, "DOMAIN_", 7)) {
1711                         float *vals = NULL;
1712                         if      (!strncmp(line + 7, "MIN ", 4)) vals = min;
1713                         else if (!strncmp(line + 7, "MAX ", 4)) vals = max;
1714                         if (!vals)
1715                             return AVERROR_INVALIDDATA;
1716                         av_sscanf(line + 11, "%f %f %f", vals, vals + 1, vals + 2);
1717                         av_log(ctx, AV_LOG_DEBUG, "min: %f %f %f | max: %f %f %f\n",
1718                                min[0], min[1], min[2], max[0], max[1], max[2]);
1719                         goto try_again;
1720                     } else if (!strncmp(line, "LUT_1D_INPUT_RANGE ", 19)) {
1721                         av_sscanf(line + 19, "%f %f", min, max);
1722                         min[1] = min[2] = min[0];
1723                         max[1] = max[2] = max[0];
1724                         goto try_again;
1725                     } else if (!strncmp(line, "TITLE", 5)) {
1726                         goto try_again;
1727                     }
1728                 } while (skip_line(line));
1729                 if (av_sscanf(line, "%f %f %f", &lut1d->lut[0][i], &lut1d->lut[1][i], &lut1d->lut[2][i]) != 3)
1730                     return AVERROR_INVALIDDATA;
1731             }
1732             break;
1733         }
1734     }
1735
1736     lut1d->scale.r = av_clipf(1. / (max[0] - min[0]), 0.f, 1.f);
1737     lut1d->scale.g = av_clipf(1. / (max[1] - min[1]), 0.f, 1.f);
1738     lut1d->scale.b = av_clipf(1. / (max[2] - min[2]), 0.f, 1.f);
1739
1740     return 0;
1741 }
1742
1743 static const AVOption lut1d_options[] = {
1744     { "file", "set 1D LUT file name", OFFSET(file), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
1745     { "interp", "select interpolation mode", OFFSET(interpolation),    AV_OPT_TYPE_INT, {.i64=INTERPOLATE_1D_LINEAR}, 0, NB_INTERP_1D_MODE-1, FLAGS, "interp_mode" },
1746         { "nearest", "use values from the nearest defined points", 0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_1D_NEAREST},   INT_MIN, INT_MAX, FLAGS, "interp_mode" },
1747         { "linear",  "use values from the linear interpolation",   0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_1D_LINEAR},    INT_MIN, INT_MAX, FLAGS, "interp_mode" },
1748         { "cosine",  "use values from the cosine interpolation",   0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_1D_COSINE},    INT_MIN, INT_MAX, FLAGS, "interp_mode" },
1749         { "cubic",   "use values from the cubic interpolation",    0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_1D_CUBIC},     INT_MIN, INT_MAX, FLAGS, "interp_mode" },
1750         { "spline",  "use values from the spline interpolation",   0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_1D_SPLINE},    INT_MIN, INT_MAX, FLAGS, "interp_mode" },
1751     { NULL }
1752 };
1753
1754 AVFILTER_DEFINE_CLASS(lut1d);
1755
1756 static inline float interp_1d_nearest(const LUT1DContext *lut1d,
1757                                       int idx, const float s)
1758 {
1759     return lut1d->lut[idx][NEAR(s)];
1760 }
1761
1762 #define NEXT1D(x) (FFMIN((int)(x) + 1, lut1d->lutsize - 1))
1763
1764 static inline float interp_1d_linear(const LUT1DContext *lut1d,
1765                                      int idx, const float s)
1766 {
1767     const int prev = PREV(s);
1768     const int next = NEXT1D(s);
1769     const float d = s - prev;
1770     const float p = lut1d->lut[idx][prev];
1771     const float n = lut1d->lut[idx][next];
1772
1773     return lerpf(p, n, d);
1774 }
1775
1776 static inline float interp_1d_cosine(const LUT1DContext *lut1d,
1777                                      int idx, const float s)
1778 {
1779     const int prev = PREV(s);
1780     const int next = NEXT1D(s);
1781     const float d = s - prev;
1782     const float p = lut1d->lut[idx][prev];
1783     const float n = lut1d->lut[idx][next];
1784     const float m = (1.f - cosf(d * M_PI)) * .5f;
1785
1786     return lerpf(p, n, m);
1787 }
1788
1789 static inline float interp_1d_cubic(const LUT1DContext *lut1d,
1790                                     int idx, const float s)
1791 {
1792     const int prev = PREV(s);
1793     const int next = NEXT1D(s);
1794     const float mu = s - prev;
1795     float a0, a1, a2, a3, mu2;
1796
1797     float y0 = lut1d->lut[idx][FFMAX(prev - 1, 0)];
1798     float y1 = lut1d->lut[idx][prev];
1799     float y2 = lut1d->lut[idx][next];
1800     float y3 = lut1d->lut[idx][FFMIN(next + 1, lut1d->lutsize - 1)];
1801
1802
1803     mu2 = mu * mu;
1804     a0 = y3 - y2 - y0 + y1;
1805     a1 = y0 - y1 - a0;
1806     a2 = y2 - y0;
1807     a3 = y1;
1808
1809     return a0 * mu * mu2 + a1 * mu2 + a2 * mu + a3;
1810 }
1811
1812 static inline float interp_1d_spline(const LUT1DContext *lut1d,
1813                                      int idx, const float s)
1814 {
1815     const int prev = PREV(s);
1816     const int next = NEXT1D(s);
1817     const float x = s - prev;
1818     float c0, c1, c2, c3;
1819
1820     float y0 = lut1d->lut[idx][FFMAX(prev - 1, 0)];
1821     float y1 = lut1d->lut[idx][prev];
1822     float y2 = lut1d->lut[idx][next];
1823     float y3 = lut1d->lut[idx][FFMIN(next + 1, lut1d->lutsize - 1)];
1824
1825     c0 = y1;
1826     c1 = .5f * (y2 - y0);
1827     c2 = y0 - 2.5f * y1 + 2.f * y2 - .5f * y3;
1828     c3 = .5f * (y3 - y0) + 1.5f * (y1 - y2);
1829
1830     return ((c3 * x + c2) * x + c1) * x + c0;
1831 }
1832
1833 #define DEFINE_INTERP_FUNC_PLANAR_1D(name, nbits, depth)                     \
1834 static int interp_1d_##nbits##_##name##_p##depth(AVFilterContext *ctx,       \
1835                                                  void *arg, int jobnr,       \
1836                                                  int nb_jobs)                \
1837 {                                                                            \
1838     int x, y;                                                                \
1839     const LUT1DContext *lut1d = ctx->priv;                                   \
1840     const ThreadData *td = arg;                                              \
1841     const AVFrame *in  = td->in;                                             \
1842     const AVFrame *out = td->out;                                            \
1843     const int direct = out == in;                                            \
1844     const int slice_start = (in->height *  jobnr   ) / nb_jobs;              \
1845     const int slice_end   = (in->height * (jobnr+1)) / nb_jobs;              \
1846     uint8_t *grow = out->data[0] + slice_start * out->linesize[0];           \
1847     uint8_t *brow = out->data[1] + slice_start * out->linesize[1];           \
1848     uint8_t *rrow = out->data[2] + slice_start * out->linesize[2];           \
1849     uint8_t *arow = out->data[3] + slice_start * out->linesize[3];           \
1850     const uint8_t *srcgrow = in->data[0] + slice_start * in->linesize[0];    \
1851     const uint8_t *srcbrow = in->data[1] + slice_start * in->linesize[1];    \
1852     const uint8_t *srcrrow = in->data[2] + slice_start * in->linesize[2];    \
1853     const uint8_t *srcarow = in->data[3] + slice_start * in->linesize[3];    \
1854     const float factor = (1 << depth) - 1;                                   \
1855     const float scale_r = (lut1d->scale.r / factor) * (lut1d->lutsize - 1);  \
1856     const float scale_g = (lut1d->scale.g / factor) * (lut1d->lutsize - 1);  \
1857     const float scale_b = (lut1d->scale.b / factor) * (lut1d->lutsize - 1);  \
1858                                                                              \
1859     for (y = slice_start; y < slice_end; y++) {                              \
1860         uint##nbits##_t *dstg = (uint##nbits##_t *)grow;                     \
1861         uint##nbits##_t *dstb = (uint##nbits##_t *)brow;                     \
1862         uint##nbits##_t *dstr = (uint##nbits##_t *)rrow;                     \
1863         uint##nbits##_t *dsta = (uint##nbits##_t *)arow;                     \
1864         const uint##nbits##_t *srcg = (const uint##nbits##_t *)srcgrow;      \
1865         const uint##nbits##_t *srcb = (const uint##nbits##_t *)srcbrow;      \
1866         const uint##nbits##_t *srcr = (const uint##nbits##_t *)srcrrow;      \
1867         const uint##nbits##_t *srca = (const uint##nbits##_t *)srcarow;      \
1868         for (x = 0; x < in->width; x++) {                                    \
1869             float r = srcr[x] * scale_r;                                     \
1870             float g = srcg[x] * scale_g;                                     \
1871             float b = srcb[x] * scale_b;                                     \
1872             r = interp_1d_##name(lut1d, 0, r);                               \
1873             g = interp_1d_##name(lut1d, 1, g);                               \
1874             b = interp_1d_##name(lut1d, 2, b);                               \
1875             dstr[x] = av_clip_uintp2(r * factor, depth);                     \
1876             dstg[x] = av_clip_uintp2(g * factor, depth);                     \
1877             dstb[x] = av_clip_uintp2(b * factor, depth);                     \
1878             if (!direct && in->linesize[3])                                  \
1879                 dsta[x] = srca[x];                                           \
1880         }                                                                    \
1881         grow += out->linesize[0];                                            \
1882         brow += out->linesize[1];                                            \
1883         rrow += out->linesize[2];                                            \
1884         arow += out->linesize[3];                                            \
1885         srcgrow += in->linesize[0];                                          \
1886         srcbrow += in->linesize[1];                                          \
1887         srcrrow += in->linesize[2];                                          \
1888         srcarow += in->linesize[3];                                          \
1889     }                                                                        \
1890     return 0;                                                                \
1891 }
1892
1893 DEFINE_INTERP_FUNC_PLANAR_1D(nearest,     8, 8)
1894 DEFINE_INTERP_FUNC_PLANAR_1D(linear,      8, 8)
1895 DEFINE_INTERP_FUNC_PLANAR_1D(cosine,      8, 8)
1896 DEFINE_INTERP_FUNC_PLANAR_1D(cubic,       8, 8)
1897 DEFINE_INTERP_FUNC_PLANAR_1D(spline,      8, 8)
1898
1899 DEFINE_INTERP_FUNC_PLANAR_1D(nearest,     16, 9)
1900 DEFINE_INTERP_FUNC_PLANAR_1D(linear,      16, 9)
1901 DEFINE_INTERP_FUNC_PLANAR_1D(cosine,      16, 9)
1902 DEFINE_INTERP_FUNC_PLANAR_1D(cubic,       16, 9)
1903 DEFINE_INTERP_FUNC_PLANAR_1D(spline,      16, 9)
1904
1905 DEFINE_INTERP_FUNC_PLANAR_1D(nearest,     16, 10)
1906 DEFINE_INTERP_FUNC_PLANAR_1D(linear,      16, 10)
1907 DEFINE_INTERP_FUNC_PLANAR_1D(cosine,      16, 10)
1908 DEFINE_INTERP_FUNC_PLANAR_1D(cubic,       16, 10)
1909 DEFINE_INTERP_FUNC_PLANAR_1D(spline,      16, 10)
1910
1911 DEFINE_INTERP_FUNC_PLANAR_1D(nearest,     16, 12)
1912 DEFINE_INTERP_FUNC_PLANAR_1D(linear,      16, 12)
1913 DEFINE_INTERP_FUNC_PLANAR_1D(cosine,      16, 12)
1914 DEFINE_INTERP_FUNC_PLANAR_1D(cubic,       16, 12)
1915 DEFINE_INTERP_FUNC_PLANAR_1D(spline,      16, 12)
1916
1917 DEFINE_INTERP_FUNC_PLANAR_1D(nearest,     16, 14)
1918 DEFINE_INTERP_FUNC_PLANAR_1D(linear,      16, 14)
1919 DEFINE_INTERP_FUNC_PLANAR_1D(cosine,      16, 14)
1920 DEFINE_INTERP_FUNC_PLANAR_1D(cubic,       16, 14)
1921 DEFINE_INTERP_FUNC_PLANAR_1D(spline,      16, 14)
1922
1923 DEFINE_INTERP_FUNC_PLANAR_1D(nearest,     16, 16)
1924 DEFINE_INTERP_FUNC_PLANAR_1D(linear,      16, 16)
1925 DEFINE_INTERP_FUNC_PLANAR_1D(cosine,      16, 16)
1926 DEFINE_INTERP_FUNC_PLANAR_1D(cubic,       16, 16)
1927 DEFINE_INTERP_FUNC_PLANAR_1D(spline,      16, 16)
1928
1929 #define DEFINE_INTERP_FUNC_PLANAR_1D_FLOAT(name, depth)                      \
1930 static int interp_1d_##name##_pf##depth(AVFilterContext *ctx,                \
1931                                                  void *arg, int jobnr,       \
1932                                                  int nb_jobs)                \
1933 {                                                                            \
1934     int x, y;                                                                \
1935     const LUT1DContext *lut1d = ctx->priv;                                   \
1936     const ThreadData *td = arg;                                              \
1937     const AVFrame *in  = td->in;                                             \
1938     const AVFrame *out = td->out;                                            \
1939     const int direct = out == in;                                            \
1940     const int slice_start = (in->height *  jobnr   ) / nb_jobs;              \
1941     const int slice_end   = (in->height * (jobnr+1)) / nb_jobs;              \
1942     uint8_t *grow = out->data[0] + slice_start * out->linesize[0];           \
1943     uint8_t *brow = out->data[1] + slice_start * out->linesize[1];           \
1944     uint8_t *rrow = out->data[2] + slice_start * out->linesize[2];           \
1945     uint8_t *arow = out->data[3] + slice_start * out->linesize[3];           \
1946     const uint8_t *srcgrow = in->data[0] + slice_start * in->linesize[0];    \
1947     const uint8_t *srcbrow = in->data[1] + slice_start * in->linesize[1];    \
1948     const uint8_t *srcrrow = in->data[2] + slice_start * in->linesize[2];    \
1949     const uint8_t *srcarow = in->data[3] + slice_start * in->linesize[3];    \
1950     const float lutsize = lut1d->lutsize - 1;                                \
1951     const float scale_r = lut1d->scale.r * lutsize;                          \
1952     const float scale_g = lut1d->scale.g * lutsize;                          \
1953     const float scale_b = lut1d->scale.b * lutsize;                          \
1954                                                                              \
1955     for (y = slice_start; y < slice_end; y++) {                              \
1956         float *dstg = (float *)grow;                                         \
1957         float *dstb = (float *)brow;                                         \
1958         float *dstr = (float *)rrow;                                         \
1959         float *dsta = (float *)arow;                                         \
1960         const float *srcg = (const float *)srcgrow;                          \
1961         const float *srcb = (const float *)srcbrow;                          \
1962         const float *srcr = (const float *)srcrrow;                          \
1963         const float *srca = (const float *)srcarow;                          \
1964         for (x = 0; x < in->width; x++) {                                    \
1965             float r = av_clipf(sanitizef(srcr[x]) * scale_r, 0.0f, lutsize); \
1966             float g = av_clipf(sanitizef(srcg[x]) * scale_g, 0.0f, lutsize); \
1967             float b = av_clipf(sanitizef(srcb[x]) * scale_b, 0.0f, lutsize); \
1968             r = interp_1d_##name(lut1d, 0, r);                               \
1969             g = interp_1d_##name(lut1d, 1, g);                               \
1970             b = interp_1d_##name(lut1d, 2, b);                               \
1971             dstr[x] = r;                                                     \
1972             dstg[x] = g;                                                     \
1973             dstb[x] = b;                                                     \
1974             if (!direct && in->linesize[3])                                  \
1975                 dsta[x] = srca[x];                                           \
1976         }                                                                    \
1977         grow += out->linesize[0];                                            \
1978         brow += out->linesize[1];                                            \
1979         rrow += out->linesize[2];                                            \
1980         arow += out->linesize[3];                                            \
1981         srcgrow += in->linesize[0];                                          \
1982         srcbrow += in->linesize[1];                                          \
1983         srcrrow += in->linesize[2];                                          \
1984         srcarow += in->linesize[3];                                          \
1985     }                                                                        \
1986     return 0;                                                                \
1987 }
1988
1989 DEFINE_INTERP_FUNC_PLANAR_1D_FLOAT(nearest, 32)
1990 DEFINE_INTERP_FUNC_PLANAR_1D_FLOAT(linear,  32)
1991 DEFINE_INTERP_FUNC_PLANAR_1D_FLOAT(cosine,  32)
1992 DEFINE_INTERP_FUNC_PLANAR_1D_FLOAT(cubic,   32)
1993 DEFINE_INTERP_FUNC_PLANAR_1D_FLOAT(spline,  32)
1994
1995 #define DEFINE_INTERP_FUNC_1D(name, nbits)                                   \
1996 static int interp_1d_##nbits##_##name(AVFilterContext *ctx, void *arg,       \
1997                                       int jobnr, int nb_jobs)                \
1998 {                                                                            \
1999     int x, y;                                                                \
2000     const LUT1DContext *lut1d = ctx->priv;                                   \
2001     const ThreadData *td = arg;                                              \
2002     const AVFrame *in  = td->in;                                             \
2003     const AVFrame *out = td->out;                                            \
2004     const int direct = out == in;                                            \
2005     const int step = lut1d->step;                                            \
2006     const uint8_t r = lut1d->rgba_map[R];                                    \
2007     const uint8_t g = lut1d->rgba_map[G];                                    \
2008     const uint8_t b = lut1d->rgba_map[B];                                    \
2009     const uint8_t a = lut1d->rgba_map[A];                                    \
2010     const int slice_start = (in->height *  jobnr   ) / nb_jobs;              \
2011     const int slice_end   = (in->height * (jobnr+1)) / nb_jobs;              \
2012     uint8_t       *dstrow = out->data[0] + slice_start * out->linesize[0];   \
2013     const uint8_t *srcrow = in ->data[0] + slice_start * in ->linesize[0];   \
2014     const float factor = (1 << nbits) - 1;                                   \
2015     const float scale_r = (lut1d->scale.r / factor) * (lut1d->lutsize - 1);  \
2016     const float scale_g = (lut1d->scale.g / factor) * (lut1d->lutsize - 1);  \
2017     const float scale_b = (lut1d->scale.b / factor) * (lut1d->lutsize - 1);  \
2018                                                                              \
2019     for (y = slice_start; y < slice_end; y++) {                              \
2020         uint##nbits##_t *dst = (uint##nbits##_t *)dstrow;                    \
2021         const uint##nbits##_t *src = (const uint##nbits##_t *)srcrow;        \
2022         for (x = 0; x < in->width * step; x += step) {                       \
2023             float rr = src[x + r] * scale_r;                                 \
2024             float gg = src[x + g] * scale_g;                                 \
2025             float bb = src[x + b] * scale_b;                                 \
2026             rr = interp_1d_##name(lut1d, 0, rr);                             \
2027             gg = interp_1d_##name(lut1d, 1, gg);                             \
2028             bb = interp_1d_##name(lut1d, 2, bb);                             \
2029             dst[x + r] = av_clip_uint##nbits(rr * factor);                   \
2030             dst[x + g] = av_clip_uint##nbits(gg * factor);                   \
2031             dst[x + b] = av_clip_uint##nbits(bb * factor);                   \
2032             if (!direct && step == 4)                                        \
2033                 dst[x + a] = src[x + a];                                     \
2034         }                                                                    \
2035         dstrow += out->linesize[0];                                          \
2036         srcrow += in ->linesize[0];                                          \
2037     }                                                                        \
2038     return 0;                                                                \
2039 }
2040
2041 DEFINE_INTERP_FUNC_1D(nearest,     8)
2042 DEFINE_INTERP_FUNC_1D(linear,      8)
2043 DEFINE_INTERP_FUNC_1D(cosine,      8)
2044 DEFINE_INTERP_FUNC_1D(cubic,       8)
2045 DEFINE_INTERP_FUNC_1D(spline,      8)
2046
2047 DEFINE_INTERP_FUNC_1D(nearest,     16)
2048 DEFINE_INTERP_FUNC_1D(linear,      16)
2049 DEFINE_INTERP_FUNC_1D(cosine,      16)
2050 DEFINE_INTERP_FUNC_1D(cubic,       16)
2051 DEFINE_INTERP_FUNC_1D(spline,      16)
2052
2053 static int config_input_1d(AVFilterLink *inlink)
2054 {
2055     int depth, is16bit, isfloat, planar;
2056     LUT1DContext *lut1d = inlink->dst->priv;
2057     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
2058
2059     depth = desc->comp[0].depth;
2060     is16bit = desc->comp[0].depth > 8;
2061     planar = desc->flags & AV_PIX_FMT_FLAG_PLANAR;
2062     isfloat = desc->flags & AV_PIX_FMT_FLAG_FLOAT;
2063     ff_fill_rgba_map(lut1d->rgba_map, inlink->format);
2064     lut1d->step = av_get_padded_bits_per_pixel(desc) >> (3 + is16bit);
2065
2066 #define SET_FUNC_1D(name) do {                                     \
2067     if (planar && !isfloat) {                                      \
2068         switch (depth) {                                           \
2069         case  8: lut1d->interp = interp_1d_8_##name##_p8;   break; \
2070         case  9: lut1d->interp = interp_1d_16_##name##_p9;  break; \
2071         case 10: lut1d->interp = interp_1d_16_##name##_p10; break; \
2072         case 12: lut1d->interp = interp_1d_16_##name##_p12; break; \
2073         case 14: lut1d->interp = interp_1d_16_##name##_p14; break; \
2074         case 16: lut1d->interp = interp_1d_16_##name##_p16; break; \
2075         }                                                          \
2076     } else if (isfloat) { lut1d->interp = interp_1d_##name##_pf32; \
2077     } else if (is16bit) { lut1d->interp = interp_1d_16_##name;     \
2078     } else {              lut1d->interp = interp_1d_8_##name; }    \
2079 } while (0)
2080
2081     switch (lut1d->interpolation) {
2082     case INTERPOLATE_1D_NEAREST:     SET_FUNC_1D(nearest);  break;
2083     case INTERPOLATE_1D_LINEAR:      SET_FUNC_1D(linear);   break;
2084     case INTERPOLATE_1D_COSINE:      SET_FUNC_1D(cosine);   break;
2085     case INTERPOLATE_1D_CUBIC:       SET_FUNC_1D(cubic);    break;
2086     case INTERPOLATE_1D_SPLINE:      SET_FUNC_1D(spline);   break;
2087     default:
2088         av_assert0(0);
2089     }
2090
2091     return 0;
2092 }
2093
2094 static av_cold int lut1d_init(AVFilterContext *ctx)
2095 {
2096     int ret;
2097     FILE *f;
2098     const char *ext;
2099     LUT1DContext *lut1d = ctx->priv;
2100
2101     lut1d->scale.r = lut1d->scale.g = lut1d->scale.b = 1.f;
2102
2103     if (!lut1d->file) {
2104         set_identity_matrix_1d(lut1d, 32);
2105         return 0;
2106     }
2107
2108     f = av_fopen_utf8(lut1d->file, "r");
2109     if (!f) {
2110         ret = AVERROR(errno);
2111         av_log(ctx, AV_LOG_ERROR, "%s: %s\n", lut1d->file, av_err2str(ret));
2112         return ret;
2113     }
2114
2115     ext = strrchr(lut1d->file, '.');
2116     if (!ext) {
2117         av_log(ctx, AV_LOG_ERROR, "Unable to guess the format from the extension\n");
2118         ret = AVERROR_INVALIDDATA;
2119         goto end;
2120     }
2121     ext++;
2122
2123     if (!av_strcasecmp(ext, "cube") || !av_strcasecmp(ext, "1dlut")) {
2124         ret = parse_cube_1d(ctx, f);
2125     } else if (!av_strcasecmp(ext, "csp")) {
2126         ret = parse_cinespace_1d(ctx, f);
2127     } else {
2128         av_log(ctx, AV_LOG_ERROR, "Unrecognized '.%s' file type\n", ext);
2129         ret = AVERROR(EINVAL);
2130     }
2131
2132     if (!ret && !lut1d->lutsize) {
2133         av_log(ctx, AV_LOG_ERROR, "1D LUT is empty\n");
2134         ret = AVERROR_INVALIDDATA;
2135     }
2136
2137 end:
2138     fclose(f);
2139     return ret;
2140 }
2141
2142 static AVFrame *apply_1d_lut(AVFilterLink *inlink, AVFrame *in)
2143 {
2144     AVFilterContext *ctx = inlink->dst;
2145     LUT1DContext *lut1d = ctx->priv;
2146     AVFilterLink *outlink = inlink->dst->outputs[0];
2147     AVFrame *out;
2148     ThreadData td;
2149
2150     if (av_frame_is_writable(in)) {
2151         out = in;
2152     } else {
2153         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
2154         if (!out) {
2155             av_frame_free(&in);
2156             return NULL;
2157         }
2158         av_frame_copy_props(out, in);
2159     }
2160
2161     td.in  = in;
2162     td.out = out;
2163     ctx->internal->execute(ctx, lut1d->interp, &td, NULL, FFMIN(outlink->h, ff_filter_get_nb_threads(ctx)));
2164
2165     if (out != in)
2166         av_frame_free(&in);
2167
2168     return out;
2169 }
2170
2171 static int filter_frame_1d(AVFilterLink *inlink, AVFrame *in)
2172 {
2173     AVFilterLink *outlink = inlink->dst->outputs[0];
2174     AVFrame *out = apply_1d_lut(inlink, in);
2175     if (!out)
2176         return AVERROR(ENOMEM);
2177     return ff_filter_frame(outlink, out);
2178 }
2179
2180 static const AVFilterPad lut1d_inputs[] = {
2181     {
2182         .name         = "default",
2183         .type         = AVMEDIA_TYPE_VIDEO,
2184         .filter_frame = filter_frame_1d,
2185         .config_props = config_input_1d,
2186     },
2187     { NULL }
2188 };
2189
2190 static const AVFilterPad lut1d_outputs[] = {
2191     {
2192         .name = "default",
2193         .type = AVMEDIA_TYPE_VIDEO,
2194     },
2195     { NULL }
2196 };
2197
2198 AVFilter ff_vf_lut1d = {
2199     .name          = "lut1d",
2200     .description   = NULL_IF_CONFIG_SMALL("Adjust colors using a 1D LUT."),
2201     .priv_size     = sizeof(LUT1DContext),
2202     .init          = lut1d_init,
2203     .query_formats = query_formats,
2204     .inputs        = lut1d_inputs,
2205     .outputs       = lut1d_outputs,
2206     .priv_class    = &lut1d_class,
2207     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC | AVFILTER_FLAG_SLICE_THREADS,
2208 };
2209 #endif