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.

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