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