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