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.

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