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.

567 lines
18KB

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