LCOV - code coverage report
Current view: top level - libavfilter - vf_palettegen.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 221 242 91.3 %
Date: 2017-12-11 04:34:20 Functions: 21 21 100.0 %

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

Generated by: LCOV version 1.13