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.

551 lines
17KB

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