OSDN Git Service

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