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.

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