2 * This file is part of FFmpeg.
4 * FFmpeg is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * FFmpeg is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with FFmpeg; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 * Use a palette to downsample an input video stream.
24 #include "libavutil/bprint.h"
25 #include "libavutil/opt.h"
26 #include "dualinput.h"
33 DITHERING_FLOYD_STEINBERG,
39 enum color_search_method {
40 COLOR_SEARCH_NNS_ITERATIVE,
41 COLOR_SEARCH_NNS_RECURSIVE,
42 COLOR_SEARCH_BRUTEFORCE,
50 int left_id, right_id;
54 #define CACHE_SIZE (1<<(3*NBITS))
62 struct cached_color *entries;
66 struct PaletteUseContext;
68 typedef int (*set_frame_func)(struct PaletteUseContext *s, AVFrame *out, AVFrame *in);
70 typedef struct PaletteUseContext {
72 FFDualInputContext dinput;
73 struct cache_node cache[CACHE_SIZE]; /* lookup cache */
74 struct color_node map[AVPALETTE_COUNT]; /* 3D-Tree (KD-Tree with K=3) for reverse colormap */
75 uint32_t palette[AVPALETTE_COUNT];
78 set_frame_func set_frame;
80 int ordered_dither[8*8];
84 int color_search_method;
86 uint64_t total_mean_err;
90 #define OFFSET(x) offsetof(PaletteUseContext, x)
91 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
92 static const AVOption paletteuse_options[] = {
93 { "dither", "select dithering mode", OFFSET(dither), AV_OPT_TYPE_INT, {.i64=DITHERING_SIERRA2_4A}, 0, NB_DITHERING-1, FLAGS, "dithering_mode" },
94 { "bayer", "ordered 8x8 bayer dithering (deterministic)", 0, AV_OPT_TYPE_CONST, {.i64=DITHERING_BAYER}, INT_MIN, INT_MAX, FLAGS, "dithering_mode" },
95 { "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" },
96 { "floyd_steinberg", "Floyd and Steingberg dithering (error diffusion)", 0, AV_OPT_TYPE_CONST, {.i64=DITHERING_FLOYD_STEINBERG}, INT_MIN, INT_MAX, FLAGS, "dithering_mode" },
97 { "sierra2", "Frankie Sierra dithering v2 (error diffusion)", 0, AV_OPT_TYPE_CONST, {.i64=DITHERING_SIERRA2}, INT_MIN, INT_MAX, FLAGS, "dithering_mode" },
98 { "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" },
99 { "bayer_scale", "set scale for bayer dithering", OFFSET(bayer_scale), AV_OPT_TYPE_INT, {.i64=2}, 0, 5, FLAGS },
101 /* following are the debug options, not part of the official API */
102 { "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 },
103 { "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" },
104 { "nns_iterative", "iterative search", 0, AV_OPT_TYPE_CONST, {.i64=COLOR_SEARCH_NNS_ITERATIVE}, INT_MIN, INT_MAX, FLAGS, "search" },
105 { "nns_recursive", "recursive search", 0, AV_OPT_TYPE_CONST, {.i64=COLOR_SEARCH_NNS_RECURSIVE}, INT_MIN, INT_MAX, FLAGS, "search" },
106 { "bruteforce", "brute-force into the palette", 0, AV_OPT_TYPE_CONST, {.i64=COLOR_SEARCH_BRUTEFORCE}, INT_MIN, INT_MAX, FLAGS, "search" },
107 { "mean_err", "compute and print mean error", OFFSET(calc_mean_err), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS },
108 { "debug_accuracy", "test color search accuracy", OFFSET(debug_accuracy), AV_OPT_TYPE_FLAGS, {.i64=0}, 0, 1, FLAGS },
112 AVFILTER_DEFINE_CLASS(paletteuse);
114 static int query_formats(AVFilterContext *ctx)
116 static const enum AVPixelFormat in_fmts[] = {AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE};
117 static const enum AVPixelFormat inpal_fmts[] = {AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE};
118 static const enum AVPixelFormat out_fmts[] = {AV_PIX_FMT_PAL8, AV_PIX_FMT_NONE};
119 AVFilterFormats *in = ff_make_format_list(in_fmts);
120 AVFilterFormats *inpal = ff_make_format_list(inpal_fmts);
121 AVFilterFormats *out = ff_make_format_list(out_fmts);
122 if (!in || !inpal || !out)
123 return AVERROR(ENOMEM);
124 ff_formats_ref(in, &ctx->inputs[0]->out_formats);
125 ff_formats_ref(inpal, &ctx->inputs[1]->out_formats);
126 ff_formats_ref(out, &ctx->outputs[0]->in_formats);
130 static av_always_inline int dither_color(uint32_t px, int er, int eg, int eb, int scale, int shift)
132 return av_clip_uint8((px >> 16 & 0xff) + ((er * scale) >> shift)) << 16
133 | av_clip_uint8((px >> 8 & 0xff) + ((eg * scale) >> shift)) << 8
134 | av_clip_uint8((px & 0xff) + ((eb * scale) >> shift));
137 static av_always_inline int diff(const uint8_t *c1, const uint8_t *c2)
139 // XXX: try L*a*b with CIE76 (dL*dL + da*da + db*db)
140 const int dr = c1[0] - c2[0];
141 const int dg = c1[1] - c2[1];
142 const int db = c1[2] - c2[2];
143 return dr*dr + dg*dg + db*db;
146 static av_always_inline uint8_t colormap_nearest_bruteforce(const uint32_t *palette, const uint8_t *rgb)
148 int i, pal_id = -1, min_dist = INT_MAX;
150 for (i = 0; i < AVPALETTE_COUNT; i++) {
151 const uint32_t c = palette[i];
153 if ((c & 0xff000000) == 0xff000000) { // ignore transparent entry
154 const uint8_t palrgb[] = {
155 palette[i]>>16 & 0xff,
156 palette[i]>> 8 & 0xff,
159 const int d = diff(palrgb, rgb);
169 /* Recursive form, simpler but a bit slower. Kept for reference. */
170 struct nearest_color {
175 static void colormap_nearest_node(const struct color_node *map,
177 const uint8_t *target,
178 struct nearest_color *nearest)
180 const struct color_node *kd = map + node_pos;
181 const int s = kd->split;
182 int dx, nearer_kd_id, further_kd_id;
183 const uint8_t *current = kd->val;
184 const int current_to_target = diff(target, current);
186 if (current_to_target < nearest->dist_sqd) {
187 nearest->node_pos = node_pos;
188 nearest->dist_sqd = current_to_target;
191 if (kd->left_id != -1 || kd->right_id != -1) {
192 dx = target[s] - current[s];
194 if (dx <= 0) nearer_kd_id = kd->left_id, further_kd_id = kd->right_id;
195 else nearer_kd_id = kd->right_id, further_kd_id = kd->left_id;
197 if (nearer_kd_id != -1)
198 colormap_nearest_node(map, nearer_kd_id, target, nearest);
200 if (further_kd_id != -1 && dx*dx < nearest->dist_sqd)
201 colormap_nearest_node(map, further_kd_id, target, nearest);
205 static av_always_inline uint8_t colormap_nearest_recursive(const struct color_node *node, const uint8_t *rgb)
207 struct nearest_color res = {.dist_sqd = INT_MAX, .node_pos = -1};
208 colormap_nearest_node(node, 0, rgb, &res);
209 return node[res.node_pos].palette_id;
217 static av_always_inline uint8_t colormap_nearest_iterative(const struct color_node *root, const uint8_t *target)
219 int pos = 0, best_node_id = -1, best_dist = INT_MAX, cur_color_id = 0;
220 struct stack_node nodes[16];
221 struct stack_node *node = &nodes[0];
225 const struct color_node *kd = &root[cur_color_id];
226 const uint8_t *current = kd->val;
227 const int current_to_target = diff(target, current);
229 /* Compare current color node to the target and update our best node if
230 * it's actually better. */
231 if (current_to_target < best_dist) {
232 best_node_id = cur_color_id;
233 if (!current_to_target)
234 goto end; // exact match, we can return immediately
235 best_dist = current_to_target;
238 /* Check if it's not a leaf */
239 if (kd->left_id != -1 || kd->right_id != -1) {
240 const int split = kd->split;
241 const int dx = target[split] - current[split];
242 int nearer_kd_id, further_kd_id;
244 /* Define which side is the most interesting. */
245 if (dx <= 0) nearer_kd_id = kd->left_id, further_kd_id = kd->right_id;
246 else nearer_kd_id = kd->right_id, further_kd_id = kd->left_id;
248 if (nearer_kd_id != -1) {
249 if (further_kd_id != -1) {
250 /* Here, both paths are defined, so we push a state for
251 * when we are going back. */
252 node->color_id = further_kd_id;
257 /* We can now update current color with the most probable path
258 * (no need to create a state since there is nothing to save
260 cur_color_id = nearer_kd_id;
262 } else if (dx*dx < best_dist) {
263 /* The nearest path isn't available, so there is only one path
264 * possible and it's the least probable. We enter it only if the
265 * distance from the current point to the hyper rectangle is
266 * less than our best distance. */
267 cur_color_id = further_kd_id;
272 /* Unstack as much as we can, typically as long as the least probable
273 * branch aren't actually probable. */
278 } while (node->dx2 >= best_dist);
280 /* We got a node where the least probable branch might actually contain
281 * a relevant color. */
282 cur_color_id = node->color_id;
286 return root[best_node_id].palette_id;
289 #define COLORMAP_NEAREST(search, palette, root, target) \
290 search == COLOR_SEARCH_NNS_ITERATIVE ? colormap_nearest_iterative(root, target) : \
291 search == COLOR_SEARCH_NNS_RECURSIVE ? colormap_nearest_recursive(root, target) : \
292 colormap_nearest_bruteforce(palette, target)
295 * Check if the requested color is in the cache already. If not, find it in the
296 * color tree and cache it.
297 * Note: r, g, and b are the component of c but are passed as well to avoid
298 * recomputing them (they are generally computed by the caller for other uses).
300 static av_always_inline uint8_t color_get(struct cache_node *cache, uint32_t color,
301 uint8_t r, uint8_t g, uint8_t b,
302 const struct color_node *map,
303 const uint32_t *palette,
304 const enum color_search_method search_method)
307 const uint8_t rgb[] = {r, g, b};
308 const uint8_t rhash = r & ((1<<NBITS)-1);
309 const uint8_t ghash = g & ((1<<NBITS)-1);
310 const uint8_t bhash = b & ((1<<NBITS)-1);
311 const unsigned hash = rhash<<(NBITS*2) | ghash<<NBITS | bhash;
312 struct cache_node *node = &cache[hash];
313 struct cached_color *e;
315 for (i = 0; i < node->nb_entries; i++) {
316 e = &node->entries[i];
317 if (e->color == color)
321 e = av_dynarray2_add((void**)&node->entries, &node->nb_entries,
322 sizeof(*node->entries), NULL);
324 return AVERROR(ENOMEM);
326 e->pal_entry = COLORMAP_NEAREST(search_method, palette, map, rgb);
330 static av_always_inline uint8_t get_dst_color_err(struct cache_node *cache,
331 uint32_t c, const struct color_node *map,
332 const uint32_t *palette,
333 int *er, int *eg, int *eb,
334 const enum color_search_method search_method)
336 const uint8_t r = c >> 16 & 0xff;
337 const uint8_t g = c >> 8 & 0xff;
338 const uint8_t b = c & 0xff;
339 const uint8_t dstx = color_get(cache, c, r, g, b, map, palette, search_method);
340 const uint32_t dstc = palette[dstx];
341 *er = r - (dstc >> 16 & 0xff);
342 *eg = g - (dstc >> 8 & 0xff);
343 *eb = b - (dstc & 0xff);
347 static av_always_inline int set_frame(PaletteUseContext *s, AVFrame *out, AVFrame *in,
348 enum dithering_mode dither,
349 const enum color_search_method search_method)
352 const struct color_node *map = s->map;
353 struct cache_node *cache = s->cache;
354 const uint32_t *palette = s->palette;
355 uint32_t *src = (uint32_t *)in ->data[0];
356 uint8_t *dst = out->data[0];
357 const int src_linesize = in ->linesize[0] >> 2;
358 const int dst_linesize = out->linesize[0];
360 for (y = 0; y < in->height; y++) {
361 for (x = 0; x < in->width; x++) {
364 if (dither == DITHERING_BAYER) {
365 const int d = s->ordered_dither[(y & 7)<<3 | (x & 7)];
366 const uint8_t r8 = src[x] >> 16 & 0xff;
367 const uint8_t g8 = src[x] >> 8 & 0xff;
368 const uint8_t b8 = src[x] & 0xff;
369 const uint8_t r = av_clip_uint8(r8 + d);
370 const uint8_t g = av_clip_uint8(g8 + d);
371 const uint8_t b = av_clip_uint8(b8 + d);
372 const uint32_t c = r<<16 | g<<8 | b;
373 const int color = color_get(cache, c, r, g, b, map, palette, search_method);
379 } else if (dither == DITHERING_HECKBERT) {
380 const int right = x < in->width - 1, down = y < in->height - 1;
381 const int color = get_dst_color_err(cache, src[x], map, palette, &er, &eg, &eb, search_method);
387 if (right) src[ x + 1] = dither_color(src[ x + 1], er, eg, eb, 3, 3);
388 if ( down) src[src_linesize + x ] = dither_color(src[src_linesize + x ], er, eg, eb, 3, 3);
389 if (right && down) src[src_linesize + x + 1] = dither_color(src[src_linesize + x + 1], er, eg, eb, 2, 3);
391 } else if (dither == DITHERING_FLOYD_STEINBERG) {
392 const int right = x < in->width - 1, down = y < in->height - 1, left = x > 0;
393 const int color = get_dst_color_err(cache, src[x], map, palette, &er, &eg, &eb, search_method);
399 if (right) src[ x + 1] = dither_color(src[ x + 1], er, eg, eb, 7, 4);
400 if (left && down) src[src_linesize + x - 1] = dither_color(src[src_linesize + x - 1], er, eg, eb, 3, 4);
401 if ( down) src[src_linesize + x ] = dither_color(src[src_linesize + x ], er, eg, eb, 5, 4);
402 if (right && down) src[src_linesize + x + 1] = dither_color(src[src_linesize + x + 1], er, eg, eb, 1, 4);
404 } else if (dither == DITHERING_SIERRA2) {
405 const int right = x < in->width - 1, down = y < in->height - 1, left = x > 0;
406 const int right2 = x < in->width - 2, left2 = x > 1;
407 const int color = get_dst_color_err(cache, src[x], map, palette, &er, &eg, &eb, search_method);
413 if (right) src[ x + 1] = dither_color(src[ x + 1], er, eg, eb, 4, 4);
414 if (right2) src[ x + 2] = dither_color(src[ x + 2], er, eg, eb, 3, 4);
417 if (left2) src[ src_linesize + x - 2] = dither_color(src[ src_linesize + x - 2], er, eg, eb, 1, 4);
418 if (left) src[ src_linesize + x - 1] = dither_color(src[ src_linesize + x - 1], er, eg, eb, 2, 4);
419 src[ src_linesize + x ] = dither_color(src[ src_linesize + x ], er, eg, eb, 3, 4);
420 if (right) src[ src_linesize + x + 1] = dither_color(src[ src_linesize + x + 1], er, eg, eb, 2, 4);
421 if (right2) src[ src_linesize + x + 2] = dither_color(src[ src_linesize + x + 2], er, eg, eb, 1, 4);
424 } else if (dither == DITHERING_SIERRA2_4A) {
425 const int right = x < in->width - 1, down = y < in->height - 1, left = x > 0;
426 const int color = get_dst_color_err(cache, src[x], map, palette, &er, &eg, &eb, search_method);
432 if (right) src[ x + 1] = dither_color(src[ x + 1], er, eg, eb, 2, 2);
433 if (left && down) src[src_linesize + x - 1] = dither_color(src[src_linesize + x - 1], er, eg, eb, 1, 2);
434 if ( down) src[src_linesize + x ] = dither_color(src[src_linesize + x ], er, eg, eb, 1, 2);
437 const uint8_t r = src[x] >> 16 & 0xff;
438 const uint8_t g = src[x] >> 8 & 0xff;
439 const uint8_t b = src[x] & 0xff;
440 const int color = color_get(cache, src[x] & 0xffffff, r, g, b, map, palette, search_method);
454 static void disp_node(AVBPrint *buf,
455 const struct color_node *map,
456 int parent_id, int node_id,
459 const struct color_node *node = &map[node_id];
460 const uint32_t fontcolor = node->val[0] > 0x50 &&
461 node->val[1] > 0x50 &&
462 node->val[2] > 0x50 ? 0 : 0xffffff;
463 av_bprintf(buf, "%*cnode%d ["
464 "label=\"%c%02X%c%02X%c%02X%c\" "
465 "fillcolor=\"#%02x%02x%02x\" "
466 "fontcolor=\"#%06X\"]\n",
467 depth*INDENT, ' ', node->palette_id,
468 "[ "[node->split], node->val[0],
469 "][ "[node->split], node->val[1],
470 " ]["[node->split], node->val[2],
472 node->val[0], node->val[1], node->val[2],
475 av_bprintf(buf, "%*cnode%d -> node%d\n", depth*INDENT, ' ',
476 map[parent_id].palette_id, node->palette_id);
477 if (node->left_id != -1) disp_node(buf, map, node_id, node->left_id, depth + 1);
478 if (node->right_id != -1) disp_node(buf, map, node_id, node->right_id, depth + 1);
481 // debug_kdtree=kdtree.dot -> dot -Tpng kdtree.dot > kdtree.png
482 static int disp_tree(const struct color_node *node, const char *fname)
485 FILE *f = av_fopen_utf8(fname, "w");
488 int ret = AVERROR(errno);
489 av_log(NULL, AV_LOG_ERROR, "Cannot open file '%s' for writing: %s\n",
490 fname, av_err2str(ret));
494 av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
496 av_bprintf(&buf, "digraph {\n");
497 av_bprintf(&buf, " node [style=filled fontsize=10 shape=box]\n");
498 disp_node(&buf, node, -1, 0, 0);
499 av_bprintf(&buf, "}\n");
501 fwrite(buf.str, 1, buf.len, f);
503 av_bprint_finalize(&buf, NULL);
507 static int debug_accuracy(const struct color_node *node, const uint32_t *palette,
508 const enum color_search_method search_method)
510 int r, g, b, ret = 0;
512 for (r = 0; r < 256; r++) {
513 for (g = 0; g < 256; g++) {
514 for (b = 0; b < 256; b++) {
515 const uint8_t rgb[] = {r, g, b};
516 const int r1 = COLORMAP_NEAREST(search_method, palette, node, rgb);
517 const int r2 = colormap_nearest_bruteforce(palette, rgb);
519 const uint32_t c1 = palette[r1];
520 const uint32_t c2 = palette[r2];
521 const uint8_t palrgb1[] = { c1>>16 & 0xff, c1>> 8 & 0xff, c1 & 0xff };
522 const uint8_t palrgb2[] = { c2>>16 & 0xff, c2>> 8 & 0xff, c2 & 0xff };
523 const int d1 = diff(palrgb1, rgb);
524 const int d2 = diff(palrgb2, rgb);
526 av_log(NULL, AV_LOG_ERROR,
527 "/!\\ %02X%02X%02X: %d ! %d (%06X ! %06X) / dist: %d ! %d\n",
528 r, g, b, r1, r2, c1 & 0xffffff, c2 & 0xffffff, d1, d2);
548 typedef int (*cmp_func)(const void *, const void *);
550 #define DECLARE_CMP_FUNC(name, pos) \
551 static int cmp_##name(const void *pa, const void *pb) \
553 const struct color *a = pa; \
554 const struct color *b = pb; \
555 return (a->value >> (8 * (2 - (pos))) & 0xff) \
556 - (b->value >> (8 * (2 - (pos))) & 0xff); \
559 DECLARE_CMP_FUNC(r, 0)
560 DECLARE_CMP_FUNC(g, 1)
561 DECLARE_CMP_FUNC(b, 2)
563 static const cmp_func cmp_funcs[] = {cmp_r, cmp_g, cmp_b};
565 static int get_next_color(const uint8_t *color_used, const uint32_t *palette,
566 int *component, const struct color_rect *box)
570 unsigned nb_color = 0;
571 struct color_rect ranges;
572 struct color tmp_pal[256];
574 ranges.min[0] = ranges.min[1] = ranges.min[2] = 0xff;
575 ranges.max[0] = ranges.max[1] = ranges.max[2] = 0x00;
577 for (i = 0; i < AVPALETTE_COUNT; i++) {
578 const uint32_t c = palette[i];
579 const uint8_t r = c >> 16 & 0xff;
580 const uint8_t g = c >> 8 & 0xff;
581 const uint8_t b = c & 0xff;
584 r < box->min[0] || g < box->min[1] || b < box->min[2] ||
585 r > box->max[0] || g > box->max[1] || b > box->max[2])
588 if (r < ranges.min[0]) ranges.min[0] = r;
589 if (g < ranges.min[1]) ranges.min[1] = g;
590 if (b < ranges.min[2]) ranges.min[2] = b;
592 if (r > ranges.max[0]) ranges.max[0] = r;
593 if (g > ranges.max[1]) ranges.max[1] = g;
594 if (b > ranges.max[2]) ranges.max[2] = b;
596 tmp_pal[nb_color].value = c;
597 tmp_pal[nb_color].pal_id = i;
605 /* define longest axis that will be the split component */
606 wr = ranges.max[0] - ranges.min[0];
607 wg = ranges.max[1] - ranges.min[1];
608 wb = ranges.max[2] - ranges.min[2];
609 if (wr >= wg && wr >= wb) longest = 0;
610 if (wg >= wr && wg >= wb) longest = 1;
611 if (wb >= wr && wb >= wg) longest = 2;
612 *component = longest;
614 /* sort along this axis to get median */
615 qsort(tmp_pal, nb_color, sizeof(*tmp_pal), cmp_funcs[longest]);
617 return tmp_pal[nb_color >> 1].pal_id;
620 static int colormap_insert(struct color_node *map,
623 const uint32_t *palette,
624 const struct color_rect *box)
627 int component, cur_id;
628 int node_left_id = -1, node_right_id = -1;
629 struct color_node *node;
630 struct color_rect box1, box2;
631 const int pal_id = get_next_color(color_used, palette, &component, box);
636 /* create new node with that color */
637 cur_id = (*nb_used)++;
640 node->split = component;
641 node->palette_id = pal_id;
642 node->val[0] = c>>16 & 0xff;
643 node->val[1] = c>> 8 & 0xff;
644 node->val[2] = c & 0xff;
646 color_used[pal_id] = 1;
648 /* get the two boxes this node creates */
650 box1.max[component] = node->val[component];
651 box2.min[component] = node->val[component] + 1;
653 node_left_id = colormap_insert(map, color_used, nb_used, palette, &box1);
655 if (box2.min[component] <= box2.max[component])
656 node_right_id = colormap_insert(map, color_used, nb_used, palette, &box2);
658 node->left_id = node_left_id;
659 node->right_id = node_right_id;
664 static int cmp_pal_entry(const void *a, const void *b)
666 const int c1 = *(const uint32_t *)a & 0xffffff;
667 const int c2 = *(const uint32_t *)b & 0xffffff;
671 static void load_colormap(PaletteUseContext *s)
674 uint8_t color_used[AVPALETTE_COUNT] = {0};
675 uint32_t last_color = 0;
676 struct color_rect box;
678 /* disable transparent colors and dups */
679 qsort(s->palette, AVPALETTE_COUNT, sizeof(*s->palette), cmp_pal_entry);
680 for (i = 0; i < AVPALETTE_COUNT; i++) {
681 const uint32_t c = s->palette[i];
682 if (i != 0 && c == last_color) {
687 if ((c & 0xff000000) != 0xff000000) {
688 color_used[i] = 1; // ignore transparent color(s)
693 box.min[0] = box.min[1] = box.min[2] = 0x00;
694 box.max[0] = box.max[1] = box.max[2] = 0xff;
696 colormap_insert(s->map, color_used, &nb_used, s->palette, &box);
699 disp_tree(s->map, s->dot_filename);
701 if (s->debug_accuracy) {
702 if (!debug_accuracy(s->map, s->palette, s->color_search_method))
703 av_log(NULL, AV_LOG_INFO, "Accuracy check passed\n");
707 static void debug_mean_error(PaletteUseContext *s, const AVFrame *in1,
708 const AVFrame *in2, int frame_count)
711 const uint32_t *palette = s->palette;
712 uint32_t *src1 = (uint32_t *)in1->data[0];
713 uint8_t *src2 = in2->data[0];
714 const int src1_linesize = in1->linesize[0] >> 2;
715 const int src2_linesize = in2->linesize[0];
716 const float div = in1->width * in1->height * 3;
717 unsigned mean_err = 0;
719 for (y = 0; y < in1->height; y++) {
720 for (x = 0; x < in1->width; x++) {
721 const uint32_t c1 = src1[x];
722 const uint32_t c2 = palette[src2[x]];
723 const uint8_t rgb1[] = {c1 >> 16 & 0xff, c1 >> 8 & 0xff, c1 & 0xff};
724 const uint8_t rgb2[] = {c2 >> 16 & 0xff, c2 >> 8 & 0xff, c2 & 0xff};
725 mean_err += diff(rgb1, rgb2);
727 src1 += src1_linesize;
728 src2 += src2_linesize;
731 s->total_mean_err += mean_err;
733 av_log(NULL, AV_LOG_INFO, "MEP:%.3f TotalMEP:%.3f\n",
734 mean_err / div, s->total_mean_err / (div * frame_count));
737 static AVFrame *apply_palette(AVFilterLink *inlink, AVFrame *in)
739 AVFilterContext *ctx = inlink->dst;
740 PaletteUseContext *s = ctx->priv;
741 AVFilterLink *outlink = inlink->dst->outputs[0];
743 AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
748 av_frame_copy_props(out, in);
749 if (s->set_frame(s, out, in) < 0) {
754 memcpy(out->data[1], s->palette, AVPALETTE_SIZE);
755 if (s->calc_mean_err)
756 debug_mean_error(s, in, out, inlink->frame_count);
761 static int config_output(AVFilterLink *outlink)
764 AVFilterContext *ctx = outlink->src;
765 PaletteUseContext *s = ctx->priv;
767 outlink->w = ctx->inputs[0]->w;
768 outlink->h = ctx->inputs[0]->h;
770 outlink->time_base = ctx->inputs[0]->time_base;
771 if ((ret = ff_dualinput_init(ctx, &s->dinput)) < 0)
776 static int config_input_palette(AVFilterLink *inlink)
778 AVFilterContext *ctx = inlink->dst;
780 if (inlink->w * inlink->h != AVPALETTE_COUNT) {
781 av_log(ctx, AV_LOG_ERROR,
782 "Palette input must contain exactly %d pixels. "
783 "Specified input has %dx%d=%d pixels\n",
784 AVPALETTE_COUNT, inlink->w, inlink->h,
785 inlink->w * inlink->h);
786 return AVERROR(EINVAL);
791 static void load_palette(PaletteUseContext *s, const AVFrame *palette_frame)
794 const uint32_t *p = (const uint32_t *)palette_frame->data[0];
795 const int p_linesize = palette_frame->linesize[0] >> 2;
798 for (y = 0; y < palette_frame->height; y++) {
799 for (x = 0; x < palette_frame->width; x++)
800 s->palette[i++] = p[x];
806 s->palette_loaded = 1;
809 static AVFrame *load_apply_palette(AVFilterContext *ctx, AVFrame *main,
810 const AVFrame *second)
812 AVFilterLink *inlink = ctx->inputs[0];
813 PaletteUseContext *s = ctx->priv;
814 if (!s->palette_loaded) {
815 load_palette(s, second);
817 return apply_palette(inlink, main);
820 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
822 PaletteUseContext *s = inlink->dst->priv;
823 return ff_dualinput_filter_frame(&s->dinput, inlink, in);
826 #define DEFINE_SET_FRAME(color_search, name, value) \
827 static int set_frame_##name(PaletteUseContext *s, AVFrame *out, AVFrame *in) \
829 return set_frame(s, out, in, value, color_search); \
832 #define DEFINE_SET_FRAME_COLOR_SEARCH(color_search, color_search_macro) \
833 DEFINE_SET_FRAME(color_search_macro, color_search##_##none, DITHERING_NONE) \
834 DEFINE_SET_FRAME(color_search_macro, color_search##_##bayer, DITHERING_BAYER) \
835 DEFINE_SET_FRAME(color_search_macro, color_search##_##heckbert, DITHERING_HECKBERT) \
836 DEFINE_SET_FRAME(color_search_macro, color_search##_##floyd_steinberg, DITHERING_FLOYD_STEINBERG) \
837 DEFINE_SET_FRAME(color_search_macro, color_search##_##sierra2, DITHERING_SIERRA2) \
838 DEFINE_SET_FRAME(color_search_macro, color_search##_##sierra2_4a, DITHERING_SIERRA2_4A) \
840 DEFINE_SET_FRAME_COLOR_SEARCH(nns_iterative, COLOR_SEARCH_NNS_ITERATIVE)
841 DEFINE_SET_FRAME_COLOR_SEARCH(nns_recursive, COLOR_SEARCH_NNS_RECURSIVE)
842 DEFINE_SET_FRAME_COLOR_SEARCH(bruteforce, COLOR_SEARCH_BRUTEFORCE)
844 #define DITHERING_ENTRIES(color_search) { \
845 set_frame_##color_search##_none, \
846 set_frame_##color_search##_bayer, \
847 set_frame_##color_search##_heckbert, \
848 set_frame_##color_search##_floyd_steinberg, \
849 set_frame_##color_search##_sierra2, \
850 set_frame_##color_search##_sierra2_4a, \
853 static const set_frame_func set_frame_lut[NB_COLOR_SEARCHES][NB_DITHERING] = {
854 DITHERING_ENTRIES(nns_iterative),
855 DITHERING_ENTRIES(nns_recursive),
856 DITHERING_ENTRIES(bruteforce),
859 static int dither_value(int p)
861 const int q = p ^ (p >> 3);
862 return (p & 4) >> 2 | (q & 4) >> 1 \
863 | (p & 2) << 1 | (q & 2) << 2 \
864 | (p & 1) << 4 | (q & 1) << 5;
867 static av_cold int init(AVFilterContext *ctx)
869 PaletteUseContext *s = ctx->priv;
870 s->dinput.repeatlast = 1; // only 1 frame in the palette
871 s->dinput.process = load_apply_palette;
873 s->set_frame = set_frame_lut[s->color_search_method][s->dither];
875 if (s->dither == DITHERING_BAYER) {
877 const int delta = 1 << (5 - s->bayer_scale); // to avoid too much luma
879 for (i = 0; i < FF_ARRAY_ELEMS(s->ordered_dither); i++)
880 s->ordered_dither[i] = (dither_value(i) >> s->bayer_scale) - delta;
886 static int request_frame(AVFilterLink *outlink)
888 PaletteUseContext *s = outlink->src->priv;
889 return ff_dualinput_request_frame(&s->dinput, outlink);
892 static av_cold void uninit(AVFilterContext *ctx)
895 PaletteUseContext *s = ctx->priv;
897 ff_dualinput_uninit(&s->dinput);
898 for (i = 0; i < CACHE_SIZE; i++)
899 av_freep(&s->cache[i].entries);
902 static const AVFilterPad paletteuse_inputs[] = {
905 .type = AVMEDIA_TYPE_VIDEO,
906 .filter_frame = filter_frame,
907 .needs_writable = 1, // for error diffusal dithering
910 .type = AVMEDIA_TYPE_VIDEO,
911 .config_props = config_input_palette,
912 .filter_frame = filter_frame,
917 static const AVFilterPad paletteuse_outputs[] = {
920 .type = AVMEDIA_TYPE_VIDEO,
921 .config_props = config_output,
922 .request_frame = request_frame,
927 AVFilter ff_vf_paletteuse = {
928 .name = "paletteuse",
929 .description = NULL_IF_CONFIG_SMALL("Use a palette to downsample an input video stream."),
930 .priv_size = sizeof(PaletteUseContext),
931 .query_formats = query_formats,
934 .inputs = paletteuse_inputs,
935 .outputs = paletteuse_outputs,
936 .priv_class = &paletteuse_class,