2 * Copyright (c) 2015 Stupeflix
3 * Copyright (c) 2022 Clément Bœsch <u pkh me>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
24 * Generate one palette for a whole video stream.
27 #include "libavutil/avassert.h"
28 #include "libavutil/internal.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/intreadwrite.h"
37 /* Reference a color and how much it's used */
44 /* Store a range of colors */
46 uint32_t color; // average color
47 struct Lab avg; // average color in perceptual OkLab space
48 int major_axis; // best axis candidate for cutting the box
49 int64_t weight; // sum of all the weights of the colors
50 int64_t cut_score; // how likely the box is to be cut down (higher implying more likely)
51 int start; // index in PaletteGenContext->refs
52 int len; // number of referenced colors
53 int sorted_by; // whether range of colors is sorted by red (0), green (1) or blue (2)
57 struct color_ref *entries;
62 STATS_MODE_ALL_FRAMES,
63 STATS_MODE_DIFF_FRAMES,
64 STATS_MODE_SINGLE_FRAMES,
68 #define HIST_SIZE (1<<15)
70 typedef struct PaletteGenContext {
74 int reserve_transparent;
77 AVFrame *prev_frame; // previous frame used for the diff stats_mode
78 struct hist_node histogram[HIST_SIZE]; // histogram/hashtable of the colors
79 struct color_ref **refs; // references of all the colors used in the stream
80 int nb_refs; // number of color references (or number of different colors)
81 struct range_box boxes[256]; // define the segmentation of the colorspace (the final palette)
82 int nb_boxes; // number of boxes (increase will segmenting them)
83 int palette_pushed; // if the palette frame is pushed into the outlink or not
84 uint8_t transparency_color[4]; // background color for transparency
87 #define OFFSET(x) offsetof(PaletteGenContext, x)
88 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
89 static const AVOption palettegen_options[] = {
90 { "max_colors", "set the maximum number of colors to use in the palette", OFFSET(max_colors), AV_OPT_TYPE_INT, {.i64=256}, 2, 256, FLAGS },
91 { "reserve_transparent", "reserve a palette entry for transparency", OFFSET(reserve_transparent), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1, FLAGS },
92 { "transparency_color", "set a background color for transparency", OFFSET(transparency_color), AV_OPT_TYPE_COLOR, {.str="lime"}, 0, 0, FLAGS },
93 { "stats_mode", "set statistics mode", OFFSET(stats_mode), AV_OPT_TYPE_INT, {.i64=STATS_MODE_ALL_FRAMES}, 0, NB_STATS_MODE-1, FLAGS, "mode" },
94 { "full", "compute full frame histograms", 0, AV_OPT_TYPE_CONST, {.i64=STATS_MODE_ALL_FRAMES}, INT_MIN, INT_MAX, FLAGS, "mode" },
95 { "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" },
96 { "single", "compute new histogram for each frame", 0, AV_OPT_TYPE_CONST, {.i64=STATS_MODE_SINGLE_FRAMES}, INT_MIN, INT_MAX, FLAGS, "mode" },
100 AVFILTER_DEFINE_CLASS(palettegen);
102 static int query_formats(AVFilterContext *ctx)
104 static const enum AVPixelFormat in_fmts[] = {AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE};
105 static const enum AVPixelFormat out_fmts[] = {AV_PIX_FMT_RGB32, AV_PIX_FMT_NONE};
108 if ((ret = ff_formats_ref(ff_make_format_list(in_fmts) , &ctx->inputs[0]->outcfg.formats)) < 0)
110 if ((ret = ff_formats_ref(ff_make_format_list(out_fmts), &ctx->outputs[0]->incfg.formats)) < 0)
115 typedef int (*cmp_func)(const void *, const void *);
117 #define DECLARE_CMP_FUNC(k0, k1, k2) \
118 static int cmp_##k0##k1##k2(const void *pa, const void *pb) \
120 const struct color_ref * const *a = pa; \
121 const struct color_ref * const *b = pb; \
122 const int c0 = FFDIFFSIGN((*a)->lab.k0, (*b)->lab.k0); \
123 const int c1 = FFDIFFSIGN((*a)->lab.k1, (*b)->lab.k1); \
124 const int c2 = FFDIFFSIGN((*a)->lab.k2, (*b)->lab.k2); \
125 return c0 ? c0 : c1 ? c1 : c2; \
128 DECLARE_CMP_FUNC(L, a, b)
129 DECLARE_CMP_FUNC(L, b, a)
130 DECLARE_CMP_FUNC(a, L, b)
131 DECLARE_CMP_FUNC(a, b, L)
132 DECLARE_CMP_FUNC(b, L, a)
133 DECLARE_CMP_FUNC(b, a, L)
135 enum { ID_XYZ, ID_XZY, ID_ZXY, ID_YXZ, ID_ZYX, ID_YZX };
136 static const char * const sortstr[] = { "Lab", "Lba", "bLa", "aLb", "baL", "abL" };
138 static const cmp_func cmp_funcs[] = {
148 * Return an identifier for the order of x, y, z (from higher to lower),
149 * preferring x over y and y over z in case of equality.
151 static int sort3id(int64_t x, int64_t y, int64_t z)
154 if (y >= z) return ID_XYZ;
155 if (x >= z) return ID_XZY;
158 if (x >= z) return ID_YXZ;
159 if (y >= z) return ID_YZX;
164 * Simple color comparison for sorting the final palette
166 static int cmp_color(const void *a, const void *b)
168 const struct range_box *box1 = a;
169 const struct range_box *box2 = b;
170 return FFDIFFSIGN(box1->color, box2->color);
173 static void compute_box_stats(PaletteGenContext *s, struct range_box *box)
175 int64_t er2[3] = {0};
177 /* Compute average color */
178 int64_t sL = 0, sa = 0, sb = 0;
180 for (int i = box->start; i < box->start + box->len; i++) {
181 const struct color_ref *ref = s->refs[i];
182 sL += ref->lab.L * ref->count;
183 sa += ref->lab.a * ref->count;
184 sb += ref->lab.b * ref->count;
185 box->weight += ref->count;
187 box->avg.L = sL / box->weight;
188 box->avg.a = sa / box->weight;
189 box->avg.b = sb / box->weight;
191 /* Compute squared error of each color channel */
192 for (int i = box->start; i < box->start + box->len; i++) {
193 const struct color_ref *ref = s->refs[i];
194 const int64_t dL = ref->lab.L - box->avg.L;
195 const int64_t da = ref->lab.a - box->avg.a;
196 const int64_t db = ref->lab.b - box->avg.b;
197 er2[0] += dL * dL * ref->count;
198 er2[1] += da * da * ref->count;
199 er2[2] += db * db * ref->count;
202 /* Define the best axis candidate for cutting the box */
203 box->major_axis = sort3id(er2[0], er2[1], er2[2]);
205 /* The box that has the axis with the biggest error amongst all boxes will but cut down */
206 box->cut_score = FFMAX3(er2[0], er2[1], er2[2]);
210 * Find the next box to split: pick the one with the highest cut score
212 static int get_next_box_id_to_split(PaletteGenContext *s)
214 int best_box_id = -1;
215 int64_t max_score = -1;
217 if (s->nb_boxes == s->max_colors - s->reserve_transparent)
220 for (int box_id = 0; box_id < s->nb_boxes; box_id++) {
221 const struct range_box *box = &s->boxes[box_id];
222 if (s->boxes[box_id].len >= 2 && box->cut_score > max_score) {
223 best_box_id = box_id;
224 max_score = box->cut_score;
231 * Split given box in two at position n. The original box becomes the left part
232 * of the split, and the new index box is the right part.
234 static void split_box(PaletteGenContext *s, struct range_box *box, int n)
236 struct range_box *new_box = &s->boxes[s->nb_boxes++];
237 new_box->start = n + 1;
238 new_box->len = box->start + box->len - new_box->start;
239 new_box->sorted_by = box->sorted_by;
240 box->len -= new_box->len;
242 av_assert0(box->len >= 1);
243 av_assert0(new_box->len >= 1);
245 compute_box_stats(s, box);
246 compute_box_stats(s, new_box);
250 * Write the palette into the output frame.
252 static void write_palette(AVFilterContext *ctx, AVFrame *out)
254 const PaletteGenContext *s = ctx->priv;
256 uint32_t *pal = (uint32_t *)out->data[0];
257 const int pal_linesize = out->linesize[0] >> 2;
258 uint32_t last_color = 0;
260 for (int y = 0; y < out->height; y++) {
261 for (int x = 0; x < out->width; x++) {
262 if (box_id < s->nb_boxes) {
263 pal[x] = s->boxes[box_id++].color;
264 if ((x || y) && pal[x] == last_color)
265 av_log(ctx, AV_LOG_WARNING, "Duped color: %08"PRIX32"\n", pal[x]);
268 pal[x] = last_color; // pad with last color
274 if (s->reserve_transparent) {
275 av_assert0(s->nb_boxes < 256);
276 pal[out->width - pal_linesize - 1] = AV_RB32(&s->transparency_color) >> 8;
281 * Crawl the histogram to get all the defined colors, and create a linear list
282 * of them (each color reference entry is a pointer to the value in the
283 * histogram/hash table).
285 static struct color_ref **load_color_refs(const struct hist_node *hist, int nb_refs)
288 struct color_ref **refs = av_malloc_array(nb_refs, sizeof(*refs));
293 for (int j = 0; j < HIST_SIZE; j++) {
294 const struct hist_node *node = &hist[j];
296 for (int i = 0; i < node->nb_entries; i++)
297 refs[k++] = &node->entries[i];
303 static double set_colorquant_ratio_meta(AVFrame *out, int nb_out, int nb_in)
306 const double ratio = (double)nb_out / nb_in;
307 snprintf(buf, sizeof(buf), "%f", ratio);
308 av_dict_set(&out->metadata, "lavfi.color_quant_ratio", buf, 0);
313 * Main function implementing the Median Cut Algorithm defined by Paul Heckbert
314 * in Color Image Quantization for Frame Buffer Display (1982)
316 static AVFrame *get_palette_frame(AVFilterContext *ctx)
319 PaletteGenContext *s = ctx->priv;
320 AVFilterLink *outlink = ctx->outputs[0];
323 struct range_box *box;
325 /* reference only the used colors from histogram */
326 s->refs = load_color_refs(s->histogram, s->nb_refs);
328 av_log(ctx, AV_LOG_ERROR, "Unable to allocate references for %d different colors\n", s->nb_refs);
332 /* create the palette frame */
333 out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
338 /* set first box for 0..nb_refs */
339 box = &s->boxes[box_id];
340 box->len = s->nb_refs;
342 compute_box_stats(s, box);
345 while (box && box->len > 1) {
347 int64_t median, weight;
349 ff_dlog(ctx, "box #%02X [%6d..%-6d] (%6d) w:%-6"PRIu64" sort by %s (already sorted:%c) ",
350 box_id, box->start, box->start + box->len - 1, box->len, box->weight,
351 sortstr[box->major_axis], box->sorted_by == box->major_axis ? 'y':'n');
353 /* sort the range by its major axis if it's not already sorted */
354 if (box->sorted_by != box->major_axis) {
355 cmp_func cmpf = cmp_funcs[box->major_axis];
356 qsort(&s->refs[box->start], box->len, sizeof(struct color_ref *), cmpf);
357 box->sorted_by = box->major_axis;
360 /* locate the median where to split */
361 median = (box->weight + 1) >> 1;
363 /* if you have 2 boxes, the maximum is actually #0: you must have at
364 * least 1 color on each side of the split, hence the -2 */
365 for (i = box->start; i < box->start + box->len - 2; i++) {
366 weight += s->refs[i]->count;
370 ff_dlog(ctx, "split @ i=%-6d with w=%-6"PRIu64" (target=%6"PRIu64")\n", i, weight, median);
371 split_box(s, box, i);
373 box_id = get_next_box_id_to_split(s);
374 box = box_id >= 0 ? &s->boxes[box_id] : NULL;
377 ratio = set_colorquant_ratio_meta(out, s->nb_boxes, s->nb_refs);
378 av_log(ctx, AV_LOG_INFO, "%d%s colors generated out of %d colors; ratio=%f\n",
379 s->nb_boxes, s->reserve_transparent ? "(+1)" : "", s->nb_refs, ratio);
381 for (int i = 0; i < s->nb_boxes; i++)
382 s->boxes[i].color = 0xffU<<24 | ff_oklab_int_to_srgb_u8(s->boxes[i].avg);
384 qsort(s->boxes, s->nb_boxes, sizeof(*s->boxes), cmp_color);
386 write_palette(ctx, out);
392 * Locate the color in the hash table and increment its counter.
394 static int color_inc(struct hist_node *hist, uint32_t color)
396 const uint32_t hash = ff_lowbias32(color) & (HIST_SIZE - 1);
397 struct hist_node *node = &hist[hash];
400 for (int i = 0; i < node->nb_entries; i++) {
401 e = &node->entries[i];
402 if (e->color == color) {
408 e = av_dynarray2_add((void**)&node->entries, &node->nb_entries,
409 sizeof(*node->entries), NULL);
411 return AVERROR(ENOMEM);
413 e->lab = ff_srgb_u8_to_oklab_int(color);
419 * Update histogram when pixels differ from previous frame.
421 static int update_histogram_diff(struct hist_node *hist,
422 const AVFrame *f1, const AVFrame *f2)
424 int x, y, ret, nb_diff_colors = 0;
426 for (y = 0; y < f1->height; y++) {
427 const uint32_t *p = (const uint32_t *)(f1->data[0] + y*f1->linesize[0]);
428 const uint32_t *q = (const uint32_t *)(f2->data[0] + y*f2->linesize[0]);
430 for (x = 0; x < f1->width; x++) {
433 ret = color_inc(hist, p[x]);
436 nb_diff_colors += ret;
439 return nb_diff_colors;
443 * Simple histogram of the frame.
445 static int update_histogram_frame(struct hist_node *hist, const AVFrame *f)
447 int x, y, ret, nb_diff_colors = 0;
449 for (y = 0; y < f->height; y++) {
450 const uint32_t *p = (const uint32_t *)(f->data[0] + y*f->linesize[0]);
452 for (x = 0; x < f->width; x++) {
453 ret = color_inc(hist, p[x]);
456 nb_diff_colors += ret;
459 return nb_diff_colors;
463 * Update the histogram for each passing frame. No frame will be pushed here.
465 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
467 AVFilterContext *ctx = inlink->dst;
468 PaletteGenContext *s = ctx->priv;
471 if (in->color_trc != AVCOL_TRC_UNSPECIFIED && in->color_trc != AVCOL_TRC_IEC61966_2_1)
472 av_log(ctx, AV_LOG_WARNING, "The input frame is not in sRGB, colors may be off\n");
474 ret = s->prev_frame ? update_histogram_diff(s->histogram, s->prev_frame, in)
475 : update_histogram_frame(s->histogram, in);
479 if (s->stats_mode == STATS_MODE_DIFF_FRAMES) {
480 av_frame_free(&s->prev_frame);
482 } else if (s->stats_mode == STATS_MODE_SINGLE_FRAMES && s->nb_refs > 0) {
486 out = get_palette_frame(ctx);
489 ret = ff_filter_frame(ctx->outputs[0], out);
490 for (i = 0; i < HIST_SIZE; i++)
491 av_freep(&s->histogram[i].entries);
495 memset(s->boxes, 0, sizeof(s->boxes));
496 memset(s->histogram, 0, sizeof(s->histogram));
505 * Returns only one frame at the end containing the full palette.
507 static int request_frame(AVFilterLink *outlink)
509 AVFilterContext *ctx = outlink->src;
510 AVFilterLink *inlink = ctx->inputs[0];
511 PaletteGenContext *s = ctx->priv;
514 r = ff_request_frame(inlink);
515 if (r == AVERROR_EOF && !s->palette_pushed && s->nb_refs && s->stats_mode != STATS_MODE_SINGLE_FRAMES) {
516 r = ff_filter_frame(outlink, get_palette_frame(ctx));
517 s->palette_pushed = 1;
524 * The output is one simple 16x16 squared-pixels palette.
526 static int config_output(AVFilterLink *outlink)
528 outlink->w = outlink->h = 16;
529 outlink->sample_aspect_ratio = av_make_q(1, 1);
533 static int init(AVFilterContext *ctx)
535 PaletteGenContext* s = ctx->priv;
537 if (s->max_colors - s->reserve_transparent < 2) {
538 av_log(ctx, AV_LOG_ERROR, "max_colors=2 is only allowed without reserving a transparent color slot\n");
539 return AVERROR(EINVAL);
545 static av_cold void uninit(AVFilterContext *ctx)
548 PaletteGenContext *s = ctx->priv;
550 for (i = 0; i < HIST_SIZE; i++)
551 av_freep(&s->histogram[i].entries);
553 av_frame_free(&s->prev_frame);
556 static const AVFilterPad palettegen_inputs[] = {
559 .type = AVMEDIA_TYPE_VIDEO,
560 .filter_frame = filter_frame,
564 static const AVFilterPad palettegen_outputs[] = {
567 .type = AVMEDIA_TYPE_VIDEO,
568 .config_props = config_output,
569 .request_frame = request_frame,
573 const AVFilter ff_vf_palettegen = {
574 .name = "palettegen",
575 .description = NULL_IF_CONFIG_SMALL("Find the optimal palette for a given stream."),
576 .priv_size = sizeof(PaletteGenContext),
579 FILTER_INPUTS(palettegen_inputs),
580 FILTER_OUTPUTS(palettegen_outputs),
581 FILTER_QUERY_FUNC(query_formats),
582 .priv_class = &palettegen_class,