]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_lut3d.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavfilter / vf_lut3d.c
1 /*
2  * Copyright (c) 2013 Clément Bœsch
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * 3D Lookup table filter
24  */
25
26 #include "libavutil/opt.h"
27 #include "libavutil/file.h"
28 #include "libavutil/intreadwrite.h"
29 #include "libavutil/avassert.h"
30 #include "libavutil/pixdesc.h"
31 #include "libavutil/avstring.h"
32 #include "avfilter.h"
33 #include "drawutils.h"
34 #include "dualinput.h"
35 #include "formats.h"
36 #include "internal.h"
37 #include "video.h"
38
39 #define R 0
40 #define G 1
41 #define B 2
42 #define A 3
43
44 enum interp_mode {
45     INTERPOLATE_NEAREST,
46     INTERPOLATE_TRILINEAR,
47     INTERPOLATE_TETRAHEDRAL,
48     NB_INTERP_MODE
49 };
50
51 struct rgbvec {
52     float r, g, b;
53 };
54
55 /* 3D LUT don't often go up to level 32, but it is common to have a Hald CLUT
56  * of 512x512 (64x64x64) */
57 #define MAX_LEVEL 64
58
59 typedef struct LUT3DContext {
60     const AVClass *class;
61     enum interp_mode interpolation;
62     char *file;
63     uint8_t rgba_map[4];
64     int step;
65     void (*interp)(const struct LUT3DContext*, AVFrame *out, const AVFrame *in);
66     struct rgbvec lut[MAX_LEVEL][MAX_LEVEL][MAX_LEVEL];
67     int lutsize;
68 #if CONFIG_HALDCLUT_FILTER
69     uint8_t clut_rgba_map[4];
70     int clut_step;
71     int clut_is16bit;
72     int clut_width;
73     FFDualInputContext dinput;
74 #endif
75 } LUT3DContext;
76
77 #define OFFSET(x) offsetof(LUT3DContext, x)
78 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
79 #define COMMON_OPTIONS \
80     { "interp", "select interpolation mode", OFFSET(interpolation), AV_OPT_TYPE_INT, {.i64=INTERPOLATE_TETRAHEDRAL}, 0, NB_INTERP_MODE-1, FLAGS, "interp_mode" }, \
81         { "nearest",     "use values from the nearest defined points",            0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_NEAREST},     INT_MIN, INT_MAX, FLAGS, "interp_mode" }, \
82         { "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" }, \
83         { "tetrahedral", "interpolate values using a tetrahedron",                0, AV_OPT_TYPE_CONST, {.i64=INTERPOLATE_TETRAHEDRAL}, INT_MIN, INT_MAX, FLAGS, "interp_mode" }, \
84     { NULL }
85
86 static inline float lerpf(float v0, float v1, float f)
87 {
88     return v0 + (v1 - v0) * f;
89 }
90
91 static inline struct rgbvec lerp(const struct rgbvec *v0, const struct rgbvec *v1, float f)
92 {
93     struct rgbvec v = {
94         lerpf(v0->r, v1->r, f), lerpf(v0->g, v1->g, f), lerpf(v0->b, v1->b, f)
95     };
96     return v;
97 }
98
99 #define NEAR(x) ((int)((x) + .5))
100 #define PREV(x) ((int)(x))
101 #define NEXT(x) (FFMIN((int)(x) + 1, lut3d->lutsize - 1))
102
103 /**
104  * Get the nearest defined point
105  */
106 static inline struct rgbvec interp_nearest(const LUT3DContext *lut3d,
107                                            const struct rgbvec *s)
108 {
109     return lut3d->lut[NEAR(s->r)][NEAR(s->g)][NEAR(s->b)];
110 }
111
112 /**
113  * Interpolate using the 8 vertices of a cube
114  * @see https://en.wikipedia.org/wiki/Trilinear_interpolation
115  */
116 static inline struct rgbvec interp_trilinear(const LUT3DContext *lut3d,
117                                              const struct rgbvec *s)
118 {
119     const int prev[] = {PREV(s->r), PREV(s->g), PREV(s->b)};
120     const int next[] = {NEXT(s->r), NEXT(s->g), NEXT(s->b)};
121     const struct rgbvec d = {s->r - prev[0], s->g - prev[1], s->b - prev[2]};
122     const struct rgbvec c000 = lut3d->lut[prev[0]][prev[1]][prev[2]];
123     const struct rgbvec c001 = lut3d->lut[prev[0]][prev[1]][next[2]];
124     const struct rgbvec c010 = lut3d->lut[prev[0]][next[1]][prev[2]];
125     const struct rgbvec c011 = lut3d->lut[prev[0]][next[1]][next[2]];
126     const struct rgbvec c100 = lut3d->lut[next[0]][prev[1]][prev[2]];
127     const struct rgbvec c101 = lut3d->lut[next[0]][prev[1]][next[2]];
128     const struct rgbvec c110 = lut3d->lut[next[0]][next[1]][prev[2]];
129     const struct rgbvec c111 = lut3d->lut[next[0]][next[1]][next[2]];
130     const struct rgbvec c00  = lerp(&c000, &c100, d.r);
131     const struct rgbvec c10  = lerp(&c010, &c110, d.r);
132     const struct rgbvec c01  = lerp(&c001, &c101, d.r);
133     const struct rgbvec c11  = lerp(&c011, &c111, d.r);
134     const struct rgbvec c0   = lerp(&c00,  &c10,  d.g);
135     const struct rgbvec c1   = lerp(&c01,  &c11,  d.g);
136     const struct rgbvec c    = lerp(&c0,   &c1,   d.b);
137     return c;
138 }
139
140 /**
141  * Tetrahedral interpolation. Based on code found in Truelight Software Library paper.
142  * @see http://www.filmlight.ltd.uk/pdf/whitepapers/FL-TL-TN-0057-SoftwareLib.pdf
143  */
144 static inline struct rgbvec interp_tetrahedral(const LUT3DContext *lut3d,
145                                                const struct rgbvec *s)
146 {
147     const int prev[] = {PREV(s->r), PREV(s->g), PREV(s->b)};
148     const int next[] = {NEXT(s->r), NEXT(s->g), NEXT(s->b)};
149     const struct rgbvec d = {s->r - prev[0], s->g - prev[1], s->b - prev[2]};
150     const struct rgbvec c000 = lut3d->lut[prev[0]][prev[1]][prev[2]];
151     const struct rgbvec c111 = lut3d->lut[next[0]][next[1]][next[2]];
152     struct rgbvec c;
153     if (d.r > d.g) {
154         if (d.g > d.b) {
155             const struct rgbvec c100 = lut3d->lut[next[0]][prev[1]][prev[2]];
156             const struct rgbvec c110 = lut3d->lut[next[0]][next[1]][prev[2]];
157             c.r = (1-d.r) * c000.r + (d.r-d.g) * c100.r + (d.g-d.b) * c110.r + (d.b) * c111.r;
158             c.g = (1-d.r) * c000.g + (d.r-d.g) * c100.g + (d.g-d.b) * c110.g + (d.b) * c111.g;
159             c.b = (1-d.r) * c000.b + (d.r-d.g) * c100.b + (d.g-d.b) * c110.b + (d.b) * c111.b;
160         } else if (d.r > d.b) {
161             const struct rgbvec c100 = lut3d->lut[next[0]][prev[1]][prev[2]];
162             const struct rgbvec c101 = lut3d->lut[next[0]][prev[1]][next[2]];
163             c.r = (1-d.r) * c000.r + (d.r-d.b) * c100.r + (d.b-d.g) * c101.r + (d.g) * c111.r;
164             c.g = (1-d.r) * c000.g + (d.r-d.b) * c100.g + (d.b-d.g) * c101.g + (d.g) * c111.g;
165             c.b = (1-d.r) * c000.b + (d.r-d.b) * c100.b + (d.b-d.g) * c101.b + (d.g) * c111.b;
166         } else {
167             const struct rgbvec c001 = lut3d->lut[prev[0]][prev[1]][next[2]];
168             const struct rgbvec c101 = lut3d->lut[next[0]][prev[1]][next[2]];
169             c.r = (1-d.b) * c000.r + (d.b-d.r) * c001.r + (d.r-d.g) * c101.r + (d.g) * c111.r;
170             c.g = (1-d.b) * c000.g + (d.b-d.r) * c001.g + (d.r-d.g) * c101.g + (d.g) * c111.g;
171             c.b = (1-d.b) * c000.b + (d.b-d.r) * c001.b + (d.r-d.g) * c101.b + (d.g) * c111.b;
172         }
173     } else {
174         if (d.b > d.g) {
175             const struct rgbvec c001 = lut3d->lut[prev[0]][prev[1]][next[2]];
176             const struct rgbvec c011 = lut3d->lut[prev[0]][next[1]][next[2]];
177             c.r = (1-d.b) * c000.r + (d.b-d.g) * c001.r + (d.g-d.r) * c011.r + (d.r) * c111.r;
178             c.g = (1-d.b) * c000.g + (d.b-d.g) * c001.g + (d.g-d.r) * c011.g + (d.r) * c111.g;
179             c.b = (1-d.b) * c000.b + (d.b-d.g) * c001.b + (d.g-d.r) * c011.b + (d.r) * c111.b;
180         } else if (d.b > d.r) {
181             const struct rgbvec c010 = lut3d->lut[prev[0]][next[1]][prev[2]];
182             const struct rgbvec c011 = lut3d->lut[prev[0]][next[1]][next[2]];
183             c.r = (1-d.g) * c000.r + (d.g-d.b) * c010.r + (d.b-d.r) * c011.r + (d.r) * c111.r;
184             c.g = (1-d.g) * c000.g + (d.g-d.b) * c010.g + (d.b-d.r) * c011.g + (d.r) * c111.g;
185             c.b = (1-d.g) * c000.b + (d.g-d.b) * c010.b + (d.b-d.r) * c011.b + (d.r) * c111.b;
186         } else {
187             const struct rgbvec c010 = lut3d->lut[prev[0]][next[1]][prev[2]];
188             const struct rgbvec c110 = lut3d->lut[next[0]][next[1]][prev[2]];
189             c.r = (1-d.g) * c000.r + (d.g-d.r) * c010.r + (d.r-d.b) * c110.r + (d.b) * c111.r;
190             c.g = (1-d.g) * c000.g + (d.g-d.r) * c010.g + (d.r-d.b) * c110.g + (d.b) * c111.g;
191             c.b = (1-d.g) * c000.b + (d.g-d.r) * c010.b + (d.r-d.b) * c110.b + (d.b) * c111.b;
192         }
193     }
194     return c;
195 }
196
197 #define DEFINE_INTERP_FUNC(name, nbits)                                                             \
198 static void interp_##nbits##_##name(const LUT3DContext *lut3d, AVFrame *out, const AVFrame *in)     \
199 {                                                                                                   \
200     int x, y;                                                                                       \
201     const int direct = out == in;                                                                   \
202     const int step = lut3d->step;                                                                   \
203     const uint8_t r = lut3d->rgba_map[R];                                                           \
204     const uint8_t g = lut3d->rgba_map[G];                                                           \
205     const uint8_t b = lut3d->rgba_map[B];                                                           \
206     const uint8_t a = lut3d->rgba_map[A];                                                           \
207     uint8_t       *dstrow = out->data[0];                                                           \
208     const uint8_t *srcrow = in ->data[0];                                                           \
209                                                                                                     \
210     for (y = 0; y < in->height; y++) {                                                              \
211         uint##nbits##_t *dst = (uint##nbits##_t *)dstrow;                                           \
212         const uint##nbits##_t *src = (const uint##nbits##_t *)srcrow;                               \
213         for (x = 0; x < in->width * step; x += step) {                                              \
214             const float scale = (1. / ((1<<nbits) - 1)) * (lut3d->lutsize - 1);                     \
215             const struct rgbvec scaled_rgb = {src[x + r] * scale,                                   \
216                                               src[x + g] * scale,                                   \
217                                               src[x + b] * scale};                                  \
218             struct rgbvec vec = interp_##name(lut3d, &scaled_rgb);                                  \
219             dst[x + r] = av_clip_uint##nbits(vec.r * (float)((1<<nbits) - 1));                      \
220             dst[x + g] = av_clip_uint##nbits(vec.g * (float)((1<<nbits) - 1));                      \
221             dst[x + b] = av_clip_uint##nbits(vec.b * (float)((1<<nbits) - 1));                      \
222             if (!direct && step == 4)                                                               \
223                 dst[x + a] = src[x + a];                                                            \
224         }                                                                                           \
225         dstrow += out->linesize[0];                                                                 \
226         srcrow += in ->linesize[0];                                                                 \
227     }                                                                                               \
228 }
229
230 DEFINE_INTERP_FUNC(nearest,     8)
231 DEFINE_INTERP_FUNC(trilinear,   8)
232 DEFINE_INTERP_FUNC(tetrahedral, 8)
233
234 DEFINE_INTERP_FUNC(nearest,     16)
235 DEFINE_INTERP_FUNC(trilinear,   16)
236 DEFINE_INTERP_FUNC(tetrahedral, 16)
237
238 #define MAX_LINE_SIZE 512
239
240 static int skip_line(const char *p)
241 {
242     while (*p && av_isspace(*p))
243         p++;
244     return !*p || *p == '#';
245 }
246
247 #define NEXT_LINE(loop_cond) do {                           \
248     if (!fgets(line, sizeof(line), f)) {                    \
249         av_log(ctx, AV_LOG_ERROR, "Unexpected EOF\n");      \
250         return AVERROR_INVALIDDATA;                         \
251     }                                                       \
252 } while (loop_cond)
253
254 /* Basically r g and b float values on each line; seems to be generated by
255  * Davinci */
256 static int parse_dat(AVFilterContext *ctx, FILE *f)
257 {
258     LUT3DContext *lut3d = ctx->priv;
259     const int size = lut3d->lutsize;
260     int i, j, k;
261
262     for (k = 0; k < size; k++) {
263         for (j = 0; j < size; j++) {
264             for (i = 0; i < size; i++) {
265                 char line[MAX_LINE_SIZE];
266                 struct rgbvec *vec = &lut3d->lut[k][j][i];
267                 NEXT_LINE(skip_line(line));
268                 sscanf(line, "%f %f %f", &vec->r, &vec->g, &vec->b);
269             }
270         }
271     }
272     return 0;
273 }
274
275 /* Iridas format */
276 static int parse_cube(AVFilterContext *ctx, FILE *f)
277 {
278     LUT3DContext *lut3d = ctx->priv;
279     char line[MAX_LINE_SIZE];
280     float min[3] = {0.0, 0.0, 0.0};
281     float max[3] = {1.0, 1.0, 1.0};
282
283     while (fgets(line, sizeof(line), f)) {
284         if (!strncmp(line, "LUT_3D_SIZE ", 12)) {
285             int i, j, k;
286             const int size = strtol(line + 12, NULL, 0);
287
288             if (size < 2 || size > MAX_LEVEL) {
289                 av_log(ctx, AV_LOG_ERROR, "Too large or invalid 3D LUT size\n");
290                 return AVERROR(EINVAL);
291             }
292             lut3d->lutsize = size;
293             for (k = 0; k < size; k++) {
294                 for (j = 0; j < size; j++) {
295                     for (i = 0; i < size; i++) {
296                         struct rgbvec *vec = &lut3d->lut[i][j][k];
297
298                         do {
299                             NEXT_LINE(0);
300                             if (!strncmp(line, "DOMAIN_", 7)) {
301                                 float *vals = NULL;
302                                 if      (!strncmp(line + 7, "MIN ", 4)) vals = min;
303                                 else if (!strncmp(line + 7, "MAX ", 4)) vals = max;
304                                 if (!vals)
305                                     return AVERROR_INVALIDDATA;
306                                 sscanf(line + 11, "%f %f %f", vals, vals + 1, vals + 2);
307                                 av_log(ctx, AV_LOG_DEBUG, "min: %f %f %f | max: %f %f %f\n",
308                                        min[0], min[1], min[2], max[0], max[1], max[2]);
309                                 continue;
310                             }
311                         } while (skip_line(line));
312                         if (sscanf(line, "%f %f %f", &vec->r, &vec->g, &vec->b) != 3)
313                             return AVERROR_INVALIDDATA;
314                         vec->r *= max[0] - min[0];
315                         vec->g *= max[1] - min[1];
316                         vec->b *= max[2] - min[2];
317                     }
318                 }
319             }
320             break;
321         }
322     }
323     return 0;
324 }
325
326 /* Assume 17x17x17 LUT with a 16-bit depth
327  * FIXME: it seems there are various 3dl formats */
328 static int parse_3dl(AVFilterContext *ctx, FILE *f)
329 {
330     char line[MAX_LINE_SIZE];
331     LUT3DContext *lut3d = ctx->priv;
332     int i, j, k;
333     const int size = 17;
334     const float scale = 16*16*16;
335
336     lut3d->lutsize = size;
337     NEXT_LINE(skip_line(line));
338     for (k = 0; k < size; k++) {
339         for (j = 0; j < size; j++) {
340             for (i = 0; i < size; i++) {
341                 int r, g, b;
342                 struct rgbvec *vec = &lut3d->lut[k][j][i];
343
344                 NEXT_LINE(skip_line(line));
345                 if (sscanf(line, "%d %d %d", &r, &g, &b) != 3)
346                     return AVERROR_INVALIDDATA;
347                 vec->r = r / scale;
348                 vec->g = g / scale;
349                 vec->b = b / scale;
350             }
351         }
352     }
353     return 0;
354 }
355
356 /* Pandora format */
357 static int parse_m3d(AVFilterContext *ctx, FILE *f)
358 {
359     LUT3DContext *lut3d = ctx->priv;
360     float scale;
361     int i, j, k, size, in = -1, out = -1;
362     char line[MAX_LINE_SIZE];
363     uint8_t rgb_map[3] = {0, 1, 2};
364
365     while (fgets(line, sizeof(line), f)) {
366         if      (!strncmp(line, "in",  2)) in  = strtol(line + 2, NULL, 0);
367         else if (!strncmp(line, "out", 3)) out = strtol(line + 3, NULL, 0);
368         else if (!strncmp(line, "values", 6)) {
369             const char *p = line + 6;
370 #define SET_COLOR(id) do {                  \
371     while (av_isspace(*p))                  \
372         p++;                                \
373     switch (*p) {                           \
374     case 'r': rgb_map[id] = 0; break;       \
375     case 'g': rgb_map[id] = 1; break;       \
376     case 'b': rgb_map[id] = 2; break;       \
377     }                                       \
378     while (*p && !av_isspace(*p))           \
379         p++;                                \
380 } while (0)
381             SET_COLOR(0);
382             SET_COLOR(1);
383             SET_COLOR(2);
384             break;
385         }
386     }
387
388     if (in == -1 || out == -1) {
389         av_log(ctx, AV_LOG_ERROR, "in and out must be defined\n");
390         return AVERROR_INVALIDDATA;
391     }
392     if (in < 2 || out < 2 ||
393         in  > MAX_LEVEL*MAX_LEVEL*MAX_LEVEL ||
394         out > MAX_LEVEL*MAX_LEVEL*MAX_LEVEL) {
395         av_log(ctx, AV_LOG_ERROR, "invalid in (%d) or out (%d)\n", in, out);
396         return AVERROR_INVALIDDATA;
397     }
398     for (size = 1; size*size*size < in; size++);
399     lut3d->lutsize = size;
400     scale = 1. / (out - 1);
401
402     for (k = 0; k < size; k++) {
403         for (j = 0; j < size; j++) {
404             for (i = 0; i < size; i++) {
405                 struct rgbvec *vec = &lut3d->lut[k][j][i];
406                 float val[3];
407
408                 NEXT_LINE(0);
409                 if (sscanf(line, "%f %f %f", val, val + 1, val + 2) != 3)
410                     return AVERROR_INVALIDDATA;
411                 vec->r = val[rgb_map[0]] * scale;
412                 vec->g = val[rgb_map[1]] * scale;
413                 vec->b = val[rgb_map[2]] * scale;
414             }
415         }
416     }
417     return 0;
418 }
419
420 static void set_identity_matrix(LUT3DContext *lut3d, int size)
421 {
422     int i, j, k;
423     const float c = 1. / (size - 1);
424
425     lut3d->lutsize = size;
426     for (k = 0; k < size; k++) {
427         for (j = 0; j < size; j++) {
428             for (i = 0; i < size; i++) {
429                 struct rgbvec *vec = &lut3d->lut[k][j][i];
430                 vec->r = k * c;
431                 vec->g = j * c;
432                 vec->b = i * c;
433             }
434         }
435     }
436 }
437
438 static int query_formats(AVFilterContext *ctx)
439 {
440     static const enum AVPixelFormat pix_fmts[] = {
441         AV_PIX_FMT_RGB24,  AV_PIX_FMT_BGR24,
442         AV_PIX_FMT_RGBA,   AV_PIX_FMT_BGRA,
443         AV_PIX_FMT_ARGB,   AV_PIX_FMT_ABGR,
444         AV_PIX_FMT_0RGB,   AV_PIX_FMT_0BGR,
445         AV_PIX_FMT_RGB0,   AV_PIX_FMT_BGR0,
446         AV_PIX_FMT_RGB48,  AV_PIX_FMT_BGR48,
447         AV_PIX_FMT_RGBA64, AV_PIX_FMT_BGRA64,
448         AV_PIX_FMT_NONE
449     };
450     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
451     return 0;
452 }
453
454 static int config_input(AVFilterLink *inlink)
455 {
456     int is16bit = 0;
457     LUT3DContext *lut3d = inlink->dst->priv;
458     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
459
460     switch (inlink->format) {
461     case AV_PIX_FMT_RGB48:
462     case AV_PIX_FMT_BGR48:
463     case AV_PIX_FMT_RGBA64:
464     case AV_PIX_FMT_BGRA64:
465         is16bit = 1;
466     }
467
468     ff_fill_rgba_map(lut3d->rgba_map, inlink->format);
469     lut3d->step = av_get_padded_bits_per_pixel(desc) >> (3 + is16bit);
470
471 #define SET_FUNC(name) do {                             \
472     if (is16bit) lut3d->interp = interp_16_##name;      \
473     else         lut3d->interp = interp_8_##name;       \
474 } while (0)
475
476     switch (lut3d->interpolation) {
477     case INTERPOLATE_NEAREST:     SET_FUNC(nearest);        break;
478     case INTERPOLATE_TRILINEAR:   SET_FUNC(trilinear);      break;
479     case INTERPOLATE_TETRAHEDRAL: SET_FUNC(tetrahedral);    break;
480     default:
481         av_assert0(0);
482     }
483
484     return 0;
485 }
486
487 static AVFrame *apply_lut(AVFilterLink *inlink, AVFrame *in)
488 {
489     AVFilterContext *ctx = inlink->dst;
490     LUT3DContext *lut3d = ctx->priv;
491     AVFilterLink *outlink = inlink->dst->outputs[0];
492     AVFrame *out;
493
494     if (av_frame_is_writable(in)) {
495         out = in;
496     } else {
497         out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
498         if (!out) {
499             av_frame_free(&in);
500             return NULL;
501         }
502         av_frame_copy_props(out, in);
503     }
504
505     lut3d->interp(lut3d, out, in);
506
507     if (out != in)
508         av_frame_free(&in);
509
510     return out;
511 }
512
513 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
514 {
515     AVFilterLink *outlink = inlink->dst->outputs[0];
516     AVFrame *out = apply_lut(inlink, in);
517     if (!out)
518         return AVERROR(ENOMEM);
519     return ff_filter_frame(outlink, out);
520 }
521
522 #if CONFIG_LUT3D_FILTER
523 static const AVOption lut3d_options[] = {
524     { "file", "set 3D LUT file name", OFFSET(file), AV_OPT_TYPE_STRING, {.str=NULL}, .flags = FLAGS },
525     COMMON_OPTIONS
526 };
527
528 AVFILTER_DEFINE_CLASS(lut3d);
529
530 static av_cold int lut3d_init(AVFilterContext *ctx)
531 {
532     int ret;
533     FILE *f;
534     const char *ext;
535     LUT3DContext *lut3d = ctx->priv;
536
537     if (!lut3d->file) {
538         set_identity_matrix(lut3d, 32);
539         return 0;
540     }
541
542     f = fopen(lut3d->file, "r");
543     if (!f) {
544         ret = AVERROR(errno);
545         av_log(ctx, AV_LOG_ERROR, "%s: %s\n", lut3d->file, av_err2str(ret));
546         return ret;
547     }
548
549     ext = strrchr(lut3d->file, '.');
550     if (!ext) {
551         av_log(ctx, AV_LOG_ERROR, "Unable to guess the format from the extension\n");
552         ret = AVERROR_INVALIDDATA;
553         goto end;
554     }
555     ext++;
556
557     if (!av_strcasecmp(ext, "dat")) {
558         lut3d->lutsize = 33;
559         ret = parse_dat(ctx, f);
560     } else if (!av_strcasecmp(ext, "3dl")) {
561         ret = parse_3dl(ctx, f);
562     } else if (!av_strcasecmp(ext, "cube")) {
563         ret = parse_cube(ctx, f);
564     } else if (!av_strcasecmp(ext, "m3d")) {
565         ret = parse_m3d(ctx, f);
566     } else {
567         av_log(ctx, AV_LOG_ERROR, "Unrecognized '.%s' file type\n", ext);
568         ret = AVERROR(EINVAL);
569     }
570
571     if (!ret && !lut3d->lutsize) {
572         av_log(ctx, AV_LOG_ERROR, "3D LUT is empty\n");
573         ret = AVERROR_INVALIDDATA;
574     }
575
576 end:
577     fclose(f);
578     return ret;
579 }
580
581 static const AVFilterPad lut3d_inputs[] = {
582     {
583         .name         = "default",
584         .type         = AVMEDIA_TYPE_VIDEO,
585         .filter_frame = filter_frame,
586         .config_props = config_input,
587     },
588     { NULL }
589 };
590
591 static const AVFilterPad lut3d_outputs[] = {
592      {
593          .name = "default",
594          .type = AVMEDIA_TYPE_VIDEO,
595      },
596      { NULL }
597 };
598
599 AVFilter ff_vf_lut3d = {
600     .name          = "lut3d",
601     .description   = NULL_IF_CONFIG_SMALL("Adjust colors using a 3D LUT."),
602     .priv_size     = sizeof(LUT3DContext),
603     .init          = lut3d_init,
604     .query_formats = query_formats,
605     .inputs        = lut3d_inputs,
606     .outputs       = lut3d_outputs,
607     .priv_class    = &lut3d_class,
608     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
609 };
610 #endif
611
612 #if CONFIG_HALDCLUT_FILTER
613
614 static void update_clut(LUT3DContext *lut3d, const AVFrame *frame)
615 {
616     const uint8_t *data = frame->data[0];
617     const int linesize  = frame->linesize[0];
618     const int w = lut3d->clut_width;
619     const int step = lut3d->clut_step;
620     const uint8_t *rgba_map = lut3d->clut_rgba_map;
621     const int level = lut3d->lutsize;
622
623 #define LOAD_CLUT(nbits) do {                                           \
624     int i, j, k, x = 0, y = 0;                                          \
625                                                                         \
626     for (k = 0; k < level; k++) {                                       \
627         for (j = 0; j < level; j++) {                                   \
628             for (i = 0; i < level; i++) {                               \
629                 const uint##nbits##_t *src = (const uint##nbits##_t *)  \
630                     (data + y*linesize + x*step);                       \
631                 struct rgbvec *vec = &lut3d->lut[k][j][i];              \
632                 vec->r = src[rgba_map[0]] / (float)((1<<(nbits)) - 1);  \
633                 vec->g = src[rgba_map[1]] / (float)((1<<(nbits)) - 1);  \
634                 vec->b = src[rgba_map[2]] / (float)((1<<(nbits)) - 1);  \
635                 if (++x == w) {                                         \
636                     x = 0;                                              \
637                     y++;                                                \
638                 }                                                       \
639             }                                                           \
640         }                                                               \
641     }                                                                   \
642 } while (0)
643
644     if (!lut3d->clut_is16bit) LOAD_CLUT(8);
645     else                      LOAD_CLUT(16);
646 }
647
648
649 static int config_output(AVFilterLink *outlink)
650 {
651     AVFilterContext *ctx = outlink->src;
652     LUT3DContext *lut3d = ctx->priv;
653     int ret;
654
655     outlink->w = ctx->inputs[0]->w;
656     outlink->h = ctx->inputs[0]->h;
657     outlink->time_base = ctx->inputs[0]->time_base;
658     if ((ret = ff_dualinput_init(ctx, &lut3d->dinput)) < 0)
659         return ret;
660     return 0;
661 }
662
663 static int filter_frame_hald(AVFilterLink *inlink, AVFrame *inpicref)
664 {
665     LUT3DContext *s = inlink->dst->priv;
666     return ff_dualinput_filter_frame(&s->dinput, inlink, inpicref);
667 }
668
669 static int request_frame(AVFilterLink *outlink)
670 {
671     LUT3DContext *s = outlink->src->priv;
672     return ff_dualinput_request_frame(&s->dinput, outlink);
673 }
674
675 static int config_clut(AVFilterLink *inlink)
676 {
677     int size, level, w, h;
678     AVFilterContext *ctx = inlink->dst;
679     LUT3DContext *lut3d = ctx->priv;
680     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
681
682     lut3d->clut_is16bit = 0;
683     switch (inlink->format) {
684     case AV_PIX_FMT_RGB48:
685     case AV_PIX_FMT_BGR48:
686     case AV_PIX_FMT_RGBA64:
687     case AV_PIX_FMT_BGRA64:
688         lut3d->clut_is16bit = 1;
689     }
690
691     lut3d->clut_step = av_get_padded_bits_per_pixel(desc) >> 3;
692     ff_fill_rgba_map(lut3d->clut_rgba_map, inlink->format);
693
694     if (inlink->w > inlink->h)
695         av_log(ctx, AV_LOG_INFO, "Padding on the right (%dpx) of the "
696                "Hald CLUT will be ignored\n", inlink->w - inlink->h);
697     else if (inlink->w < inlink->h)
698         av_log(ctx, AV_LOG_INFO, "Padding at the bottom (%dpx) of the "
699                "Hald CLUT will be ignored\n", inlink->h - inlink->w);
700     lut3d->clut_width = w = h = FFMIN(inlink->w, inlink->h);
701
702     for (level = 1; level*level*level < w; level++);
703     size = level*level*level;
704     if (size != w) {
705         av_log(ctx, AV_LOG_WARNING, "The Hald CLUT width does not match the level\n");
706         return AVERROR_INVALIDDATA;
707     }
708     av_assert0(w == h && w == size);
709     level *= level;
710     if (level > MAX_LEVEL) {
711         const int max_clut_level = sqrt(MAX_LEVEL);
712         const int max_clut_size  = max_clut_level*max_clut_level*max_clut_level;
713         av_log(ctx, AV_LOG_ERROR, "Too large Hald CLUT "
714                "(maximum level is %d, or %dx%d CLUT)\n",
715                max_clut_level, max_clut_size, max_clut_size);
716         return AVERROR(EINVAL);
717     }
718     lut3d->lutsize = level;
719
720     return 0;
721 }
722
723 static AVFrame *update_apply_clut(AVFilterContext *ctx, AVFrame *main,
724                                   const AVFrame *second)
725 {
726     AVFilterLink *inlink = ctx->inputs[0];
727     update_clut(ctx->priv, second);
728     return apply_lut(inlink, main);
729 }
730
731 static av_cold int haldclut_init(AVFilterContext *ctx)
732 {
733     LUT3DContext *lut3d = ctx->priv;
734     lut3d->dinput.process = update_apply_clut;
735     return 0;
736 }
737
738 static av_cold void haldclut_uninit(AVFilterContext *ctx)
739 {
740     LUT3DContext *lut3d = ctx->priv;
741     ff_dualinput_uninit(&lut3d->dinput);
742 }
743
744 static const AVOption haldclut_options[] = {
745     { "shortest",   "force termination when the shortest input terminates", OFFSET(dinput.shortest),   AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
746     { "repeatlast", "continue applying the last clut after eos",            OFFSET(dinput.repeatlast), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, FLAGS },
747     COMMON_OPTIONS
748 };
749
750 AVFILTER_DEFINE_CLASS(haldclut);
751
752 static const AVFilterPad haldclut_inputs[] = {
753     {
754         .name         = "main",
755         .type         = AVMEDIA_TYPE_VIDEO,
756         .filter_frame = filter_frame_hald,
757         .config_props = config_input,
758     },{
759         .name         = "clut",
760         .type         = AVMEDIA_TYPE_VIDEO,
761         .filter_frame = filter_frame_hald,
762         .config_props = config_clut,
763     },
764     { NULL }
765 };
766
767 static const AVFilterPad haldclut_outputs[] = {
768     {
769         .name          = "default",
770         .type          = AVMEDIA_TYPE_VIDEO,
771         .request_frame = request_frame,
772         .config_props  = config_output,
773     },
774     { NULL }
775 };
776
777 AVFilter ff_vf_haldclut = {
778     .name          = "haldclut",
779     .description   = NULL_IF_CONFIG_SMALL("Adjust colors using a Hald CLUT."),
780     .priv_size     = sizeof(LUT3DContext),
781     .init          = haldclut_init,
782     .uninit        = haldclut_uninit,
783     .query_formats = query_formats,
784     .inputs        = haldclut_inputs,
785     .outputs       = haldclut_outputs,
786     .priv_class    = &haldclut_class,
787     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL,
788 };
789 #endif