vf_palettegen.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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. * Generate one palette for a whole video stream.
  23. */
  24. #include "libavutil/avassert.h"
  25. #include "libavutil/opt.h"
  26. #include "libavutil/qsort.h"
  27. #include "avfilter.h"
  28. #include "internal.h"
  29. /* Reference a color and how much it's used */
  30. struct color_ref {
  31. uint32_t color;
  32. uint64_t count;
  33. };
  34. /* Store a range of colors */
  35. struct range_box {
  36. uint32_t color; // average color
  37. int64_t variance; // overall variance of the box (how much the colors are spread)
  38. int start; // index in PaletteGenContext->refs
  39. int len; // number of referenced colors
  40. int sorted_by; // whether range of colors is sorted by red (0), green (1) or blue (2)
  41. };
  42. struct hist_node {
  43. struct color_ref *entries;
  44. int nb_entries;
  45. };
  46. enum {
  47. STATS_MODE_ALL_FRAMES,
  48. STATS_MODE_DIFF_FRAMES,
  49. NB_STATS_MODE
  50. };
  51. #define NBITS 5
  52. #define HIST_SIZE (1<<(3*NBITS))
  53. typedef struct {
  54. const AVClass *class;
  55. int max_colors;
  56. int reserve_transparent;
  57. int stats_mode;
  58. AVFrame *prev_frame; // previous frame used for the diff stats_mode
  59. struct hist_node histogram[HIST_SIZE]; // histogram/hashtable of the colors
  60. struct color_ref **refs; // references of all the colors used in the stream
  61. int nb_refs; // number of color references (or number of different colors)
  62. struct range_box boxes[256]; // define the segmentation of the colorspace (the final palette)
  63. int nb_boxes; // number of boxes (increase will segmenting them)
  64. int palette_pushed; // if the palette frame is pushed into the outlink or not
  65. } PaletteGenContext;
  66. #define OFFSET(x) offsetof(PaletteGenContext, x)
  67. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  68. static const AVOption palettegen_options[] = {
  69. { "max_colors", "set the maximum number of colors to use in the palette", OFFSET(max_colors), AV_OPT_TYPE_INT, {.i64=256}, 4, 256, FLAGS },
  70. { "reserve_transparent", "reserve a palette entry for transparency", OFFSET(reserve_transparent), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS },
  71. { "stats_mode", "set statistics mode", OFFSET(stats_mode), AV_OPT_TYPE_INT, {.i64=STATS_MODE_ALL_FRAMES}, 0, NB_STATS_MODE, FLAGS, "mode" },
  72. { "full", "compute full frame histograms", 0, AV_OPT_TYPE_CONST, {.i64=STATS_MODE_ALL_FRAMES}, INT_MIN, INT_MAX, FLAGS, "mode" },
  73. { "diff", "compute histograms only for the part that differs from previous frame", 0, AV_OPT_TYPE_CONST, {.i64=STATS_MODE_DIFF_FRAMES}, INT_MIN, INT_MAX, FLAGS, "mode" },
  74. { NULL }
  75. };
  76. AVFILTER_DEFINE_CLASS(palettegen);
  77. static int query_formats(AVFilterContext *ctx)
  78. {
  79. static const enum AVPixelFormat in_fmts[] = {AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE};
  80. static const enum AVPixelFormat out_fmts[] = {AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE};
  81. AVFilterFormats *in = ff_make_format_list(in_fmts);
  82. AVFilterFormats *out = ff_make_format_list(out_fmts);
  83. if (!in || !out) {
  84. av_freep(&in);
  85. av_freep(&out);
  86. return AVERROR(ENOMEM);
  87. }
  88. ff_formats_ref(in, &ctx->inputs[0]->out_formats);
  89. ff_formats_ref(out, &ctx->outputs[0]->in_formats);
  90. return 0;
  91. }
  92. typedef int (*cmp_func)(const void *, const void *);
  93. #define DECLARE_CMP_FUNC(name, pos) \
  94. static int cmp_##name(const void *pa, const void *pb) \
  95. { \
  96. const struct color_ref * const *a = pa; \
  97. const struct color_ref * const *b = pb; \
  98. return ((*a)->color >> (8 * (2 - (pos))) & 0xff) \
  99. - ((*b)->color >> (8 * (2 - (pos))) & 0xff); \
  100. }
  101. DECLARE_CMP_FUNC(r, 0)
  102. DECLARE_CMP_FUNC(g, 1)
  103. DECLARE_CMP_FUNC(b, 2)
  104. static const cmp_func cmp_funcs[] = {cmp_r, cmp_g, cmp_b};
  105. /**
  106. * Simple color comparison for sorting the final palette
  107. */
  108. static int cmp_color(const void *a, const void *b)
  109. {
  110. const struct range_box *box1 = a;
  111. const struct range_box *box2 = b;
  112. return box1->color - box2->color;
  113. }
  114. static av_always_inline int diff(const uint32_t a, const uint32_t b)
  115. {
  116. const uint8_t c1[] = {a >> 16 & 0xff, a >> 8 & 0xff, a & 0xff};
  117. const uint8_t c2[] = {b >> 16 & 0xff, b >> 8 & 0xff, b & 0xff};
  118. const int dr = c1[0] - c2[0];
  119. const int dg = c1[1] - c2[1];
  120. const int db = c1[2] - c2[2];
  121. return dr*dr + dg*dg + db*db;
  122. }
  123. /**
  124. * Find the next box to split: pick the one with the highest variance
  125. */
  126. static int get_next_box_id_to_split(PaletteGenContext *s)
  127. {
  128. int box_id, i, best_box_id = -1;
  129. int64_t max_variance = -1;
  130. if (s->nb_boxes == s->max_colors - s->reserve_transparent)
  131. return -1;
  132. for (box_id = 0; box_id < s->nb_boxes; box_id++) {
  133. struct range_box *box = &s->boxes[box_id];
  134. if (s->boxes[box_id].len >= 2) {
  135. if (box->variance == -1) {
  136. int64_t variance = 0;
  137. for (i = 0; i < box->len; i++) {
  138. const struct color_ref *ref = s->refs[box->start + i];
  139. variance += diff(ref->color, box->color) * ref->count;
  140. }
  141. box->variance = variance;
  142. }
  143. if (box->variance > max_variance) {
  144. best_box_id = box_id;
  145. max_variance = box->variance;
  146. }
  147. } else {
  148. box->variance = -1;
  149. }
  150. }
  151. return best_box_id;
  152. }
  153. /**
  154. * Get the 32-bit average color for the range of RGB colors enclosed in the
  155. * specified box. Takes into account the weight of each color.
  156. */
  157. static uint32_t get_avg_color(struct color_ref * const *refs,
  158. const struct range_box *box)
  159. {
  160. int i;
  161. const int n = box->len;
  162. uint64_t r = 0, g = 0, b = 0, div = 0;
  163. for (i = 0; i < n; i++) {
  164. const struct color_ref *ref = refs[box->start + i];
  165. r += (ref->color >> 16 & 0xff) * ref->count;
  166. g += (ref->color >> 8 & 0xff) * ref->count;
  167. b += (ref->color & 0xff) * ref->count;
  168. div += ref->count;
  169. }
  170. r = r / div;
  171. g = g / div;
  172. b = b / div;
  173. return 0xffU<<24 | r<<16 | g<<8 | b;
  174. }
  175. /**
  176. * Split given box in two at position n. The original box becomes the left part
  177. * of the split, and the new index box is the right part.
  178. */
  179. static void split_box(PaletteGenContext *s, struct range_box *box, int n)
  180. {
  181. struct range_box *new_box = &s->boxes[s->nb_boxes++];
  182. new_box->start = n + 1;
  183. new_box->len = box->start + box->len - new_box->start;
  184. new_box->sorted_by = box->sorted_by;
  185. box->len -= new_box->len;
  186. av_assert0(box->len >= 1);
  187. av_assert0(new_box->len >= 1);
  188. box->color = get_avg_color(s->refs, box);
  189. new_box->color = get_avg_color(s->refs, new_box);
  190. box->variance = -1;
  191. new_box->variance = -1;
  192. }
  193. /**
  194. * Write the palette into the output frame.
  195. */
  196. static void write_palette(AVFilterContext *ctx, AVFrame *out)
  197. {
  198. const PaletteGenContext *s = ctx->priv;
  199. int x, y, box_id = 0;
  200. uint32_t *pal = (uint32_t *)out->data[0];
  201. const int pal_linesize = out->linesize[0] >> 2;
  202. uint32_t last_color = 0;
  203. for (y = 0; y < out->height; y++) {
  204. for (x = 0; x < out->width; x++) {
  205. if (box_id < s->nb_boxes) {
  206. pal[x] = s->boxes[box_id++].color;
  207. if ((x || y) && pal[x] == last_color)
  208. av_log(ctx, AV_LOG_WARNING, "Dupped color: %08X\n", pal[x]);
  209. last_color = pal[x];
  210. } else {
  211. pal[x] = 0xff000000; // pad with black
  212. }
  213. }
  214. pal += pal_linesize;
  215. }
  216. if (s->reserve_transparent) {
  217. av_assert0(s->nb_boxes < 256);
  218. pal[out->width - pal_linesize - 1] = 0x0000ff00; // add a green transparent color
  219. }
  220. }
  221. /**
  222. * Crawl the histogram to get all the defined colors, and create a linear list
  223. * of them (each color reference entry is a pointer to the value in the
  224. * histogram/hash table).
  225. */
  226. static struct color_ref **load_color_refs(const struct hist_node *hist, int nb_refs)
  227. {
  228. int i, j, k = 0;
  229. struct color_ref **refs = av_malloc_array(nb_refs, sizeof(*refs));
  230. if (!refs)
  231. return NULL;
  232. for (j = 0; j < HIST_SIZE; j++) {
  233. const struct hist_node *node = &hist[j];
  234. for (i = 0; i < node->nb_entries; i++)
  235. refs[k++] = &node->entries[i];
  236. }
  237. return refs;
  238. }
  239. static double set_colorquant_ratio_meta(AVFrame *out, int nb_out, int nb_in)
  240. {
  241. char buf[32];
  242. const double ratio = (double)nb_out / nb_in;
  243. snprintf(buf, sizeof(buf), "%f", ratio);
  244. av_dict_set(&out->metadata, "lavfi.color_quant_ratio", buf, 0);
  245. return ratio;
  246. }
  247. /**
  248. * Main function implementing the Median Cut Algorithm defined by Paul Heckbert
  249. * in Color Image Quantization for Frame Buffer Display (1982)
  250. */
  251. static AVFrame *get_palette_frame(AVFilterContext *ctx)
  252. {
  253. AVFrame *out;
  254. PaletteGenContext *s = ctx->priv;
  255. AVFilterLink *outlink = ctx->outputs[0];
  256. double ratio;
  257. int box_id = 0;
  258. struct range_box *box;
  259. /* reference only the used colors from histogram */
  260. s->refs = load_color_refs(s->histogram, s->nb_refs);
  261. if (!s->refs) {
  262. av_log(ctx, AV_LOG_ERROR, "Unable to allocate references for %d different colors\n", s->nb_refs);
  263. return NULL;
  264. }
  265. /* create the palette frame */
  266. out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
  267. if (!out)
  268. return NULL;
  269. out->pts = 0;
  270. /* set first box for 0..nb_refs */
  271. box = &s->boxes[box_id];
  272. box->len = s->nb_refs;
  273. box->sorted_by = -1;
  274. box->color = get_avg_color(s->refs, box);
  275. box->variance = -1;
  276. s->nb_boxes = 1;
  277. while (box && box->len > 1) {
  278. int i, rr, gr, br, longest;
  279. uint64_t median, box_weight = 0;
  280. /* compute the box weight (sum all the weights of the colors in the
  281. * range) and its boundings */
  282. uint8_t min[3] = {0xff, 0xff, 0xff};
  283. uint8_t max[3] = {0x00, 0x00, 0x00};
  284. for (i = box->start; i < box->start + box->len; i++) {
  285. const struct color_ref *ref = s->refs[i];
  286. const uint32_t rgb = ref->color;
  287. const uint8_t r = rgb >> 16 & 0xff, g = rgb >> 8 & 0xff, b = rgb & 0xff;
  288. min[0] = FFMIN(r, min[0]), max[0] = FFMAX(r, max[0]);
  289. min[1] = FFMIN(g, min[1]), max[1] = FFMAX(g, max[1]);
  290. min[2] = FFMIN(b, min[2]), max[2] = FFMAX(b, max[2]);
  291. box_weight += ref->count;
  292. }
  293. /* define the axis to sort by according to the widest range of colors */
  294. rr = max[0] - min[0];
  295. gr = max[1] - min[1];
  296. br = max[2] - min[2];
  297. longest = 1; // pick green by default (the color the eye is the most sensitive to)
  298. if (br >= rr && br >= gr) longest = 2;
  299. if (rr >= gr && rr >= br) longest = 0;
  300. if (gr >= rr && gr >= br) longest = 1; // prefer green again
  301. av_dlog(ctx, "box #%02X [%6d..%-6d] (%6d) w:%-6"PRIu64" ranges:[%2x %2x %2x] sort by %c (already sorted:%c) ",
  302. box_id, box->start, box->start + box->len - 1, box->len, box_weight,
  303. rr, gr, br, "rgb"[longest], box->sorted_by == longest ? 'y':'n');
  304. /* sort the range by its longest axis if it's not already sorted */
  305. if (box->sorted_by != longest) {
  306. cmp_func cmpf = cmp_funcs[longest];
  307. AV_QSORT(&s->refs[box->start], box->len, const struct color_ref *, cmpf);
  308. box->sorted_by = longest;
  309. }
  310. /* locate the median where to split */
  311. median = (box_weight + 1) >> 1;
  312. box_weight = 0;
  313. /* if you have 2 boxes, the maximum is actually #0: you must have at
  314. * least 1 color on each side of the split, hence the -2 */
  315. for (i = box->start; i < box->start + box->len - 2; i++) {
  316. box_weight += s->refs[i]->count;
  317. if (box_weight > median)
  318. break;
  319. }
  320. av_dlog(ctx, "split @ i=%-6d with w=%-6"PRIu64" (target=%6"PRIu64")\n", i, box_weight, median);
  321. split_box(s, box, i);
  322. box_id = get_next_box_id_to_split(s);
  323. box = box_id >= 0 ? &s->boxes[box_id] : NULL;
  324. }
  325. ratio = set_colorquant_ratio_meta(out, s->nb_boxes, s->nb_refs);
  326. av_log(ctx, AV_LOG_INFO, "%d%s colors generated out of %d colors; ratio=%f\n",
  327. s->nb_boxes, s->reserve_transparent ? "(+1)" : "", s->nb_refs, ratio);
  328. qsort(s->boxes, s->nb_boxes, sizeof(*s->boxes), cmp_color);
  329. write_palette(ctx, out);
  330. return out;
  331. }
  332. /**
  333. * Hashing function for the color.
  334. * It keeps the NBITS least significant bit of each component to make it
  335. * "random" even if the scene doesn't have much different colors.
  336. */
  337. static inline unsigned color_hash(uint32_t color)
  338. {
  339. const uint8_t r = color >> 16 & ((1<<NBITS)-1);
  340. const uint8_t g = color >> 8 & ((1<<NBITS)-1);
  341. const uint8_t b = color & ((1<<NBITS)-1);
  342. return r<<(NBITS*2) | g<<NBITS | b;
  343. }
  344. /**
  345. * Locate the color in the hash table and increment its counter.
  346. */
  347. static int color_inc(struct hist_node *hist, uint32_t color)
  348. {
  349. int i;
  350. const unsigned hash = color_hash(color);
  351. struct hist_node *node = &hist[hash];
  352. struct color_ref *e;
  353. for (i = 0; i < node->nb_entries; i++) {
  354. e = &node->entries[i];
  355. if (e->color == color) {
  356. e->count++;
  357. return 0;
  358. }
  359. }
  360. e = av_dynarray2_add((void**)&node->entries, &node->nb_entries,
  361. sizeof(*node->entries), NULL);
  362. if (!e)
  363. return AVERROR(ENOMEM);
  364. e->color = color;
  365. e->count = 1;
  366. return 1;
  367. }
  368. /**
  369. * Update histogram when pixels differ from previous frame.
  370. */
  371. static int update_histogram_diff(struct hist_node *hist,
  372. const AVFrame *f1, const AVFrame *f2)
  373. {
  374. int x, y, ret, nb_diff_colors = 0;
  375. for (y = 0; y < f1->height; y++) {
  376. const uint32_t *p = (const uint32_t *)(f1->data[0] + y*f1->linesize[0]);
  377. const uint32_t *q = (const uint32_t *)(f2->data[0] + y*f2->linesize[0]);
  378. for (x = 0; x < f1->width; x++) {
  379. if (p[x] == q[x])
  380. continue;
  381. ret = color_inc(hist, p[x]);
  382. if (ret < 0)
  383. return ret;
  384. nb_diff_colors += ret;
  385. }
  386. }
  387. return nb_diff_colors;
  388. }
  389. /**
  390. * Simple histogram of the frame.
  391. */
  392. static int update_histogram_frame(struct hist_node *hist, const AVFrame *f)
  393. {
  394. int x, y, ret, nb_diff_colors = 0;
  395. for (y = 0; y < f->height; y++) {
  396. const uint32_t *p = (const uint32_t *)(f->data[0] + y*f->linesize[0]);
  397. for (x = 0; x < f->width; x++) {
  398. ret = color_inc(hist, p[x]);
  399. if (ret < 0)
  400. return ret;
  401. nb_diff_colors += ret;
  402. }
  403. }
  404. return nb_diff_colors;
  405. }
  406. /**
  407. * Update the histogram for each passing frame. No frame will be pushed here.
  408. */
  409. static int filter_frame(AVFilterLink *inlink, AVFrame *in)
  410. {
  411. AVFilterContext *ctx = inlink->dst;
  412. PaletteGenContext *s = ctx->priv;
  413. const int ret = s->prev_frame ? update_histogram_diff(s->histogram, s->prev_frame, in)
  414. : update_histogram_frame(s->histogram, in);
  415. if (ret > 0)
  416. s->nb_refs += ret;
  417. if (s->stats_mode == STATS_MODE_DIFF_FRAMES) {
  418. av_frame_free(&s->prev_frame);
  419. s->prev_frame = in;
  420. } else {
  421. av_frame_free(&in);
  422. }
  423. return ret;
  424. }
  425. /**
  426. * Returns only one frame at the end containing the full palette.
  427. */
  428. static int request_frame(AVFilterLink *outlink)
  429. {
  430. AVFilterContext *ctx = outlink->src;
  431. AVFilterLink *inlink = ctx->inputs[0];
  432. PaletteGenContext *s = ctx->priv;
  433. int r;
  434. r = ff_request_frame(inlink);
  435. if (r == AVERROR_EOF && !s->palette_pushed && s->nb_refs) {
  436. r = ff_filter_frame(outlink, get_palette_frame(ctx));
  437. s->palette_pushed = 1;
  438. return r;
  439. }
  440. return r;
  441. }
  442. /**
  443. * The output is one simple 16x16 squared-pixels palette.
  444. */
  445. static int config_output(AVFilterLink *outlink)
  446. {
  447. outlink->w = outlink->h = 16;
  448. outlink->sample_aspect_ratio = av_make_q(1, 1);
  449. outlink->flags |= FF_LINK_FLAG_REQUEST_LOOP;
  450. return 0;
  451. }
  452. static av_cold void uninit(AVFilterContext *ctx)
  453. {
  454. int i;
  455. PaletteGenContext *s = ctx->priv;
  456. for (i = 0; i < HIST_SIZE; i++)
  457. av_freep(&s->histogram[i].entries);
  458. av_freep(&s->refs);
  459. av_frame_free(&s->prev_frame);
  460. }
  461. static const AVFilterPad palettegen_inputs[] = {
  462. {
  463. .name = "default",
  464. .type = AVMEDIA_TYPE_VIDEO,
  465. .filter_frame = filter_frame,
  466. },
  467. { NULL }
  468. };
  469. static const AVFilterPad palettegen_outputs[] = {
  470. {
  471. .name = "default",
  472. .type = AVMEDIA_TYPE_VIDEO,
  473. .config_props = config_output,
  474. .request_frame = request_frame,
  475. },
  476. { NULL }
  477. };
  478. AVFilter ff_vf_palettegen = {
  479. .name = "palettegen",
  480. .description = NULL_IF_CONFIG_SMALL("Find the optimal palette for a given stream."),
  481. .priv_size = sizeof(PaletteGenContext),
  482. .uninit = uninit,
  483. .query_formats = query_formats,
  484. .inputs = palettegen_inputs,
  485. .outputs = palettegen_outputs,
  486. .priv_class = &palettegen_class,
  487. };