You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

938 lines
35KB

  1. /*
  2. * This file is part of FFmpeg.
  3. *
  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.
  8. *
  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.
  13. *
  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
  17. */
  18. /**
  19. * @file
  20. * Use a palette to downsample an input video stream.
  21. */
  22. #include "libavutil/bprint.h"
  23. #include "libavutil/opt.h"
  24. #include "dualinput.h"
  25. #include "avfilter.h"
  26. enum dithering_mode {
  27. DITHERING_NONE,
  28. DITHERING_BAYER,
  29. DITHERING_HECKBERT,
  30. DITHERING_FLOYD_STEINBERG,
  31. DITHERING_SIERRA2,
  32. DITHERING_SIERRA2_4A,
  33. NB_DITHERING
  34. };
  35. enum color_search_method {
  36. COLOR_SEARCH_NNS_ITERATIVE,
  37. COLOR_SEARCH_NNS_RECURSIVE,
  38. COLOR_SEARCH_BRUTEFORCE,
  39. NB_COLOR_SEARCHES
  40. };
  41. struct color_node {
  42. uint8_t val[3];
  43. uint8_t palette_id;
  44. int split;
  45. int left_id, right_id;
  46. };
  47. #define NBITS 5
  48. #define CACHE_SIZE (1<<(3*NBITS))
  49. struct cached_color {
  50. uint32_t color;
  51. uint8_t pal_entry;
  52. };
  53. struct cache_node {
  54. struct cached_color *entries;
  55. int nb_entries;
  56. };
  57. struct PaletteUseContext;
  58. typedef int (*set_frame_func)(struct PaletteUseContext *s, AVFrame *out, AVFrame *in);
  59. typedef struct PaletteUseContext {
  60. const AVClass *class;
  61. FFDualInputContext dinput;
  62. struct cache_node cache[CACHE_SIZE]; /* lookup cache */
  63. struct color_node map[AVPALETTE_COUNT]; /* 3D-Tree (KD-Tree with K=3) for reverse colormap */
  64. uint32_t palette[AVPALETTE_COUNT];
  65. int palette_loaded;
  66. int dither;
  67. set_frame_func set_frame;
  68. int bayer_scale;
  69. int ordered_dither[8*8];
  70. /* debug options */
  71. char *dot_filename;
  72. int color_search_method;
  73. int calc_mean_err;
  74. uint64_t total_mean_err;
  75. int debug_accuracy;
  76. } PaletteUseContext;
  77. #define OFFSET(x) offsetof(PaletteUseContext, x)
  78. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  79. static const AVOption paletteuse_options[] = {
  80. { "dither", "select dithering mode", OFFSET(dither), AV_OPT_TYPE_INT, {.i64=DITHERING_SIERRA2_4A}, 0, NB_DITHERING-1, FLAGS, "dithering_mode" },
  81. { "bayer", "ordered 8x8 bayer dithering (deterministic)", 0, AV_OPT_TYPE_CONST, {.i64=DITHERING_BAYER}, INT_MIN, INT_MAX, FLAGS, "dithering_mode" },
  82. { "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" },
  83. { "floyd_steinberg", "Floyd and Steingberg dithering (error diffusion)", 0, AV_OPT_TYPE_CONST, {.i64=DITHERING_FLOYD_STEINBERG}, INT_MIN, INT_MAX, FLAGS, "dithering_mode" },
  84. { "sierra2", "Frankie Sierra dithering v2 (error diffusion)", 0, AV_OPT_TYPE_CONST, {.i64=DITHERING_SIERRA2}, INT_MIN, INT_MAX, FLAGS, "dithering_mode" },
  85. { "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" },
  86. { "bayer_scale", "set scale for bayer dithering", OFFSET(bayer_scale), AV_OPT_TYPE_INT, {.i64=2}, 0, 5, FLAGS },
  87. /* following are the debug options, not part of the official API */
  88. { "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 },
  89. { "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" },
  90. { "nns_iterative", "iterative search", 0, AV_OPT_TYPE_CONST, {.i64=COLOR_SEARCH_NNS_ITERATIVE}, INT_MIN, INT_MAX, FLAGS, "search" },
  91. { "nns_recursive", "recursive search", 0, AV_OPT_TYPE_CONST, {.i64=COLOR_SEARCH_NNS_RECURSIVE}, INT_MIN, INT_MAX, FLAGS, "search" },
  92. { "bruteforce", "brute-force into the palette", 0, AV_OPT_TYPE_CONST, {.i64=COLOR_SEARCH_BRUTEFORCE}, INT_MIN, INT_MAX, FLAGS, "search" },
  93. { "mean_err", "compute and print mean error", OFFSET(calc_mean_err), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS },
  94. { "debug_accuracy", "test color search accuracy", OFFSET(debug_accuracy), AV_OPT_TYPE_FLAGS, {.i64=0}, 0, 1, FLAGS },
  95. { NULL }
  96. };
  97. AVFILTER_DEFINE_CLASS(paletteuse);
  98. static int query_formats(AVFilterContext *ctx)
  99. {
  100. static const enum AVPixelFormat in_fmts[] = {AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE};
  101. static const enum AVPixelFormat inpal_fmts[] = {AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE};
  102. static const enum AVPixelFormat out_fmts[] = {AV_PIX_FMT_PAL8, AV_PIX_FMT_NONE};
  103. AVFilterFormats *in = ff_make_format_list(in_fmts);
  104. AVFilterFormats *inpal = ff_make_format_list(inpal_fmts);
  105. AVFilterFormats *out = ff_make_format_list(out_fmts);
  106. if (!in || !inpal || !out)
  107. return AVERROR(ENOMEM);
  108. ff_formats_ref(in, &ctx->inputs[0]->out_formats);
  109. ff_formats_ref(inpal, &ctx->inputs[1]->out_formats);
  110. ff_formats_ref(out, &ctx->outputs[0]->in_formats);
  111. return 0;
  112. }
  113. static av_always_inline int dither_color(uint32_t px, int er, int eg, int eb, int scale, int shift)
  114. {
  115. return av_clip_uint8((px >> 16 & 0xff) + ((er * scale) >> shift)) << 16
  116. | av_clip_uint8((px >> 8 & 0xff) + ((eg * scale) >> shift)) << 8
  117. | av_clip_uint8((px & 0xff) + ((eb * scale) >> shift));
  118. }
  119. static av_always_inline int diff(const uint8_t *c1, const uint8_t *c2)
  120. {
  121. // XXX: try L*a*b with CIE76 (dL*dL + da*da + db*db)
  122. const int dr = c1[0] - c2[0];
  123. const int dg = c1[1] - c2[1];
  124. const int db = c1[2] - c2[2];
  125. return dr*dr + dg*dg + db*db;
  126. }
  127. static av_always_inline uint8_t colormap_nearest_bruteforce(const uint32_t *palette, const uint8_t *rgb)
  128. {
  129. int i, pal_id = -1, min_dist = INT_MAX;
  130. for (i = 0; i < AVPALETTE_COUNT; i++) {
  131. const uint32_t c = palette[i];
  132. if ((c & 0xff000000) == 0xff000000) { // ignore transparent entry
  133. const uint8_t palrgb[] = {
  134. palette[i]>>16 & 0xff,
  135. palette[i]>> 8 & 0xff,
  136. palette[i] & 0xff,
  137. };
  138. const int d = diff(palrgb, rgb);
  139. if (d < min_dist) {
  140. pal_id = i;
  141. min_dist = d;
  142. }
  143. }
  144. }
  145. return pal_id;
  146. }
  147. /* Recursive form, simpler but a bit slower. Kept for reference. */
  148. struct nearest_color {
  149. int node_pos;
  150. int dist_sqd;
  151. };
  152. static void colormap_nearest_node(const struct color_node *map,
  153. const int node_pos,
  154. const uint8_t *target,
  155. struct nearest_color *nearest)
  156. {
  157. const struct color_node *kd = map + node_pos;
  158. const int s = kd->split;
  159. int dx, nearer_kd_id, further_kd_id;
  160. const uint8_t *current = kd->val;
  161. const int current_to_target = diff(target, current);
  162. if (current_to_target < nearest->dist_sqd) {
  163. nearest->node_pos = node_pos;
  164. nearest->dist_sqd = current_to_target;
  165. }
  166. if (kd->left_id != -1 || kd->right_id != -1) {
  167. dx = target[s] - current[s];
  168. if (dx <= 0) nearer_kd_id = kd->left_id, further_kd_id = kd->right_id;
  169. else nearer_kd_id = kd->right_id, further_kd_id = kd->left_id;
  170. if (nearer_kd_id != -1)
  171. colormap_nearest_node(map, nearer_kd_id, target, nearest);
  172. if (further_kd_id != -1 && dx*dx < nearest->dist_sqd)
  173. colormap_nearest_node(map, further_kd_id, target, nearest);
  174. }
  175. }
  176. static av_always_inline uint8_t colormap_nearest_recursive(const struct color_node *node, const uint8_t *rgb)
  177. {
  178. struct nearest_color res = {.dist_sqd = INT_MAX, .node_pos = -1};
  179. colormap_nearest_node(node, 0, rgb, &res);
  180. return node[res.node_pos].palette_id;
  181. }
  182. struct stack_node {
  183. int color_id;
  184. int dx2;
  185. };
  186. static av_always_inline uint8_t colormap_nearest_iterative(const struct color_node *root, const uint8_t *target)
  187. {
  188. int pos = 0, best_node_id = -1, best_dist = INT_MAX, cur_color_id = 0;
  189. struct stack_node nodes[16];
  190. struct stack_node *node = &nodes[0];
  191. for (;;) {
  192. const struct color_node *kd = &root[cur_color_id];
  193. const uint8_t *current = kd->val;
  194. const int current_to_target = diff(target, current);
  195. /* Compare current color node to the target and update our best node if
  196. * it's actually better. */
  197. if (current_to_target < best_dist) {
  198. best_node_id = cur_color_id;
  199. if (!current_to_target)
  200. goto end; // exact match, we can return immediately
  201. best_dist = current_to_target;
  202. }
  203. /* Check if it's not a leaf */
  204. if (kd->left_id != -1 || kd->right_id != -1) {
  205. const int split = kd->split;
  206. const int dx = target[split] - current[split];
  207. int nearer_kd_id, further_kd_id;
  208. /* Define which side is the most interesting. */
  209. if (dx <= 0) nearer_kd_id = kd->left_id, further_kd_id = kd->right_id;
  210. else nearer_kd_id = kd->right_id, further_kd_id = kd->left_id;
  211. if (nearer_kd_id != -1) {
  212. if (further_kd_id != -1) {
  213. /* Here, both paths are defined, so we push a state for
  214. * when we are going back. */
  215. node->color_id = further_kd_id;
  216. node->dx2 = dx*dx;
  217. pos++;
  218. node++;
  219. }
  220. /* We can now update current color with the most probable path
  221. * (no need to create a state since there is nothing to save
  222. * anymore). */
  223. cur_color_id = nearer_kd_id;
  224. continue;
  225. } else if (dx*dx < best_dist) {
  226. /* The nearest path isn't available, so there is only one path
  227. * possible and it's the least probable. We enter it only if the
  228. * distance from the current point to the hyper rectangle is
  229. * less than our best distance. */
  230. cur_color_id = further_kd_id;
  231. continue;
  232. }
  233. }
  234. /* Unstack as much as we can, typically as long as the least probable
  235. * branch aren't actually probable. */
  236. do {
  237. if (--pos < 0)
  238. goto end;
  239. node--;
  240. } while (node->dx2 >= best_dist);
  241. /* We got a node where the least probable branch might actually contain
  242. * a relevant color. */
  243. cur_color_id = node->color_id;
  244. }
  245. end:
  246. return root[best_node_id].palette_id;
  247. }
  248. #define COLORMAP_NEAREST(search, palette, root, target) \
  249. search == COLOR_SEARCH_NNS_ITERATIVE ? colormap_nearest_iterative(root, target) : \
  250. search == COLOR_SEARCH_NNS_RECURSIVE ? colormap_nearest_recursive(root, target) : \
  251. colormap_nearest_bruteforce(palette, target)
  252. /**
  253. * Check if the requested color is in the cache already. If not, find it in the
  254. * color tree and cache it.
  255. * Note: r, g, and b are the component of c but are passed as well to avoid
  256. * recomputing them (they are generally computed by the caller for other uses).
  257. */
  258. static av_always_inline uint8_t color_get(struct cache_node *cache, uint32_t color,
  259. uint8_t r, uint8_t g, uint8_t b,
  260. const struct color_node *map,
  261. const uint32_t *palette,
  262. const enum color_search_method search_method)
  263. {
  264. int i;
  265. const uint8_t rgb[] = {r, g, b};
  266. const uint8_t rhash = r & ((1<<NBITS)-1);
  267. const uint8_t ghash = g & ((1<<NBITS)-1);
  268. const uint8_t bhash = b & ((1<<NBITS)-1);
  269. const unsigned hash = rhash<<(NBITS*2) | ghash<<NBITS | bhash;
  270. struct cache_node *node = &cache[hash];
  271. struct cached_color *e;
  272. for (i = 0; i < node->nb_entries; i++) {
  273. e = &node->entries[i];
  274. if (e->color == color)
  275. return e->pal_entry;
  276. }
  277. e = av_dynarray2_add((void**)&node->entries, &node->nb_entries,
  278. sizeof(*node->entries), NULL);
  279. if (!e)
  280. return AVERROR(ENOMEM);
  281. e->color = color;
  282. e->pal_entry = COLORMAP_NEAREST(search_method, palette, map, rgb);
  283. return e->pal_entry;
  284. }
  285. static av_always_inline uint8_t get_dst_color_err(struct cache_node *cache,
  286. uint32_t c, const struct color_node *map,
  287. const uint32_t *palette,
  288. int *er, int *eg, int *eb,
  289. const enum color_search_method search_method)
  290. {
  291. const uint8_t r = c >> 16 & 0xff;
  292. const uint8_t g = c >> 8 & 0xff;
  293. const uint8_t b = c & 0xff;
  294. const uint8_t dstx = color_get(cache, c, r, g, b, map, palette, search_method);
  295. const uint32_t dstc = palette[dstx];
  296. *er = r - (dstc >> 16 & 0xff);
  297. *eg = g - (dstc >> 8 & 0xff);
  298. *eb = b - (dstc & 0xff);
  299. return dstx;
  300. }
  301. static av_always_inline int set_frame(PaletteUseContext *s, AVFrame *out, AVFrame *in,
  302. enum dithering_mode dither,
  303. const enum color_search_method search_method)
  304. {
  305. int x, y;
  306. const struct color_node *map = s->map;
  307. struct cache_node *cache = s->cache;
  308. const uint32_t *palette = s->palette;
  309. uint32_t *src = (uint32_t *)in ->data[0];
  310. uint8_t *dst = out->data[0];
  311. const int src_linesize = in ->linesize[0] >> 2;
  312. const int dst_linesize = out->linesize[0];
  313. for (y = 0; y < in->height; y++) {
  314. for (x = 0; x < in->width; x++) {
  315. int er, eg, eb;
  316. if (dither == DITHERING_BAYER) {
  317. const int d = s->ordered_dither[(y & 7)<<3 | (x & 7)];
  318. const uint8_t r8 = src[x] >> 16 & 0xff;
  319. const uint8_t g8 = src[x] >> 8 & 0xff;
  320. const uint8_t b8 = src[x] & 0xff;
  321. const uint8_t r = av_clip_uint8(r8 + d);
  322. const uint8_t g = av_clip_uint8(g8 + d);
  323. const uint8_t b = av_clip_uint8(b8 + d);
  324. const uint32_t c = r<<16 | g<<8 | b;
  325. const int color = color_get(cache, c, r, g, b, map, palette, search_method);
  326. if (color < 0)
  327. return color;
  328. dst[x] = color;
  329. } else if (dither == DITHERING_HECKBERT) {
  330. const int right = x < in->width - 1, down = y < in->height - 1;
  331. const int color = get_dst_color_err(cache, src[x], map, palette, &er, &eg, &eb, search_method);
  332. if (color < 0)
  333. return color;
  334. dst[x] = color;
  335. if (right) src[ x + 1] = dither_color(src[ x + 1], er, eg, eb, 3, 3);
  336. if ( down) src[src_linesize + x ] = dither_color(src[src_linesize + x ], er, eg, eb, 3, 3);
  337. if (right && down) src[src_linesize + x + 1] = dither_color(src[src_linesize + x + 1], er, eg, eb, 2, 3);
  338. } else if (dither == DITHERING_FLOYD_STEINBERG) {
  339. const int right = x < in->width - 1, down = y < in->height - 1, left = x > 0;
  340. const int color = get_dst_color_err(cache, src[x], map, palette, &er, &eg, &eb, search_method);
  341. if (color < 0)
  342. return color;
  343. dst[x] = color;
  344. if (right) src[ x + 1] = dither_color(src[ x + 1], er, eg, eb, 7, 4);
  345. if (left && down) src[src_linesize + x - 1] = dither_color(src[src_linesize + x - 1], er, eg, eb, 3, 4);
  346. if ( down) src[src_linesize + x ] = dither_color(src[src_linesize + x ], er, eg, eb, 5, 4);
  347. if (right && down) src[src_linesize + x + 1] = dither_color(src[src_linesize + x + 1], er, eg, eb, 1, 4);
  348. } else if (dither == DITHERING_SIERRA2) {
  349. const int right = x < in->width - 1, down = y < in->height - 1, left = x > 0;
  350. const int right2 = x < in->width - 2, left2 = x > 1;
  351. const int color = get_dst_color_err(cache, src[x], map, palette, &er, &eg, &eb, search_method);
  352. if (color < 0)
  353. return color;
  354. dst[x] = color;
  355. if (right) src[ x + 1] = dither_color(src[ x + 1], er, eg, eb, 4, 4);
  356. if (right2) src[ x + 2] = dither_color(src[ x + 2], er, eg, eb, 3, 4);
  357. if (down) {
  358. if (left2) src[ src_linesize + x - 2] = dither_color(src[ src_linesize + x - 2], er, eg, eb, 1, 4);
  359. if (left) src[ src_linesize + x - 1] = dither_color(src[ src_linesize + x - 1], er, eg, eb, 2, 4);
  360. src[ src_linesize + x ] = dither_color(src[ src_linesize + x ], er, eg, eb, 3, 4);
  361. if (right) src[ src_linesize + x + 1] = dither_color(src[ src_linesize + x + 1], er, eg, eb, 2, 4);
  362. if (right2) src[ src_linesize + x + 2] = dither_color(src[ src_linesize + x + 2], er, eg, eb, 1, 4);
  363. }
  364. } else if (dither == DITHERING_SIERRA2_4A) {
  365. const int right = x < in->width - 1, down = y < in->height - 1, left = x > 0;
  366. const int color = get_dst_color_err(cache, src[x], map, palette, &er, &eg, &eb, search_method);
  367. if (color < 0)
  368. return color;
  369. dst[x] = color;
  370. if (right) src[ x + 1] = dither_color(src[ x + 1], er, eg, eb, 2, 2);
  371. if (left && down) src[src_linesize + x - 1] = dither_color(src[src_linesize + x - 1], er, eg, eb, 1, 2);
  372. if ( down) src[src_linesize + x ] = dither_color(src[src_linesize + x ], er, eg, eb, 1, 2);
  373. } else {
  374. const uint8_t r = src[x] >> 16 & 0xff;
  375. const uint8_t g = src[x] >> 8 & 0xff;
  376. const uint8_t b = src[x] & 0xff;
  377. const int color = color_get(cache, src[x] & 0xffffff, r, g, b, map, palette, search_method);
  378. if (color < 0)
  379. return color;
  380. dst[x] = color;
  381. }
  382. }
  383. src += src_linesize;
  384. dst += dst_linesize;
  385. }
  386. return 0;
  387. }
  388. #define INDENT 4
  389. static void disp_node(AVBPrint *buf,
  390. const struct color_node *map,
  391. int parent_id, int node_id,
  392. int depth)
  393. {
  394. const struct color_node *node = &map[node_id];
  395. const uint32_t fontcolor = node->val[0] > 0x50 &&
  396. node->val[1] > 0x50 &&
  397. node->val[2] > 0x50 ? 0 : 0xffffff;
  398. av_bprintf(buf, "%*cnode%d ["
  399. "label=\"%c%02X%c%02X%c%02X%c\" "
  400. "fillcolor=\"#%02x%02x%02x\" "
  401. "fontcolor=\"#%06X\"]\n",
  402. depth*INDENT, ' ', node->palette_id,
  403. "[ "[node->split], node->val[0],
  404. "][ "[node->split], node->val[1],
  405. " ]["[node->split], node->val[2],
  406. " ]"[node->split],
  407. node->val[0], node->val[1], node->val[2],
  408. fontcolor);
  409. if (parent_id != -1)
  410. av_bprintf(buf, "%*cnode%d -> node%d\n", depth*INDENT, ' ',
  411. map[parent_id].palette_id, node->palette_id);
  412. if (node->left_id != -1) disp_node(buf, map, node_id, node->left_id, depth + 1);
  413. if (node->right_id != -1) disp_node(buf, map, node_id, node->right_id, depth + 1);
  414. }
  415. // debug_kdtree=kdtree.dot -> dot -Tpng kdtree.dot > kdtree.png
  416. static int disp_tree(const struct color_node *node, const char *fname)
  417. {
  418. AVBPrint buf;
  419. FILE *f = av_fopen_utf8(fname, "w");
  420. if (!f) {
  421. int ret = AVERROR(errno);
  422. av_log(NULL, AV_LOG_ERROR, "Cannot open file '%s' for writing: %s\n",
  423. fname, av_err2str(ret));
  424. return ret;
  425. }
  426. av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
  427. av_bprintf(&buf, "digraph {\n");
  428. av_bprintf(&buf, " node [style=filled fontsize=10 shape=box]\n");
  429. disp_node(&buf, node, -1, 0, 0);
  430. av_bprintf(&buf, "}\n");
  431. fwrite(buf.str, 1, buf.len, f);
  432. fclose(f);
  433. av_bprint_finalize(&buf, NULL);
  434. return 0;
  435. }
  436. static int debug_accuracy(const struct color_node *node, const uint32_t *palette,
  437. const enum color_search_method search_method)
  438. {
  439. int r, g, b, ret = 0;
  440. for (r = 0; r < 256; r++) {
  441. for (g = 0; g < 256; g++) {
  442. for (b = 0; b < 256; b++) {
  443. const uint8_t rgb[] = {r, g, b};
  444. const int r1 = COLORMAP_NEAREST(search_method, palette, node, rgb);
  445. const int r2 = colormap_nearest_bruteforce(palette, rgb);
  446. if (r1 != r2) {
  447. const uint32_t c1 = palette[r1];
  448. const uint32_t c2 = palette[r2];
  449. const uint8_t palrgb1[] = { c1>>16 & 0xff, c1>> 8 & 0xff, c1 & 0xff };
  450. const uint8_t palrgb2[] = { c2>>16 & 0xff, c2>> 8 & 0xff, c2 & 0xff };
  451. const int d1 = diff(palrgb1, rgb);
  452. const int d2 = diff(palrgb2, rgb);
  453. if (d1 != d2) {
  454. av_log(NULL, AV_LOG_ERROR,
  455. "/!\\ %02X%02X%02X: %d ! %d (%06X ! %06X) / dist: %d ! %d\n",
  456. r, g, b, r1, r2, c1 & 0xffffff, c2 & 0xffffff, d1, d2);
  457. ret = 1;
  458. }
  459. }
  460. }
  461. }
  462. }
  463. return ret;
  464. }
  465. struct color {
  466. uint32_t value;
  467. uint8_t pal_id;
  468. };
  469. struct color_rect {
  470. uint8_t min[3];
  471. uint8_t max[3];
  472. };
  473. typedef int (*cmp_func)(const void *, const void *);
  474. #define DECLARE_CMP_FUNC(name, pos) \
  475. static int cmp_##name(const void *pa, const void *pb) \
  476. { \
  477. const struct color *a = pa; \
  478. const struct color *b = pb; \
  479. return (a->value >> (8 * (2 - (pos))) & 0xff) \
  480. - (b->value >> (8 * (2 - (pos))) & 0xff); \
  481. }
  482. DECLARE_CMP_FUNC(r, 0)
  483. DECLARE_CMP_FUNC(g, 1)
  484. DECLARE_CMP_FUNC(b, 2)
  485. static const cmp_func cmp_funcs[] = {cmp_r, cmp_g, cmp_b};
  486. static int get_next_color(const uint8_t *color_used, const uint32_t *palette,
  487. int *component, const struct color_rect *box)
  488. {
  489. int wr, wg, wb;
  490. int i, longest = 0;
  491. unsigned nb_color = 0;
  492. struct color_rect ranges;
  493. struct color tmp_pal[256];
  494. ranges.min[0] = ranges.min[1] = ranges.min[2] = 0xff;
  495. ranges.max[0] = ranges.max[1] = ranges.max[2] = 0x00;
  496. for (i = 0; i < AVPALETTE_COUNT; i++) {
  497. const uint32_t c = palette[i];
  498. const uint8_t r = c >> 16 & 0xff;
  499. const uint8_t g = c >> 8 & 0xff;
  500. const uint8_t b = c & 0xff;
  501. if (color_used[i] ||
  502. r < box->min[0] || g < box->min[1] || b < box->min[2] ||
  503. r > box->max[0] || g > box->max[1] || b > box->max[2])
  504. continue;
  505. if (r < ranges.min[0]) ranges.min[0] = r;
  506. if (g < ranges.min[1]) ranges.min[1] = g;
  507. if (b < ranges.min[2]) ranges.min[2] = b;
  508. if (r > ranges.max[0]) ranges.max[0] = r;
  509. if (g > ranges.max[1]) ranges.max[1] = g;
  510. if (b > ranges.max[2]) ranges.max[2] = b;
  511. tmp_pal[nb_color].value = c;
  512. tmp_pal[nb_color].pal_id = i;
  513. nb_color++;
  514. }
  515. if (!nb_color)
  516. return -1;
  517. /* define longest axis that will be the split component */
  518. wr = ranges.max[0] - ranges.min[0];
  519. wg = ranges.max[1] - ranges.min[1];
  520. wb = ranges.max[2] - ranges.min[2];
  521. if (wr >= wg && wr >= wb) longest = 0;
  522. if (wg >= wr && wg >= wb) longest = 1;
  523. if (wb >= wr && wb >= wg) longest = 2;
  524. *component = longest;
  525. /* sort along this axis to get median */
  526. qsort(tmp_pal, nb_color, sizeof(*tmp_pal), cmp_funcs[longest]);
  527. return tmp_pal[nb_color >> 1].pal_id;
  528. }
  529. static int colormap_insert(struct color_node *map,
  530. uint8_t *color_used,
  531. int *nb_used,
  532. const uint32_t *palette,
  533. const struct color_rect *box)
  534. {
  535. uint32_t c;
  536. int component, cur_id;
  537. int node_left_id = -1, node_right_id = -1;
  538. struct color_node *node;
  539. struct color_rect box1, box2;
  540. const int pal_id = get_next_color(color_used, palette, &component, box);
  541. if (pal_id < 0)
  542. return -1;
  543. /* create new node with that color */
  544. cur_id = (*nb_used)++;
  545. c = palette[pal_id];
  546. node = &map[cur_id];
  547. node->split = component;
  548. node->palette_id = pal_id;
  549. node->val[0] = c>>16 & 0xff;
  550. node->val[1] = c>> 8 & 0xff;
  551. node->val[2] = c & 0xff;
  552. color_used[pal_id] = 1;
  553. /* get the two boxes this node creates */
  554. box1 = box2 = *box;
  555. box1.max[component] = node->val[component];
  556. box2.min[component] = node->val[component] + 1;
  557. node_left_id = colormap_insert(map, color_used, nb_used, palette, &box1);
  558. if (box2.min[component] <= box2.max[component])
  559. node_right_id = colormap_insert(map, color_used, nb_used, palette, &box2);
  560. node->left_id = node_left_id;
  561. node->right_id = node_right_id;
  562. return cur_id;
  563. }
  564. static int cmp_pal_entry(const void *a, const void *b)
  565. {
  566. const int c1 = *(const uint32_t *)a & 0xffffff;
  567. const int c2 = *(const uint32_t *)b & 0xffffff;
  568. return c1 - c2;
  569. }
  570. static void load_colormap(PaletteUseContext *s)
  571. {
  572. int i, nb_used = 0;
  573. uint8_t color_used[AVPALETTE_COUNT] = {0};
  574. uint32_t last_color = 0;
  575. struct color_rect box;
  576. /* disable transparent colors and dups */
  577. qsort(s->palette, AVPALETTE_COUNT, sizeof(*s->palette), cmp_pal_entry);
  578. for (i = 0; i < AVPALETTE_COUNT; i++) {
  579. const uint32_t c = s->palette[i];
  580. if (i != 0 && c == last_color) {
  581. color_used[i] = 1;
  582. continue;
  583. }
  584. last_color = c;
  585. if ((c & 0xff000000) != 0xff000000) {
  586. color_used[i] = 1; // ignore transparent color(s)
  587. continue;
  588. }
  589. }
  590. box.min[0] = box.min[1] = box.min[2] = 0x00;
  591. box.max[0] = box.max[1] = box.max[2] = 0xff;
  592. colormap_insert(s->map, color_used, &nb_used, s->palette, &box);
  593. if (s->dot_filename)
  594. disp_tree(s->map, s->dot_filename);
  595. if (s->debug_accuracy) {
  596. if (!debug_accuracy(s->map, s->palette, s->color_search_method))
  597. av_log(NULL, AV_LOG_INFO, "Accuracy check passed\n");
  598. }
  599. }
  600. static void debug_mean_error(PaletteUseContext *s, const AVFrame *in1,
  601. const AVFrame *in2, int frame_count)
  602. {
  603. int x, y;
  604. const uint32_t *palette = s->palette;
  605. uint32_t *src1 = (uint32_t *)in1->data[0];
  606. uint8_t *src2 = in2->data[0];
  607. const int src1_linesize = in1->linesize[0] >> 2;
  608. const int src2_linesize = in2->linesize[0];
  609. const float div = in1->width * in1->height * 3;
  610. unsigned mean_err = 0;
  611. for (y = 0; y < in1->height; y++) {
  612. for (x = 0; x < in1->width; x++) {
  613. const uint32_t c1 = src1[x];
  614. const uint32_t c2 = palette[src2[x]];
  615. const uint8_t rgb1[] = {c1 >> 16 & 0xff, c1 >> 8 & 0xff, c1 & 0xff};
  616. const uint8_t rgb2[] = {c2 >> 16 & 0xff, c2 >> 8 & 0xff, c2 & 0xff};
  617. mean_err += diff(rgb1, rgb2);
  618. }
  619. src1 += src1_linesize;
  620. src2 += src2_linesize;
  621. }
  622. s->total_mean_err += mean_err;
  623. av_log(NULL, AV_LOG_INFO, "MEP:%.3f TotalMEP:%.3f\n",
  624. mean_err / div, s->total_mean_err / (div * frame_count));
  625. }
  626. static AVFrame *apply_palette(AVFilterLink *inlink, AVFrame *in)
  627. {
  628. AVFilterContext *ctx = inlink->dst;
  629. PaletteUseContext *s = ctx->priv;
  630. AVFilterLink *outlink = inlink->dst->outputs[0];
  631. AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
  632. if (!out) {
  633. av_frame_free(&in);
  634. return NULL;
  635. }
  636. av_frame_copy_props(out, in);
  637. if (s->set_frame(s, out, in) < 0) {
  638. av_frame_free(&in);
  639. av_frame_free(&out);
  640. return NULL;
  641. }
  642. memcpy(out->data[1], s->palette, AVPALETTE_SIZE);
  643. if (s->calc_mean_err)
  644. debug_mean_error(s, in, out, inlink->frame_count);
  645. av_frame_free(&in);
  646. return out;
  647. }
  648. static int config_output(AVFilterLink *outlink)
  649. {
  650. int ret;
  651. AVFilterContext *ctx = outlink->src;
  652. PaletteUseContext *s = ctx->priv;
  653. outlink->w = ctx->inputs[0]->w;
  654. outlink->h = ctx->inputs[0]->h;
  655. outlink->time_base = ctx->inputs[0]->time_base;
  656. if ((ret = ff_dualinput_init(ctx, &s->dinput)) < 0)
  657. return ret;
  658. return 0;
  659. }
  660. static int config_input_palette(AVFilterLink *inlink)
  661. {
  662. AVFilterContext *ctx = inlink->dst;
  663. if (inlink->w * inlink->h != AVPALETTE_COUNT) {
  664. av_log(ctx, AV_LOG_ERROR,
  665. "Palette input must contain exactly %d pixels. "
  666. "Specified input has %dx%d=%d pixels\n",
  667. AVPALETTE_COUNT, inlink->w, inlink->h,
  668. inlink->w * inlink->h);
  669. return AVERROR(EINVAL);
  670. }
  671. return 0;
  672. }
  673. static void load_palette(PaletteUseContext *s, const AVFrame *palette_frame)
  674. {
  675. int i, x, y;
  676. const uint32_t *p = (const uint32_t *)palette_frame->data[0];
  677. const int p_linesize = palette_frame->linesize[0] >> 2;
  678. i = 0;
  679. for (y = 0; y < palette_frame->height; y++) {
  680. for (x = 0; x < palette_frame->width; x++)
  681. s->palette[i++] = p[x];
  682. p += p_linesize;
  683. }
  684. load_colormap(s);
  685. s->palette_loaded = 1;
  686. }
  687. static AVFrame *load_apply_palette(AVFilterContext *ctx, AVFrame *main,
  688. const AVFrame *second)
  689. {
  690. AVFilterLink *inlink = ctx->inputs[0];
  691. PaletteUseContext *s = ctx->priv;
  692. if (!s->palette_loaded) {
  693. load_palette(s, second);
  694. }
  695. return apply_palette(inlink, main);
  696. }
  697. static int filter_frame(AVFilterLink *inlink, AVFrame *in)
  698. {
  699. PaletteUseContext *s = inlink->dst->priv;
  700. return ff_dualinput_filter_frame(&s->dinput, inlink, in);
  701. }
  702. #define DEFINE_SET_FRAME(color_search, name, value) \
  703. static int set_frame_##name(PaletteUseContext *s, AVFrame *out, AVFrame *in) \
  704. { \
  705. return set_frame(s, out, in, value, color_search); \
  706. }
  707. #define DEFINE_SET_FRAME_COLOR_SEARCH(color_search, color_search_macro) \
  708. DEFINE_SET_FRAME(color_search_macro, color_search##_##none, DITHERING_NONE) \
  709. DEFINE_SET_FRAME(color_search_macro, color_search##_##bayer, DITHERING_BAYER) \
  710. DEFINE_SET_FRAME(color_search_macro, color_search##_##heckbert, DITHERING_HECKBERT) \
  711. DEFINE_SET_FRAME(color_search_macro, color_search##_##floyd_steinberg, DITHERING_FLOYD_STEINBERG) \
  712. DEFINE_SET_FRAME(color_search_macro, color_search##_##sierra2, DITHERING_SIERRA2) \
  713. DEFINE_SET_FRAME(color_search_macro, color_search##_##sierra2_4a, DITHERING_SIERRA2_4A) \
  714. DEFINE_SET_FRAME_COLOR_SEARCH(nns_iterative, COLOR_SEARCH_NNS_ITERATIVE)
  715. DEFINE_SET_FRAME_COLOR_SEARCH(nns_recursive, COLOR_SEARCH_NNS_RECURSIVE)
  716. DEFINE_SET_FRAME_COLOR_SEARCH(bruteforce, COLOR_SEARCH_BRUTEFORCE)
  717. #define DITHERING_ENTRIES(color_search) { \
  718. set_frame_##color_search##_none, \
  719. set_frame_##color_search##_bayer, \
  720. set_frame_##color_search##_heckbert, \
  721. set_frame_##color_search##_floyd_steinberg, \
  722. set_frame_##color_search##_sierra2, \
  723. set_frame_##color_search##_sierra2_4a, \
  724. }
  725. static const set_frame_func set_frame_lut[NB_COLOR_SEARCHES][NB_DITHERING] = {
  726. DITHERING_ENTRIES(nns_iterative),
  727. DITHERING_ENTRIES(nns_recursive),
  728. DITHERING_ENTRIES(bruteforce),
  729. };
  730. static int dither_value(int p)
  731. {
  732. const int q = p ^ (p >> 3);
  733. return (p & 4) >> 2 | (q & 4) >> 1 \
  734. | (p & 2) << 1 | (q & 2) << 2 \
  735. | (p & 1) << 4 | (q & 1) << 5;
  736. }
  737. static av_cold int init(AVFilterContext *ctx)
  738. {
  739. PaletteUseContext *s = ctx->priv;
  740. s->dinput.repeatlast = 1; // only 1 frame in the palette
  741. s->dinput.process = load_apply_palette;
  742. s->set_frame = set_frame_lut[s->color_search_method][s->dither];
  743. if (s->dither == DITHERING_BAYER) {
  744. int i;
  745. const int delta = 1 << (5 - s->bayer_scale); // to avoid too much luma
  746. for (i = 0; i < FF_ARRAY_ELEMS(s->ordered_dither); i++)
  747. s->ordered_dither[i] = (dither_value(i) >> s->bayer_scale) - delta;
  748. }
  749. return 0;
  750. }
  751. static int request_frame(AVFilterLink *outlink)
  752. {
  753. PaletteUseContext *s = outlink->src->priv;
  754. return ff_dualinput_request_frame(&s->dinput, outlink);
  755. }
  756. static av_cold void uninit(AVFilterContext *ctx)
  757. {
  758. int i;
  759. PaletteUseContext *s = ctx->priv;
  760. ff_dualinput_uninit(&s->dinput);
  761. for (i = 0; i < CACHE_SIZE; i++)
  762. av_freep(&s->cache[i].entries);
  763. }
  764. static const AVFilterPad paletteuse_inputs[] = {
  765. {
  766. .name = "default",
  767. .type = AVMEDIA_TYPE_VIDEO,
  768. .filter_frame = filter_frame,
  769. .needs_writable = 1, // for error diffusal dithering
  770. },{
  771. .name = "palette",
  772. .type = AVMEDIA_TYPE_VIDEO,
  773. .config_props = config_input_palette,
  774. .filter_frame = filter_frame,
  775. },
  776. { NULL }
  777. };
  778. static const AVFilterPad paletteuse_outputs[] = {
  779. {
  780. .name = "default",
  781. .type = AVMEDIA_TYPE_VIDEO,
  782. .config_props = config_output,
  783. .request_frame = request_frame,
  784. },
  785. { NULL }
  786. };
  787. AVFilter ff_vf_paletteuse = {
  788. .name = "paletteuse",
  789. .description = NULL_IF_CONFIG_SMALL("Use a palette to downsample an input video stream."),
  790. .priv_size = sizeof(PaletteUseContext),
  791. .query_formats = query_formats,
  792. .init = init,
  793. .uninit = uninit,
  794. .inputs = paletteuse_inputs,
  795. .outputs = paletteuse_outputs,
  796. .priv_class = &paletteuse_class,
  797. };