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.

1069 lines
39KB

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