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.

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