vf_palettegen.c 18 KB

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