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.

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