vf_palettegen.c 19 KB

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