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