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.

553 lines
17KB

  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/opt.h"
  26. #include "avfilter.h"
  27. #include "internal.h"
  28. /* Reference a color and how much it's used */
  29. struct color_ref {
  30. uint32_t color;
  31. uint64_t count;
  32. };
  33. /* Store a range of colors */
  34. struct range_box {
  35. uint32_t color; // average color
  36. int64_t variance; // overall variance of the box (how much the colors are spread)
  37. int start; // index in PaletteGenContext->refs
  38. int len; // number of referenced colors
  39. int sorted_by; // whether range of colors is sorted by red (0), green (1) or blue (2)
  40. };
  41. struct hist_node {
  42. struct color_ref *entries;
  43. int nb_entries;
  44. };
  45. enum {
  46. STATS_MODE_ALL_FRAMES,
  47. STATS_MODE_DIFF_FRAMES,
  48. NB_STATS_MODE
  49. };
  50. #define NBITS 5
  51. #define HIST_SIZE (1<<(3*NBITS))
  52. typedef struct {
  53. const AVClass *class;
  54. int max_colors;
  55. int reserve_transparent;
  56. int stats_mode;
  57. AVFrame *prev_frame; // previous frame used for the diff stats_mode
  58. struct hist_node histogram[HIST_SIZE]; // histogram/hashtable of the colors
  59. struct color_ref **refs; // references of all the colors used in the stream
  60. int nb_refs; // number of color references (or number of different colors)
  61. struct range_box boxes[256]; // define the segmentation of the colorspace (the final palette)
  62. int nb_boxes; // number of boxes (increase will segmenting them)
  63. int palette_pushed; // if the palette frame is pushed into the outlink or not
  64. } PaletteGenContext;
  65. #define OFFSET(x) offsetof(PaletteGenContext, x)
  66. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  67. static const AVOption palettegen_options[] = {
  68. { "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 },
  69. { "reserve_transparent", "reserve a palette entry for transparency", OFFSET(reserve_transparent), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS },
  70. { "stats_mode", "set statistics mode", OFFSET(stats_mode), AV_OPT_TYPE_INT, {.i64=STATS_MODE_ALL_FRAMES}, 0, NB_STATS_MODE, FLAGS, "mode" },
  71. { "full", "compute full frame histograms", 0, AV_OPT_TYPE_CONST, {.i64=STATS_MODE_ALL_FRAMES}, INT_MIN, INT_MAX, FLAGS, "mode" },
  72. { "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" },
  73. { NULL }
  74. };
  75. AVFILTER_DEFINE_CLASS(palettegen);
  76. static int query_formats(AVFilterContext *ctx)
  77. {
  78. static const enum AVPixelFormat in_fmts[] = {AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE};
  79. static const enum AVPixelFormat out_fmts[] = {AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE};
  80. AVFilterFormats *in = ff_make_format_list(in_fmts);
  81. AVFilterFormats *out = ff_make_format_list(out_fmts);
  82. if (!in || !out) {
  83. av_freep(&in);
  84. av_freep(&out);
  85. return AVERROR(ENOMEM);
  86. }
  87. ff_formats_ref(in, &ctx->inputs[0]->out_formats);
  88. ff_formats_ref(out, &ctx->outputs[0]->in_formats);
  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 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(const PaletteGenContext *s, AVFrame *out)
  196. {
  197. int x, y, box_id = 0;
  198. uint32_t *pal = (uint32_t *)out->data[0];
  199. const int pal_linesize = out->linesize[0] >> 2;
  200. uint32_t last_color = 0;
  201. for (y = 0; y < out->height; y++) {
  202. for (x = 0; x < out->width; x++) {
  203. if (box_id < s->nb_boxes) {
  204. pal[x] = s->boxes[box_id++].color;
  205. if ((x || y) && pal[x] == last_color)
  206. av_log(NULL, AV_LOG_WARNING, "Dupped color: %08X\n", pal[x]);
  207. last_color = pal[x];
  208. } else {
  209. pal[x] = 0xff000000; // pad with black
  210. }
  211. }
  212. pal += pal_linesize;
  213. }
  214. if (s->reserve_transparent) {
  215. av_assert0(s->nb_boxes < 256);
  216. pal[out->width - pal_linesize - 1] = 0x0000ff00; // add a green transparent color
  217. }
  218. }
  219. /**
  220. * Crawl the histogram to get all the defined colors, and create a linear list
  221. * of them (each color reference entry is a pointer to the value in the
  222. * histogram/hash table).
  223. */
  224. static struct color_ref **load_color_refs(const struct hist_node *hist, int nb_refs)
  225. {
  226. int i, j, k = 0;
  227. struct color_ref **refs = av_malloc_array(nb_refs, sizeof(*refs));
  228. if (!refs)
  229. return NULL;
  230. for (j = 0; j < HIST_SIZE; j++) {
  231. const struct hist_node *node = &hist[j];
  232. for (i = 0; i < node->nb_entries; i++)
  233. refs[k++] = &node->entries[i];
  234. }
  235. return refs;
  236. }
  237. /**
  238. * Main function implementing the Median Cut Algorithm defined by Paul Heckbert
  239. * in Color Image Quantization for Frame Buffer Display (1982)
  240. */
  241. static AVFrame *get_palette_frame(AVFilterContext *ctx)
  242. {
  243. AVFrame *out;
  244. PaletteGenContext *s = ctx->priv;
  245. AVFilterLink *outlink = ctx->outputs[0];
  246. int box_id = 0;
  247. int longest = 0;
  248. struct range_box *box;
  249. /* reference only the used colors from histogram */
  250. s->refs = load_color_refs(s->histogram, s->nb_refs);
  251. if (!s->refs) {
  252. av_log(ctx, AV_LOG_ERROR, "Unable to allocate references for %d different colors\n", s->nb_refs);
  253. return NULL;
  254. }
  255. /* create the palette frame */
  256. out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
  257. if (!out)
  258. return NULL;
  259. out->pts = 0;
  260. /* set first box for 0..nb_refs */
  261. box = &s->boxes[box_id];
  262. box->len = s->nb_refs;
  263. box->sorted_by = -1;
  264. box->color = get_avg_color(s->refs, box);
  265. box->variance = -1;
  266. s->nb_boxes = 1;
  267. while (box && box->len > 1) {
  268. int i, rr, gr, br;
  269. uint64_t median, box_weight = 0;
  270. /* compute the box weight (sum all the weights of the colors in the
  271. * range) and its boundings */
  272. uint8_t min[3] = {0xff, 0xff, 0xff};
  273. uint8_t max[3] = {0x00, 0x00, 0x00};
  274. for (i = box->start; i < box->start + box->len; i++) {
  275. const struct color_ref *ref = s->refs[i];
  276. const uint32_t rgb = ref->color;
  277. const uint8_t r = rgb >> 16 & 0xff, g = rgb >> 8 & 0xff, b = rgb & 0xff;
  278. min[0] = FFMIN(r, min[0]), max[0] = FFMAX(r, max[0]);
  279. min[1] = FFMIN(g, min[1]), max[1] = FFMAX(g, max[1]);
  280. min[2] = FFMIN(b, min[2]), max[2] = FFMAX(b, max[2]);
  281. box_weight += ref->count;
  282. }
  283. /* define the axis to sort by according to the widest range of colors */
  284. rr = max[0] - min[0];
  285. gr = max[1] - min[1];
  286. br = max[2] - min[2];
  287. longest = 1; // pick green by default (the color the eye is the most sensitive to)
  288. if (br >= rr && br >= gr) longest = 2;
  289. if (rr >= gr && rr >= br) longest = 0;
  290. if (gr >= rr && gr >= br) longest = 1; // prefer green again
  291. av_dlog(ctx, "box #%02X [%6d..%-6d] (%6d) w:%-6"PRIu64" ranges:[%2x %2x %2x] sort by %c (already sorted:%c) ",
  292. box_id, box->start, box->start + box->len - 1, box->len, box_weight,
  293. rr, gr, br, "rgb"[longest], box->sorted_by == longest ? 'y':'n');
  294. /* sort the range by its longest axis if it's not already sorted */
  295. if (box->sorted_by != longest) {
  296. qsort(&s->refs[box->start], box->len, sizeof(*s->refs), cmp_funcs[longest]);
  297. box->sorted_by = longest;
  298. }
  299. /* locate the median where to split */
  300. median = (box_weight + 1) >> 1;
  301. box_weight = 0;
  302. /* if you have 2 boxes, the maximum is actually #0: you must have at
  303. * least 1 color on each side of the split, hence the -2 */
  304. for (i = box->start; i < box->start + box->len - 2; i++) {
  305. box_weight += s->refs[i]->count;
  306. if (box_weight > median)
  307. break;
  308. }
  309. av_dlog(ctx, "split @ i=%-6d with w=%-6"PRIu64" (target=%6"PRIu64")\n", i, box_weight, median);
  310. split_box(s, box, i);
  311. box_id = get_next_box_id_to_split(s);
  312. box = box_id >= 0 ? &s->boxes[box_id] : NULL;
  313. }
  314. av_log(ctx, AV_LOG_DEBUG, "%d%s boxes generated out of %d colors\n",
  315. s->nb_boxes, s->reserve_transparent ? "(+1)" : "", s->nb_refs);
  316. qsort(s->boxes, s->nb_boxes, sizeof(*s->boxes), cmp_color);
  317. write_palette(s, out);
  318. return out;
  319. }
  320. /**
  321. * Hashing function for the color.
  322. * It keeps the NBITS least significant bit of each component to make it
  323. * "random" even if the scene doesn't have much different colors.
  324. */
  325. static inline unsigned color_hash(uint32_t color)
  326. {
  327. const uint8_t r = color >> 16 & ((1<<NBITS)-1);
  328. const uint8_t g = color >> 8 & ((1<<NBITS)-1);
  329. const uint8_t b = color & ((1<<NBITS)-1);
  330. return r<<(NBITS*2) | g<<NBITS | b;
  331. }
  332. /**
  333. * Locate the color in the hash table and increment its counter.
  334. */
  335. static int color_inc(struct hist_node *hist, uint32_t color)
  336. {
  337. int i;
  338. const unsigned hash = color_hash(color);
  339. struct hist_node *node = &hist[hash];
  340. struct color_ref *e;
  341. for (i = 0; i < node->nb_entries; i++) {
  342. e = &node->entries[i];
  343. if (e->color == color) {
  344. e->count++;
  345. return 0;
  346. }
  347. }
  348. e = av_dynarray2_add((void**)&node->entries, &node->nb_entries,
  349. sizeof(*node->entries), NULL);
  350. if (!e)
  351. return AVERROR(ENOMEM);
  352. e->color = color;
  353. e->count = 1;
  354. return 1;
  355. }
  356. /**
  357. * Update histogram when pixels differ from previous frame.
  358. */
  359. static int update_histogram_diff(struct hist_node *hist,
  360. const AVFrame *f1, const AVFrame *f2)
  361. {
  362. int x, y, ret, nb_diff_colors = 0;
  363. for (y = 0; y < f1->height; y++) {
  364. const uint32_t *p = (const uint32_t *)(f1->data[0] + y*f1->linesize[0]);
  365. const uint32_t *q = (const uint32_t *)(f2->data[0] + y*f2->linesize[0]);
  366. for (x = 0; x < f2->width; x++) {
  367. if (p[x] == q[x])
  368. continue;
  369. ret = color_inc(hist, p[x]);
  370. if (ret < 0)
  371. return ret;
  372. nb_diff_colors += ret;
  373. }
  374. }
  375. return nb_diff_colors;
  376. }
  377. /**
  378. * Simple histogram of the frame.
  379. */
  380. static int update_histogram_frame(struct hist_node *hist, const AVFrame *f)
  381. {
  382. int x, y, ret, nb_diff_colors = 0;
  383. for (y = 0; y < f->height; y++) {
  384. const uint32_t *p = (const uint32_t *)(f->data[0] + y*f->linesize[0]);
  385. for (x = 0; x < f->width; x++) {
  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. * Update the histogram for each passing frame. No frame will be pushed here.
  396. */
  397. static int filter_frame(AVFilterLink *inlink, AVFrame *in)
  398. {
  399. AVFilterContext *ctx = inlink->dst;
  400. PaletteGenContext *s = ctx->priv;
  401. const int ret = s->prev_frame ? update_histogram_diff(s->histogram, s->prev_frame, in)
  402. : update_histogram_frame(s->histogram, in);
  403. if (ret > 0)
  404. s->nb_refs += ret;
  405. if (s->stats_mode == STATS_MODE_DIFF_FRAMES) {
  406. av_frame_free(&s->prev_frame);
  407. s->prev_frame = in;
  408. } else {
  409. av_frame_free(&in);
  410. }
  411. return ret;
  412. }
  413. /**
  414. * Returns only one frame at the end containing the full palette.
  415. */
  416. static int request_frame(AVFilterLink *outlink)
  417. {
  418. AVFilterContext *ctx = outlink->src;
  419. AVFilterLink *inlink = ctx->inputs[0];
  420. PaletteGenContext *s = ctx->priv;
  421. int r;
  422. r = ff_request_frame(inlink);
  423. if (r == AVERROR_EOF && !s->palette_pushed) {
  424. r = ff_filter_frame(outlink, get_palette_frame(ctx));
  425. s->palette_pushed = 1;
  426. return r;
  427. }
  428. return r;
  429. }
  430. /**
  431. * The output is one simple 16x16 squared-pixels palette.
  432. */
  433. static int config_output(AVFilterLink *outlink)
  434. {
  435. outlink->w = outlink->h = 16;
  436. outlink->sample_aspect_ratio = av_make_q(1, 1);
  437. outlink->flags |= FF_LINK_FLAG_REQUEST_LOOP;
  438. return 0;
  439. }
  440. static av_cold void uninit(AVFilterContext *ctx)
  441. {
  442. int i;
  443. PaletteGenContext *s = ctx->priv;
  444. for (i = 0; i < HIST_SIZE; i++)
  445. av_freep(&s->histogram[i].entries);
  446. av_freep(&s->refs);
  447. av_freep(&s->prev_frame);
  448. }
  449. static const AVFilterPad palettegen_inputs[] = {
  450. {
  451. .name = "default",
  452. .type = AVMEDIA_TYPE_VIDEO,
  453. .filter_frame = filter_frame,
  454. },
  455. { NULL }
  456. };
  457. static const AVFilterPad palettegen_outputs[] = {
  458. {
  459. .name = "default",
  460. .type = AVMEDIA_TYPE_VIDEO,
  461. .config_props = config_output,
  462. .request_frame = request_frame,
  463. },
  464. { NULL }
  465. };
  466. AVFilter ff_vf_palettegen = {
  467. .name = "palettegen",
  468. .description = NULL_IF_CONFIG_SMALL("Find the optimal palette for a given stream."),
  469. .priv_size = sizeof(PaletteGenContext),
  470. .uninit = uninit,
  471. .query_formats = query_formats,
  472. .inputs = palettegen_inputs,
  473. .outputs = palettegen_outputs,
  474. .priv_class = &palettegen_class,
  475. };