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.

1087 lines
40KB

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