]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_paletteuse.c
Merge commit 'b31328d008985f87f0a7c83c700847cef1a4f08c'
[ffmpeg] / libavfilter / vf_paletteuse.c
1 /*
2  * Copyright (c) 2015 Stupeflix
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  * Use a palette to downsample an input video stream.
24  */
25
26 #include "libavutil/bprint.h"
27 #include "libavutil/opt.h"
28 #include "dualinput.h"
29 #include "avfilter.h"
30
31 enum dithering_mode {
32     DITHERING_NONE,
33     DITHERING_BAYER,
34     DITHERING_HECKBERT,
35     DITHERING_FLOYD_STEINBERG,
36     DITHERING_SIERRA2,
37     DITHERING_SIERRA2_4A,
38     NB_DITHERING
39 };
40
41 enum color_search_method {
42     COLOR_SEARCH_NNS_ITERATIVE,
43     COLOR_SEARCH_NNS_RECURSIVE,
44     COLOR_SEARCH_BRUTEFORCE,
45     NB_COLOR_SEARCHES
46 };
47
48 enum diff_mode {
49     DIFF_MODE_NONE,
50     DIFF_MODE_RECTANGLE,
51     NB_DIFF_MODE
52 };
53
54 struct color_node {
55     uint8_t val[3];
56     uint8_t palette_id;
57     int split;
58     int left_id, right_id;
59 };
60
61 #define NBITS 5
62 #define CACHE_SIZE (1<<(3*NBITS))
63
64 struct cached_color {
65     uint32_t color;
66     uint8_t pal_entry;
67 };
68
69 struct cache_node {
70     struct cached_color *entries;
71     int nb_entries;
72 };
73
74 struct PaletteUseContext;
75
76 typedef int (*set_frame_func)(struct PaletteUseContext *s, AVFrame *out, AVFrame *in,
77                               int x_start, int y_start, int width, int height);
78
79 typedef struct PaletteUseContext {
80     const AVClass *class;
81     FFDualInputContext dinput;
82     struct cache_node cache[CACHE_SIZE];    /* lookup cache */
83     struct color_node map[AVPALETTE_COUNT]; /* 3D-Tree (KD-Tree with K=3) for reverse colormap */
84     uint32_t palette[AVPALETTE_COUNT];
85     int palette_loaded;
86     int dither;
87     set_frame_func set_frame;
88     int bayer_scale;
89     int ordered_dither[8*8];
90     int diff_mode;
91     AVFrame *last_in;
92     AVFrame *last_out;
93
94     /* debug options */
95     char *dot_filename;
96     int color_search_method;
97     int calc_mean_err;
98     uint64_t total_mean_err;
99     int debug_accuracy;
100 } PaletteUseContext;
101
102 #define OFFSET(x) offsetof(PaletteUseContext, x)
103 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
104 static const AVOption paletteuse_options[] = {
105     { "dither", "select dithering mode", OFFSET(dither), AV_OPT_TYPE_INT, {.i64=DITHERING_SIERRA2_4A}, 0, NB_DITHERING-1, FLAGS, "dithering_mode" },
106         { "bayer",           "ordered 8x8 bayer dithering (deterministic)",                            0, AV_OPT_TYPE_CONST, {.i64=DITHERING_BAYER},           INT_MIN, INT_MAX, FLAGS, "dithering_mode" },
107         { "heckbert",        "dithering as defined by Paul Heckbert in 1982 (simple error diffusion)", 0, AV_OPT_TYPE_CONST, {.i64=DITHERING_HECKBERT},        INT_MIN, INT_MAX, FLAGS, "dithering_mode" },
108         { "floyd_steinberg", "Floyd and Steingberg dithering (error diffusion)",                       0, AV_OPT_TYPE_CONST, {.i64=DITHERING_FLOYD_STEINBERG}, INT_MIN, INT_MAX, FLAGS, "dithering_mode" },
109         { "sierra2",         "Frankie Sierra dithering v2 (error diffusion)",                          0, AV_OPT_TYPE_CONST, {.i64=DITHERING_SIERRA2},         INT_MIN, INT_MAX, FLAGS, "dithering_mode" },
110         { "sierra2_4a",      "Frankie Sierra dithering v2 \"Lite\" (error diffusion)",                 0, AV_OPT_TYPE_CONST, {.i64=DITHERING_SIERRA2_4A},      INT_MIN, INT_MAX, FLAGS, "dithering_mode" },
111     { "bayer_scale", "set scale for bayer dithering", OFFSET(bayer_scale), AV_OPT_TYPE_INT, {.i64=2}, 0, 5, FLAGS },
112     { "diff_mode",   "set frame difference mode",     OFFSET(diff_mode),   AV_OPT_TYPE_INT, {.i64=DIFF_MODE_NONE}, 0, NB_DIFF_MODE-1, FLAGS, "diff_mode" },
113         { "rectangle", "process smallest different rectangle", 0, AV_OPT_TYPE_CONST, {.i64=DIFF_MODE_RECTANGLE}, INT_MIN, INT_MAX, FLAGS, "diff_mode" },
114
115     /* following are the debug options, not part of the official API */
116     { "debug_kdtree", "save Graphviz graph of the kdtree in specified file", OFFSET(dot_filename), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS },
117     { "color_search", "set reverse colormap color search method", OFFSET(color_search_method), AV_OPT_TYPE_INT, {.i64=COLOR_SEARCH_NNS_ITERATIVE}, 0, NB_COLOR_SEARCHES-1, FLAGS, "search" },
118         { "nns_iterative", "iterative search",             0, AV_OPT_TYPE_CONST, {.i64=COLOR_SEARCH_NNS_ITERATIVE}, INT_MIN, INT_MAX, FLAGS, "search" },
119         { "nns_recursive", "recursive search",             0, AV_OPT_TYPE_CONST, {.i64=COLOR_SEARCH_NNS_RECURSIVE}, INT_MIN, INT_MAX, FLAGS, "search" },
120         { "bruteforce",    "brute-force into the palette", 0, AV_OPT_TYPE_CONST, {.i64=COLOR_SEARCH_BRUTEFORCE},    INT_MIN, INT_MAX, FLAGS, "search" },
121     { "mean_err", "compute and print mean error", OFFSET(calc_mean_err), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS },
122     { "debug_accuracy", "test color search accuracy", OFFSET(debug_accuracy), AV_OPT_TYPE_FLAGS, {.i64=0}, 0, 1, FLAGS },
123     { NULL }
124 };
125
126 AVFILTER_DEFINE_CLASS(paletteuse);
127
128 static int query_formats(AVFilterContext *ctx)
129 {
130     static const enum AVPixelFormat in_fmts[]    = {AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE};
131     static const enum AVPixelFormat inpal_fmts[] = {AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE};
132     static const enum AVPixelFormat out_fmts[]   = {AV_PIX_FMT_PAL8,  AV_PIX_FMT_NONE};
133     AVFilterFormats *in    = ff_make_format_list(in_fmts);
134     AVFilterFormats *inpal = ff_make_format_list(inpal_fmts);
135     AVFilterFormats *out   = ff_make_format_list(out_fmts);
136     if (!in || !inpal || !out) {
137         av_freep(&in);
138         av_freep(&inpal);
139         av_freep(&out);
140         return AVERROR(ENOMEM);
141     }
142     ff_formats_ref(in,    &ctx->inputs[0]->out_formats);
143     ff_formats_ref(inpal, &ctx->inputs[1]->out_formats);
144     ff_formats_ref(out,   &ctx->outputs[0]->in_formats);
145     return 0;
146 }
147
148 static av_always_inline int dither_color(uint32_t px, int er, int eg, int eb, int scale, int shift)
149 {
150     return av_clip_uint8((px >> 16 & 0xff) + ((er * scale) / (1<<shift))) << 16
151          | av_clip_uint8((px >>  8 & 0xff) + ((eg * scale) / (1<<shift))) <<  8
152          | av_clip_uint8((px       & 0xff) + ((eb * scale) / (1<<shift)));
153 }
154
155 static av_always_inline int diff(const uint8_t *c1, const uint8_t *c2)
156 {
157     // XXX: try L*a*b with CIE76 (dL*dL + da*da + db*db)
158     const int dr = c1[0] - c2[0];
159     const int dg = c1[1] - c2[1];
160     const int db = c1[2] - c2[2];
161     return dr*dr + dg*dg + db*db;
162 }
163
164 static av_always_inline uint8_t colormap_nearest_bruteforce(const uint32_t *palette, const uint8_t *rgb)
165 {
166     int i, pal_id = -1, min_dist = INT_MAX;
167
168     for (i = 0; i < AVPALETTE_COUNT; i++) {
169         const uint32_t c = palette[i];
170
171         if ((c & 0xff000000) == 0xff000000) { // ignore transparent entry
172             const uint8_t palrgb[] = {
173                 palette[i]>>16 & 0xff,
174                 palette[i]>> 8 & 0xff,
175                 palette[i]     & 0xff,
176             };
177             const int d = diff(palrgb, rgb);
178             if (d < min_dist) {
179                 pal_id = i;
180                 min_dist = d;
181             }
182         }
183     }
184     return pal_id;
185 }
186
187 /* Recursive form, simpler but a bit slower. Kept for reference. */
188 struct nearest_color {
189     int node_pos;
190     int dist_sqd;
191 };
192
193 static void colormap_nearest_node(const struct color_node *map,
194                                   const int node_pos,
195                                   const uint8_t *target,
196                                   struct nearest_color *nearest)
197 {
198     const struct color_node *kd = map + node_pos;
199     const int s = kd->split;
200     int dx, nearer_kd_id, further_kd_id;
201     const uint8_t *current = kd->val;
202     const int current_to_target = diff(target, current);
203
204     if (current_to_target < nearest->dist_sqd) {
205         nearest->node_pos = node_pos;
206         nearest->dist_sqd = current_to_target;
207     }
208
209     if (kd->left_id != -1 || kd->right_id != -1) {
210         dx = target[s] - current[s];
211
212         if (dx <= 0) nearer_kd_id = kd->left_id,  further_kd_id = kd->right_id;
213         else         nearer_kd_id = kd->right_id, further_kd_id = kd->left_id;
214
215         if (nearer_kd_id != -1)
216             colormap_nearest_node(map, nearer_kd_id, target, nearest);
217
218         if (further_kd_id != -1 && dx*dx < nearest->dist_sqd)
219             colormap_nearest_node(map, further_kd_id, target, nearest);
220     }
221 }
222
223 static av_always_inline uint8_t colormap_nearest_recursive(const struct color_node *node, const uint8_t *rgb)
224 {
225     struct nearest_color res = {.dist_sqd = INT_MAX, .node_pos = -1};
226     colormap_nearest_node(node, 0, rgb, &res);
227     return node[res.node_pos].palette_id;
228 }
229
230 struct stack_node {
231     int color_id;
232     int dx2;
233 };
234
235 static av_always_inline uint8_t colormap_nearest_iterative(const struct color_node *root, const uint8_t *target)
236 {
237     int pos = 0, best_node_id = -1, best_dist = INT_MAX, cur_color_id = 0;
238     struct stack_node nodes[16];
239     struct stack_node *node = &nodes[0];
240
241     for (;;) {
242
243         const struct color_node *kd = &root[cur_color_id];
244         const uint8_t *current = kd->val;
245         const int current_to_target = diff(target, current);
246
247         /* Compare current color node to the target and update our best node if
248          * it's actually better. */
249         if (current_to_target < best_dist) {
250             best_node_id = cur_color_id;
251             if (!current_to_target)
252                 goto end; // exact match, we can return immediately
253             best_dist = current_to_target;
254         }
255
256         /* Check if it's not a leaf */
257         if (kd->left_id != -1 || kd->right_id != -1) {
258             const int split = kd->split;
259             const int dx = target[split] - current[split];
260             int nearer_kd_id, further_kd_id;
261
262             /* Define which side is the most interesting. */
263             if (dx <= 0) nearer_kd_id = kd->left_id,  further_kd_id = kd->right_id;
264             else         nearer_kd_id = kd->right_id, further_kd_id = kd->left_id;
265
266             if (nearer_kd_id != -1) {
267                 if (further_kd_id != -1) {
268                     /* Here, both paths are defined, so we push a state for
269                      * when we are going back. */
270                     node->color_id = further_kd_id;
271                     node->dx2 = dx*dx;
272                     pos++;
273                     node++;
274                 }
275                 /* We can now update current color with the most probable path
276                  * (no need to create a state since there is nothing to save
277                  * anymore). */
278                 cur_color_id = nearer_kd_id;
279                 continue;
280             } else if (dx*dx < best_dist) {
281                 /* The nearest path isn't available, so there is only one path
282                  * possible and it's the least probable. We enter it only if the
283                  * distance from the current point to the hyper rectangle is
284                  * less than our best distance. */
285                 cur_color_id = further_kd_id;
286                 continue;
287             }
288         }
289
290         /* Unstack as much as we can, typically as long as the least probable
291          * branch aren't actually probable. */
292         do {
293             if (--pos < 0)
294                 goto end;
295             node--;
296         } while (node->dx2 >= best_dist);
297
298         /* We got a node where the least probable branch might actually contain
299          * a relevant color. */
300         cur_color_id = node->color_id;
301     }
302
303 end:
304     return root[best_node_id].palette_id;
305 }
306
307 #define COLORMAP_NEAREST(search, palette, root, target)                                    \
308     search == COLOR_SEARCH_NNS_ITERATIVE ? colormap_nearest_iterative(root, target) :      \
309     search == COLOR_SEARCH_NNS_RECURSIVE ? colormap_nearest_recursive(root, target) :      \
310                                            colormap_nearest_bruteforce(palette, target)
311
312 /**
313  * Check if the requested color is in the cache already. If not, find it in the
314  * color tree and cache it.
315  * Note: r, g, and b are the component of c but are passed as well to avoid
316  * recomputing them (they are generally computed by the caller for other uses).
317  */
318 static av_always_inline uint8_t color_get(struct cache_node *cache, uint32_t color,
319                                           uint8_t r, uint8_t g, uint8_t b,
320                                           const struct color_node *map,
321                                           const uint32_t *palette,
322                                           const enum color_search_method search_method)
323 {
324     int i;
325     const uint8_t rgb[] = {r, g, b};
326     const uint8_t rhash = r & ((1<<NBITS)-1);
327     const uint8_t ghash = g & ((1<<NBITS)-1);
328     const uint8_t bhash = b & ((1<<NBITS)-1);
329     const unsigned hash = rhash<<(NBITS*2) | ghash<<NBITS | bhash;
330     struct cache_node *node = &cache[hash];
331     struct cached_color *e;
332
333     for (i = 0; i < node->nb_entries; i++) {
334         e = &node->entries[i];
335         if (e->color == color)
336             return e->pal_entry;
337     }
338
339     e = av_dynarray2_add((void**)&node->entries, &node->nb_entries,
340                          sizeof(*node->entries), NULL);
341     if (!e)
342         return AVERROR(ENOMEM);
343     e->color = color;
344     e->pal_entry = COLORMAP_NEAREST(search_method, palette, map, rgb);
345     return e->pal_entry;
346 }
347
348 static av_always_inline uint8_t get_dst_color_err(struct cache_node *cache,
349                                                   uint32_t c, const struct color_node *map,
350                                                   const uint32_t *palette,
351                                                   int *er, int *eg, int *eb,
352                                                   const enum color_search_method search_method)
353 {
354     const uint8_t r = c >> 16 & 0xff;
355     const uint8_t g = c >>  8 & 0xff;
356     const uint8_t b = c       & 0xff;
357     const uint8_t dstx = color_get(cache, c, r, g, b, map, palette, search_method);
358     const uint32_t dstc = palette[dstx];
359     *er = r - (dstc >> 16 & 0xff);
360     *eg = g - (dstc >>  8 & 0xff);
361     *eb = b - (dstc       & 0xff);
362     return dstx;
363 }
364
365 static av_always_inline int set_frame(PaletteUseContext *s, AVFrame *out, AVFrame *in,
366                                       int x_start, int y_start, int w, int h,
367                                       enum dithering_mode dither,
368                                       const enum color_search_method search_method)
369 {
370     int x, y;
371     const struct color_node *map = s->map;
372     struct cache_node *cache = s->cache;
373     const uint32_t *palette = s->palette;
374     const int src_linesize = in ->linesize[0] >> 2;
375     const int dst_linesize = out->linesize[0];
376     uint32_t *src = ((uint32_t *)in ->data[0]) + y_start*src_linesize;
377     uint8_t  *dst =              out->data[0]  + y_start*dst_linesize;
378
379     w += x_start;
380     h += y_start;
381
382     for (y = y_start; y < h; y++) {
383         for (x = x_start; x < w; x++) {
384             int er, eg, eb;
385
386             if (dither == DITHERING_BAYER) {
387                 const int d = s->ordered_dither[(y & 7)<<3 | (x & 7)];
388                 const uint8_t r8 = src[x] >> 16 & 0xff;
389                 const uint8_t g8 = src[x] >>  8 & 0xff;
390                 const uint8_t b8 = src[x]       & 0xff;
391                 const uint8_t r = av_clip_uint8(r8 + d);
392                 const uint8_t g = av_clip_uint8(g8 + d);
393                 const uint8_t b = av_clip_uint8(b8 + d);
394                 const uint32_t c = r<<16 | g<<8 | b;
395                 const int color = color_get(cache, c, r, g, b, map, palette, search_method);
396
397                 if (color < 0)
398                     return color;
399                 dst[x] = color;
400
401             } else if (dither == DITHERING_HECKBERT) {
402                 const int right = x < w - 1, down = y < h - 1;
403                 const int color = get_dst_color_err(cache, src[x], map, palette, &er, &eg, &eb, search_method);
404
405                 if (color < 0)
406                     return color;
407                 dst[x] = color;
408
409                 if (right)         src[               x + 1] = dither_color(src[               x + 1], er, eg, eb, 3, 3);
410                 if (         down) src[src_linesize + x    ] = dither_color(src[src_linesize + x    ], er, eg, eb, 3, 3);
411                 if (right && down) src[src_linesize + x + 1] = dither_color(src[src_linesize + x + 1], er, eg, eb, 2, 3);
412
413             } else if (dither == DITHERING_FLOYD_STEINBERG) {
414                 const int right = x < w - 1, down = y < h - 1, left = x > x_start;
415                 const int color = get_dst_color_err(cache, src[x], map, palette, &er, &eg, &eb, search_method);
416
417                 if (color < 0)
418                     return color;
419                 dst[x] = color;
420
421                 if (right)         src[               x + 1] = dither_color(src[               x + 1], er, eg, eb, 7, 4);
422                 if (left  && down) src[src_linesize + x - 1] = dither_color(src[src_linesize + x - 1], er, eg, eb, 3, 4);
423                 if (         down) src[src_linesize + x    ] = dither_color(src[src_linesize + x    ], er, eg, eb, 5, 4);
424                 if (right && down) src[src_linesize + x + 1] = dither_color(src[src_linesize + x + 1], er, eg, eb, 1, 4);
425
426             } else if (dither == DITHERING_SIERRA2) {
427                 const int right  = x < w - 1, down  = y < h - 1, left  = x > x_start;
428                 const int right2 = x < w - 2,                    left2 = x > x_start + 1;
429                 const int color = get_dst_color_err(cache, src[x], map, palette, &er, &eg, &eb, search_method);
430
431                 if (color < 0)
432                     return color;
433                 dst[x] = color;
434
435                 if (right)          src[                 x + 1] = dither_color(src[                 x + 1], er, eg, eb, 4, 4);
436                 if (right2)         src[                 x + 2] = dither_color(src[                 x + 2], er, eg, eb, 3, 4);
437
438                 if (down) {
439                     if (left2)      src[  src_linesize + x - 2] = dither_color(src[  src_linesize + x - 2], er, eg, eb, 1, 4);
440                     if (left)       src[  src_linesize + x - 1] = dither_color(src[  src_linesize + x - 1], er, eg, eb, 2, 4);
441                                     src[  src_linesize + x    ] = dither_color(src[  src_linesize + x    ], er, eg, eb, 3, 4);
442                     if (right)      src[  src_linesize + x + 1] = dither_color(src[  src_linesize + x + 1], er, eg, eb, 2, 4);
443                     if (right2)     src[  src_linesize + x + 2] = dither_color(src[  src_linesize + x + 2], er, eg, eb, 1, 4);
444                 }
445
446             } else if (dither == DITHERING_SIERRA2_4A) {
447                 const int right = x < w - 1, down = y < h - 1, left = x > x_start;
448                 const int color = get_dst_color_err(cache, src[x], map, palette, &er, &eg, &eb, search_method);
449
450                 if (color < 0)
451                     return color;
452                 dst[x] = color;
453
454                 if (right)         src[               x + 1] = dither_color(src[               x + 1], er, eg, eb, 2, 2);
455                 if (left  && down) src[src_linesize + x - 1] = dither_color(src[src_linesize + x - 1], er, eg, eb, 1, 2);
456                 if (         down) src[src_linesize + x    ] = dither_color(src[src_linesize + x    ], er, eg, eb, 1, 2);
457
458             } else {
459                 const uint8_t r = src[x] >> 16 & 0xff;
460                 const uint8_t g = src[x] >>  8 & 0xff;
461                 const uint8_t b = src[x]       & 0xff;
462                 const int color = color_get(cache, src[x] & 0xffffff, r, g, b, map, palette, search_method);
463
464                 if (color < 0)
465                     return color;
466                 dst[x] = color;
467             }
468         }
469         src += src_linesize;
470         dst += dst_linesize;
471     }
472     return 0;
473 }
474
475 #define INDENT 4
476 static void disp_node(AVBPrint *buf,
477                       const struct color_node *map,
478                       int parent_id, int node_id,
479                       int depth)
480 {
481     const struct color_node *node = &map[node_id];
482     const uint32_t fontcolor = node->val[0] > 0x50 &&
483                                node->val[1] > 0x50 &&
484                                node->val[2] > 0x50 ? 0 : 0xffffff;
485     av_bprintf(buf, "%*cnode%d ["
486                "label=\"%c%02X%c%02X%c%02X%c\" "
487                "fillcolor=\"#%02x%02x%02x\" "
488                "fontcolor=\"#%06X\"]\n",
489                depth*INDENT, ' ', node->palette_id,
490                "[  "[node->split], node->val[0],
491                "][ "[node->split], node->val[1],
492                " ]["[node->split], node->val[2],
493                "  ]"[node->split],
494                node->val[0], node->val[1], node->val[2],
495                fontcolor);
496     if (parent_id != -1)
497         av_bprintf(buf, "%*cnode%d -> node%d\n", depth*INDENT, ' ',
498                    map[parent_id].palette_id, node->palette_id);
499     if (node->left_id  != -1) disp_node(buf, map, node_id, node->left_id,  depth + 1);
500     if (node->right_id != -1) disp_node(buf, map, node_id, node->right_id, depth + 1);
501 }
502
503 // debug_kdtree=kdtree.dot -> dot -Tpng kdtree.dot > kdtree.png
504 static int disp_tree(const struct color_node *node, const char *fname)
505 {
506     AVBPrint buf;
507     FILE *f = av_fopen_utf8(fname, "w");
508
509     if (!f) {
510         int ret = AVERROR(errno);
511         av_log(NULL, AV_LOG_ERROR, "Cannot open file '%s' for writing: %s\n",
512                fname, av_err2str(ret));
513         return ret;
514     }
515
516     av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
517
518     av_bprintf(&buf, "digraph {\n");
519     av_bprintf(&buf, "    node [style=filled fontsize=10 shape=box]\n");
520     disp_node(&buf, node, -1, 0, 0);
521     av_bprintf(&buf, "}\n");
522
523     fwrite(buf.str, 1, buf.len, f);
524     fclose(f);
525     av_bprint_finalize(&buf, NULL);
526     return 0;
527 }
528
529 static int debug_accuracy(const struct color_node *node, const uint32_t *palette,
530                           const enum color_search_method search_method)
531 {
532     int r, g, b, ret = 0;
533
534     for (r = 0; r < 256; r++) {
535         for (g = 0; g < 256; g++) {
536             for (b = 0; b < 256; b++) {
537                 const uint8_t rgb[] = {r, g, b};
538                 const int r1 = COLORMAP_NEAREST(search_method, palette, node, rgb);
539                 const int r2 = colormap_nearest_bruteforce(palette, rgb);
540                 if (r1 != r2) {
541                     const uint32_t c1 = palette[r1];
542                     const uint32_t c2 = palette[r2];
543                     const uint8_t palrgb1[] = { c1>>16 & 0xff, c1>> 8 & 0xff, c1 & 0xff };
544                     const uint8_t palrgb2[] = { c2>>16 & 0xff, c2>> 8 & 0xff, c2 & 0xff };
545                     const int d1 = diff(palrgb1, rgb);
546                     const int d2 = diff(palrgb2, rgb);
547                     if (d1 != d2) {
548                         av_log(NULL, AV_LOG_ERROR,
549                                "/!\\ %02X%02X%02X: %d ! %d (%06X ! %06X) / dist: %d ! %d\n",
550                                r, g, b, r1, r2, c1 & 0xffffff, c2 & 0xffffff, d1, d2);
551                         ret = 1;
552                     }
553                 }
554             }
555         }
556     }
557     return ret;
558 }
559
560 struct color {
561     uint32_t value;
562     uint8_t pal_id;
563 };
564
565 struct color_rect {
566     uint8_t min[3];
567     uint8_t max[3];
568 };
569
570 typedef int (*cmp_func)(const void *, const void *);
571
572 #define DECLARE_CMP_FUNC(name, pos)                     \
573 static int cmp_##name(const void *pa, const void *pb)   \
574 {                                                       \
575     const struct color *a = pa;                         \
576     const struct color *b = pb;                         \
577     return   (a->value >> (8 * (2 - (pos))) & 0xff)     \
578            - (b->value >> (8 * (2 - (pos))) & 0xff);    \
579 }
580
581 DECLARE_CMP_FUNC(r, 0)
582 DECLARE_CMP_FUNC(g, 1)
583 DECLARE_CMP_FUNC(b, 2)
584
585 static const cmp_func cmp_funcs[] = {cmp_r, cmp_g, cmp_b};
586
587 static int get_next_color(const uint8_t *color_used, const uint32_t *palette,
588                           int *component, const struct color_rect *box)
589 {
590     int wr, wg, wb;
591     int i, longest = 0;
592     unsigned nb_color = 0;
593     struct color_rect ranges;
594     struct color tmp_pal[256];
595
596     ranges.min[0] = ranges.min[1] = ranges.min[2] = 0xff;
597     ranges.max[0] = ranges.max[1] = ranges.max[2] = 0x00;
598
599     for (i = 0; i < AVPALETTE_COUNT; i++) {
600         const uint32_t c = palette[i];
601         const uint8_t r = c >> 16 & 0xff;
602         const uint8_t g = c >>  8 & 0xff;
603         const uint8_t b = c       & 0xff;
604
605         if (color_used[i] ||
606             r < box->min[0] || g < box->min[1] || b < box->min[2] ||
607             r > box->max[0] || g > box->max[1] || b > box->max[2])
608             continue;
609
610         if (r < ranges.min[0]) ranges.min[0] = r;
611         if (g < ranges.min[1]) ranges.min[1] = g;
612         if (b < ranges.min[2]) ranges.min[2] = b;
613
614         if (r > ranges.max[0]) ranges.max[0] = r;
615         if (g > ranges.max[1]) ranges.max[1] = g;
616         if (b > ranges.max[2]) ranges.max[2] = b;
617
618         tmp_pal[nb_color].value  = c;
619         tmp_pal[nb_color].pal_id = i;
620
621         nb_color++;
622     }
623
624     if (!nb_color)
625         return -1;
626
627     /* define longest axis that will be the split component */
628     wr = ranges.max[0] - ranges.min[0];
629     wg = ranges.max[1] - ranges.min[1];
630     wb = ranges.max[2] - ranges.min[2];
631     if (wr >= wg && wr >= wb) longest = 0;
632     if (wg >= wr && wg >= wb) longest = 1;
633     if (wb >= wr && wb >= wg) longest = 2;
634     *component = longest;
635
636     /* sort along this axis to get median */
637     qsort(tmp_pal, nb_color, sizeof(*tmp_pal), cmp_funcs[longest]);
638
639     return tmp_pal[nb_color >> 1].pal_id;
640 }
641
642 static int colormap_insert(struct color_node *map,
643                            uint8_t *color_used,
644                            int *nb_used,
645                            const uint32_t *palette,
646                            const struct color_rect *box)
647 {
648     uint32_t c;
649     int component, cur_id;
650     int node_left_id = -1, node_right_id = -1;
651     struct color_node *node;
652     struct color_rect box1, box2;
653     const int pal_id = get_next_color(color_used, palette, &component, box);
654
655     if (pal_id < 0)
656         return -1;
657
658     /* create new node with that color */
659     cur_id = (*nb_used)++;
660     c = palette[pal_id];
661     node = &map[cur_id];
662     node->split = component;
663     node->palette_id = pal_id;
664     node->val[0] = c>>16 & 0xff;
665     node->val[1] = c>> 8 & 0xff;
666     node->val[2] = c     & 0xff;
667
668     color_used[pal_id] = 1;
669
670     /* get the two boxes this node creates */
671     box1 = box2 = *box;
672     box1.max[component] = node->val[component];
673     box2.min[component] = node->val[component] + 1;
674
675     node_left_id = colormap_insert(map, color_used, nb_used, palette, &box1);
676
677     if (box2.min[component] <= box2.max[component])
678         node_right_id = colormap_insert(map, color_used, nb_used, palette, &box2);
679
680     node->left_id  = node_left_id;
681     node->right_id = node_right_id;
682
683     return cur_id;
684 }
685
686 static int cmp_pal_entry(const void *a, const void *b)
687 {
688     const int c1 = *(const uint32_t *)a & 0xffffff;
689     const int c2 = *(const uint32_t *)b & 0xffffff;
690     return c1 - c2;
691 }
692
693 static void load_colormap(PaletteUseContext *s)
694 {
695     int i, nb_used = 0;
696     uint8_t color_used[AVPALETTE_COUNT] = {0};
697     uint32_t last_color = 0;
698     struct color_rect box;
699
700     /* disable transparent colors and dups */
701     qsort(s->palette, AVPALETTE_COUNT, sizeof(*s->palette), cmp_pal_entry);
702     for (i = 0; i < AVPALETTE_COUNT; i++) {
703         const uint32_t c = s->palette[i];
704         if (i != 0 && c == last_color) {
705             color_used[i] = 1;
706             continue;
707         }
708         last_color = c;
709         if ((c & 0xff000000) != 0xff000000) {
710             color_used[i] = 1; // ignore transparent color(s)
711             continue;
712         }
713     }
714
715     box.min[0] = box.min[1] = box.min[2] = 0x00;
716     box.max[0] = box.max[1] = box.max[2] = 0xff;
717
718     colormap_insert(s->map, color_used, &nb_used, s->palette, &box);
719
720     if (s->dot_filename)
721         disp_tree(s->map, s->dot_filename);
722
723     if (s->debug_accuracy) {
724         if (!debug_accuracy(s->map, s->palette, s->color_search_method))
725             av_log(NULL, AV_LOG_INFO, "Accuracy check passed\n");
726     }
727 }
728
729 static void debug_mean_error(PaletteUseContext *s, const AVFrame *in1,
730                              const AVFrame *in2, int frame_count)
731 {
732     int x, y;
733     const uint32_t *palette = s->palette;
734     uint32_t *src1 = (uint32_t *)in1->data[0];
735     uint8_t  *src2 =             in2->data[0];
736     const int src1_linesize = in1->linesize[0] >> 2;
737     const int src2_linesize = in2->linesize[0];
738     const float div = in1->width * in1->height * 3;
739     unsigned mean_err = 0;
740
741     for (y = 0; y < in1->height; y++) {
742         for (x = 0; x < in1->width; x++) {
743             const uint32_t c1 = src1[x];
744             const uint32_t c2 = palette[src2[x]];
745             const uint8_t rgb1[] = {c1 >> 16 & 0xff, c1 >> 8 & 0xff, c1 & 0xff};
746             const uint8_t rgb2[] = {c2 >> 16 & 0xff, c2 >> 8 & 0xff, c2 & 0xff};
747             mean_err += diff(rgb1, rgb2);
748         }
749         src1 += src1_linesize;
750         src2 += src2_linesize;
751     }
752
753     s->total_mean_err += mean_err;
754
755     av_log(NULL, AV_LOG_INFO, "MEP:%.3f TotalMEP:%.3f\n",
756            mean_err / div, s->total_mean_err / (div * frame_count));
757 }
758
759 static void set_processing_window(enum diff_mode diff_mode,
760                                   const AVFrame *prv_src, const AVFrame *cur_src,
761                                   const AVFrame *prv_dst,       AVFrame *cur_dst,
762                                   int *xp, int *yp, int *wp, int *hp)
763 {
764     int x_start = 0, y_start = 0;
765     int width  = cur_src->width;
766     int height = cur_src->height;
767
768     if (prv_src && diff_mode == DIFF_MODE_RECTANGLE) {
769         int y;
770         int x_end = cur_src->width  - 1,
771             y_end = cur_src->height - 1;
772         const uint32_t *prv_srcp = (const uint32_t *)prv_src->data[0];
773         const uint32_t *cur_srcp = (const uint32_t *)cur_src->data[0];
774         const uint8_t  *prv_dstp = prv_dst->data[0];
775         uint8_t        *cur_dstp = cur_dst->data[0];
776
777         const int prv_src_linesize = prv_src->linesize[0] >> 2;
778         const int cur_src_linesize = cur_src->linesize[0] >> 2;
779         const int prv_dst_linesize = prv_dst->linesize[0];
780         const int cur_dst_linesize = cur_dst->linesize[0];
781
782         /* skip common lines */
783         while (y_start < y_end && !memcmp(prv_srcp + y_start*prv_src_linesize,
784                                           cur_srcp + y_start*cur_src_linesize,
785                                           cur_src->width * 4)) {
786             memcpy(cur_dstp + y_start*cur_dst_linesize,
787                    prv_dstp + y_start*prv_dst_linesize,
788                    cur_dst->width);
789             y_start++;
790         }
791         while (y_end > y_start && !memcmp(prv_srcp + y_end*prv_src_linesize,
792                                           cur_srcp + y_end*cur_src_linesize,
793                                           cur_src->width * 4)) {
794             memcpy(cur_dstp + y_end*cur_dst_linesize,
795                    prv_dstp + y_end*prv_dst_linesize,
796                    cur_dst->width);
797             y_end--;
798         }
799
800         height = y_end + 1 - y_start;
801
802         /* skip common columns */
803         while (x_start < x_end) {
804             int same_column = 1;
805             for (y = y_start; y <= y_end; y++) {
806                 if (prv_srcp[y*prv_src_linesize + x_start] != cur_srcp[y*cur_src_linesize + x_start]) {
807                     same_column = 0;
808                     break;
809                 }
810             }
811             if (!same_column)
812                 break;
813             x_start++;
814         }
815         while (x_end > x_start) {
816             int same_column = 1;
817             for (y = y_start; y <= y_end; y++) {
818                 if (prv_srcp[y*prv_src_linesize + x_end] != cur_srcp[y*cur_src_linesize + x_end]) {
819                     same_column = 0;
820                     break;
821                 }
822             }
823             if (!same_column)
824                 break;
825             x_end--;
826         }
827         width = x_end + 1 - x_start;
828
829         if (x_start) {
830             for (y = y_start; y <= y_end; y++)
831                 memcpy(cur_dstp + y*cur_dst_linesize,
832                        prv_dstp + y*prv_dst_linesize, x_start);
833         }
834         if (x_end != cur_src->width - 1) {
835             const int copy_len = cur_src->width - 1 - x_end;
836             for (y = y_start; y <= y_end; y++)
837                 memcpy(cur_dstp + y*cur_dst_linesize + x_end + 1,
838                        prv_dstp + y*prv_dst_linesize + x_end + 1,
839                        copy_len);
840         }
841     }
842     *xp = x_start;
843     *yp = y_start;
844     *wp = width;
845     *hp = height;
846 }
847
848 static AVFrame *apply_palette(AVFilterLink *inlink, AVFrame *in)
849 {
850     int x, y, w, h;
851     AVFilterContext *ctx = inlink->dst;
852     PaletteUseContext *s = ctx->priv;
853     AVFilterLink *outlink = inlink->dst->outputs[0];
854
855     AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
856     if (!out) {
857         av_frame_free(&in);
858         return NULL;
859     }
860     av_frame_copy_props(out, in);
861
862     set_processing_window(s->diff_mode, s->last_in, in,
863                           s->last_out, out, &x, &y, &w, &h);
864     av_frame_free(&s->last_in);
865     av_frame_free(&s->last_out);
866     s->last_in  = av_frame_clone(in);
867     s->last_out = av_frame_clone(out);
868     if (!s->last_in || !s->last_out ||
869         av_frame_make_writable(s->last_in) < 0) {
870         av_frame_free(&in);
871         av_frame_free(&out);
872         return NULL;
873     }
874
875     av_dlog(ctx, "%dx%d rect: (%d;%d) -> (%d,%d) [area:%dx%d]\n",
876             w, h, x, y, x+w, y+h, in->width, in->height);
877
878     if (s->set_frame(s, out, in, x, y, w, h) < 0) {
879         av_frame_free(&out);
880         return NULL;
881     }
882     memcpy(out->data[1], s->palette, AVPALETTE_SIZE);
883     if (s->calc_mean_err)
884         debug_mean_error(s, in, out, inlink->frame_count);
885     av_frame_free(&in);
886     return out;
887 }
888
889 static int config_output(AVFilterLink *outlink)
890 {
891     int ret;
892     AVFilterContext *ctx = outlink->src;
893     PaletteUseContext *s = ctx->priv;
894
895     outlink->w = ctx->inputs[0]->w;
896     outlink->h = ctx->inputs[0]->h;
897
898     outlink->time_base = ctx->inputs[0]->time_base;
899     if ((ret = ff_dualinput_init(ctx, &s->dinput)) < 0)
900         return ret;
901     return 0;
902 }
903
904 static int config_input_palette(AVFilterLink *inlink)
905 {
906     AVFilterContext *ctx = inlink->dst;
907
908     if (inlink->w * inlink->h != AVPALETTE_COUNT) {
909         av_log(ctx, AV_LOG_ERROR,
910                "Palette input must contain exactly %d pixels. "
911                "Specified input has %dx%d=%d pixels\n",
912                AVPALETTE_COUNT, inlink->w, inlink->h,
913                inlink->w * inlink->h);
914         return AVERROR(EINVAL);
915     }
916     return 0;
917 }
918
919 static void load_palette(PaletteUseContext *s, const AVFrame *palette_frame)
920 {
921     int i, x, y;
922     const uint32_t *p = (const uint32_t *)palette_frame->data[0];
923     const int p_linesize = palette_frame->linesize[0] >> 2;
924
925     i = 0;
926     for (y = 0; y < palette_frame->height; y++) {
927         for (x = 0; x < palette_frame->width; x++)
928             s->palette[i++] = p[x];
929         p += p_linesize;
930     }
931
932     load_colormap(s);
933
934     s->palette_loaded = 1;
935 }
936
937 static AVFrame *load_apply_palette(AVFilterContext *ctx, AVFrame *main,
938                                    const AVFrame *second)
939 {
940     AVFilterLink *inlink = ctx->inputs[0];
941     PaletteUseContext *s = ctx->priv;
942     if (!s->palette_loaded) {
943         load_palette(s, second);
944     }
945     return apply_palette(inlink, main);
946 }
947
948 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
949 {
950     PaletteUseContext *s = inlink->dst->priv;
951     return ff_dualinput_filter_frame(&s->dinput, inlink, in);
952 }
953
954 #define DEFINE_SET_FRAME(color_search, name, value)                             \
955 static int set_frame_##name(PaletteUseContext *s, AVFrame *out, AVFrame *in,    \
956                             int x_start, int y_start, int w, int h)             \
957 {                                                                               \
958     return set_frame(s, out, in, x_start, y_start, w, h, value, color_search);  \
959 }
960
961 #define DEFINE_SET_FRAME_COLOR_SEARCH(color_search, color_search_macro)                                 \
962     DEFINE_SET_FRAME(color_search_macro, color_search##_##none,            DITHERING_NONE)              \
963     DEFINE_SET_FRAME(color_search_macro, color_search##_##bayer,           DITHERING_BAYER)             \
964     DEFINE_SET_FRAME(color_search_macro, color_search##_##heckbert,        DITHERING_HECKBERT)          \
965     DEFINE_SET_FRAME(color_search_macro, color_search##_##floyd_steinberg, DITHERING_FLOYD_STEINBERG)   \
966     DEFINE_SET_FRAME(color_search_macro, color_search##_##sierra2,         DITHERING_SIERRA2)           \
967     DEFINE_SET_FRAME(color_search_macro, color_search##_##sierra2_4a,      DITHERING_SIERRA2_4A)        \
968
969 DEFINE_SET_FRAME_COLOR_SEARCH(nns_iterative, COLOR_SEARCH_NNS_ITERATIVE)
970 DEFINE_SET_FRAME_COLOR_SEARCH(nns_recursive, COLOR_SEARCH_NNS_RECURSIVE)
971 DEFINE_SET_FRAME_COLOR_SEARCH(bruteforce,    COLOR_SEARCH_BRUTEFORCE)
972
973 #define DITHERING_ENTRIES(color_search) {       \
974     set_frame_##color_search##_none,            \
975     set_frame_##color_search##_bayer,           \
976     set_frame_##color_search##_heckbert,        \
977     set_frame_##color_search##_floyd_steinberg, \
978     set_frame_##color_search##_sierra2,         \
979     set_frame_##color_search##_sierra2_4a,      \
980 }
981
982 static const set_frame_func set_frame_lut[NB_COLOR_SEARCHES][NB_DITHERING] = {
983     DITHERING_ENTRIES(nns_iterative),
984     DITHERING_ENTRIES(nns_recursive),
985     DITHERING_ENTRIES(bruteforce),
986 };
987
988 static int dither_value(int p)
989 {
990     const int q = p ^ (p >> 3);
991     return   (p & 4) >> 2 | (q & 4) >> 1 \
992            | (p & 2) << 1 | (q & 2) << 2 \
993            | (p & 1) << 4 | (q & 1) << 5;
994 }
995
996 static av_cold int init(AVFilterContext *ctx)
997 {
998     PaletteUseContext *s = ctx->priv;
999     s->dinput.repeatlast = 1; // only 1 frame in the palette
1000     s->dinput.process    = load_apply_palette;
1001
1002     s->set_frame = set_frame_lut[s->color_search_method][s->dither];
1003
1004     if (s->dither == DITHERING_BAYER) {
1005         int i;
1006         const int delta = 1 << (5 - s->bayer_scale); // to avoid too much luma
1007
1008         for (i = 0; i < FF_ARRAY_ELEMS(s->ordered_dither); i++)
1009             s->ordered_dither[i] = (dither_value(i) >> s->bayer_scale) - delta;
1010     }
1011
1012     return 0;
1013 }
1014
1015 static int request_frame(AVFilterLink *outlink)
1016 {
1017     PaletteUseContext *s = outlink->src->priv;
1018     return ff_dualinput_request_frame(&s->dinput, outlink);
1019 }
1020
1021 static av_cold void uninit(AVFilterContext *ctx)
1022 {
1023     int i;
1024     PaletteUseContext *s = ctx->priv;
1025
1026     ff_dualinput_uninit(&s->dinput);
1027     for (i = 0; i < CACHE_SIZE; i++)
1028         av_freep(&s->cache[i].entries);
1029     av_frame_free(&s->last_in);
1030     av_frame_free(&s->last_out);
1031 }
1032
1033 static const AVFilterPad paletteuse_inputs[] = {
1034     {
1035         .name           = "default",
1036         .type           = AVMEDIA_TYPE_VIDEO,
1037         .filter_frame   = filter_frame,
1038         .needs_writable = 1, // for error diffusal dithering
1039     },{
1040         .name           = "palette",
1041         .type           = AVMEDIA_TYPE_VIDEO,
1042         .config_props   = config_input_palette,
1043         .filter_frame   = filter_frame,
1044     },
1045     { NULL }
1046 };
1047
1048 static const AVFilterPad paletteuse_outputs[] = {
1049     {
1050         .name          = "default",
1051         .type          = AVMEDIA_TYPE_VIDEO,
1052         .config_props  = config_output,
1053         .request_frame = request_frame,
1054     },
1055     { NULL }
1056 };
1057
1058 AVFilter ff_vf_paletteuse = {
1059     .name          = "paletteuse",
1060     .description   = NULL_IF_CONFIG_SMALL("Use a palette to downsample an input video stream."),
1061     .priv_size     = sizeof(PaletteUseContext),
1062     .query_formats = query_formats,
1063     .init          = init,
1064     .uninit        = uninit,
1065     .inputs        = paletteuse_inputs,
1066     .outputs       = paletteuse_outputs,
1067     .priv_class    = &paletteuse_class,
1068 };