xref: /aosp_15_r20/external/webp/src/utils/palette.c (revision b2055c353e87c8814eb2b6b1b11112a1562253bd)
1 // Copyright 2023 Google Inc. All Rights Reserved.
2 //
3 // Use of this source code is governed by a BSD-style license
4 // that can be found in the COPYING file in the root of the source
5 // tree. An additional intellectual property rights grant can be found
6 // in the file PATENTS. All contributing project authors may
7 // be found in the AUTHORS file in the root of the source tree.
8 // -----------------------------------------------------------------------------
9 //
10 // Utilities for palette analysis.
11 //
12 // Author: Vincent Rabaud ([email protected])
13 
14 #include "src/utils/palette.h"
15 
16 #include <assert.h>
17 #include <stdlib.h>
18 
19 #include "src/dsp/lossless_common.h"
20 #include "src/utils/color_cache_utils.h"
21 #include "src/utils/utils.h"
22 #include "src/webp/encode.h"
23 #include "src/webp/format_constants.h"
24 
25 // -----------------------------------------------------------------------------
26 
27 // Palette reordering for smaller sum of deltas (and for smaller storage).
28 
PaletteCompareColorsForQsort(const void * p1,const void * p2)29 static int PaletteCompareColorsForQsort(const void* p1, const void* p2) {
30   const uint32_t a = WebPMemToUint32((uint8_t*)p1);
31   const uint32_t b = WebPMemToUint32((uint8_t*)p2);
32   assert(a != b);
33   return (a < b) ? -1 : 1;
34 }
35 
PaletteComponentDistance(uint32_t v)36 static WEBP_INLINE uint32_t PaletteComponentDistance(uint32_t v) {
37   return (v <= 128) ? v : (256 - v);
38 }
39 
40 // Computes a value that is related to the entropy created by the
41 // palette entry diff.
42 //
43 // Note that the last & 0xff is a no-operation in the next statement, but
44 // removed by most compilers and is here only for regularity of the code.
PaletteColorDistance(uint32_t col1,uint32_t col2)45 static WEBP_INLINE uint32_t PaletteColorDistance(uint32_t col1, uint32_t col2) {
46   const uint32_t diff = VP8LSubPixels(col1, col2);
47   const int kMoreWeightForRGBThanForAlpha = 9;
48   uint32_t score;
49   score = PaletteComponentDistance((diff >> 0) & 0xff);
50   score += PaletteComponentDistance((diff >> 8) & 0xff);
51   score += PaletteComponentDistance((diff >> 16) & 0xff);
52   score *= kMoreWeightForRGBThanForAlpha;
53   score += PaletteComponentDistance((diff >> 24) & 0xff);
54   return score;
55 }
56 
SwapColor(uint32_t * const col1,uint32_t * const col2)57 static WEBP_INLINE void SwapColor(uint32_t* const col1, uint32_t* const col2) {
58   const uint32_t tmp = *col1;
59   *col1 = *col2;
60   *col2 = tmp;
61 }
62 
SearchColorNoIdx(const uint32_t sorted[],uint32_t color,int num_colors)63 int SearchColorNoIdx(const uint32_t sorted[], uint32_t color, int num_colors) {
64   int low = 0, hi = num_colors;
65   if (sorted[low] == color) return low;  // loop invariant: sorted[low] != color
66   while (1) {
67     const int mid = (low + hi) >> 1;
68     if (sorted[mid] == color) {
69       return mid;
70     } else if (sorted[mid] < color) {
71       low = mid;
72     } else {
73       hi = mid;
74     }
75   }
76   assert(0);
77   return 0;
78 }
79 
PrepareMapToPalette(const uint32_t palette[],uint32_t num_colors,uint32_t sorted[],uint32_t idx_map[])80 void PrepareMapToPalette(const uint32_t palette[], uint32_t num_colors,
81                          uint32_t sorted[], uint32_t idx_map[]) {
82   uint32_t i;
83   memcpy(sorted, palette, num_colors * sizeof(*sorted));
84   qsort(sorted, num_colors, sizeof(*sorted), PaletteCompareColorsForQsort);
85   for (i = 0; i < num_colors; ++i) {
86     idx_map[SearchColorNoIdx(sorted, palette[i], num_colors)] = i;
87   }
88 }
89 
90 //------------------------------------------------------------------------------
91 
92 #define COLOR_HASH_SIZE (MAX_PALETTE_SIZE * 4)
93 #define COLOR_HASH_RIGHT_SHIFT 22  // 32 - log2(COLOR_HASH_SIZE).
94 
GetColorPalette(const WebPPicture * const pic,uint32_t * const palette)95 int GetColorPalette(const WebPPicture* const pic, uint32_t* const palette) {
96   int i;
97   int x, y;
98   int num_colors = 0;
99   uint8_t in_use[COLOR_HASH_SIZE] = {0};
100   uint32_t colors[COLOR_HASH_SIZE] = {0};
101   const uint32_t* argb = pic->argb;
102   const int width = pic->width;
103   const int height = pic->height;
104   uint32_t last_pix = ~argb[0];  // so we're sure that last_pix != argb[0]
105   assert(pic != NULL);
106   assert(pic->use_argb);
107 
108   for (y = 0; y < height; ++y) {
109     for (x = 0; x < width; ++x) {
110       int key;
111       if (argb[x] == last_pix) {
112         continue;
113       }
114       last_pix = argb[x];
115       key = VP8LHashPix(last_pix, COLOR_HASH_RIGHT_SHIFT);
116       while (1) {
117         if (!in_use[key]) {
118           colors[key] = last_pix;
119           in_use[key] = 1;
120           ++num_colors;
121           if (num_colors > MAX_PALETTE_SIZE) {
122             return MAX_PALETTE_SIZE + 1;  // Exact count not needed.
123           }
124           break;
125         } else if (colors[key] == last_pix) {
126           break;  // The color is already there.
127         } else {
128           // Some other color sits here, so do linear conflict resolution.
129           ++key;
130           key &= (COLOR_HASH_SIZE - 1);  // Key mask.
131         }
132       }
133     }
134     argb += pic->argb_stride;
135   }
136 
137   if (palette != NULL) {  // Fill the colors into palette.
138     num_colors = 0;
139     for (i = 0; i < COLOR_HASH_SIZE; ++i) {
140       if (in_use[i]) {
141         palette[num_colors] = colors[i];
142         ++num_colors;
143       }
144     }
145     qsort(palette, num_colors, sizeof(*palette), PaletteCompareColorsForQsort);
146   }
147   return num_colors;
148 }
149 
150 #undef COLOR_HASH_SIZE
151 #undef COLOR_HASH_RIGHT_SHIFT
152 
153 // -----------------------------------------------------------------------------
154 
155 // The palette has been sorted by alpha. This function checks if the other
156 // components of the palette have a monotonic development with regards to
157 // position in the palette. If all have monotonic development, there is
158 // no benefit to re-organize them greedily. A monotonic development
159 // would be spotted in green-only situations (like lossy alpha) or gray-scale
160 // images.
PaletteHasNonMonotonousDeltas(const uint32_t * const palette,int num_colors)161 static int PaletteHasNonMonotonousDeltas(const uint32_t* const palette,
162                                          int num_colors) {
163   uint32_t predict = 0x000000;
164   int i;
165   uint8_t sign_found = 0x00;
166   for (i = 0; i < num_colors; ++i) {
167     const uint32_t diff = VP8LSubPixels(palette[i], predict);
168     const uint8_t rd = (diff >> 16) & 0xff;
169     const uint8_t gd = (diff >> 8) & 0xff;
170     const uint8_t bd = (diff >> 0) & 0xff;
171     if (rd != 0x00) {
172       sign_found |= (rd < 0x80) ? 1 : 2;
173     }
174     if (gd != 0x00) {
175       sign_found |= (gd < 0x80) ? 8 : 16;
176     }
177     if (bd != 0x00) {
178       sign_found |= (bd < 0x80) ? 64 : 128;
179     }
180     predict = palette[i];
181   }
182   return (sign_found & (sign_found << 1)) != 0;  // two consequent signs.
183 }
184 
PaletteSortMinimizeDeltas(const uint32_t * const palette_sorted,int num_colors,uint32_t * const palette)185 static void PaletteSortMinimizeDeltas(const uint32_t* const palette_sorted,
186                                       int num_colors, uint32_t* const palette) {
187   uint32_t predict = 0x00000000;
188   int i, k;
189   memcpy(palette, palette_sorted, num_colors * sizeof(*palette));
190   if (!PaletteHasNonMonotonousDeltas(palette_sorted, num_colors)) return;
191   // Find greedily always the closest color of the predicted color to minimize
192   // deltas in the palette. This reduces storage needs since the
193   // palette is stored with delta encoding.
194   for (i = 0; i < num_colors; ++i) {
195     int best_ix = i;
196     uint32_t best_score = ~0U;
197     for (k = i; k < num_colors; ++k) {
198       const uint32_t cur_score = PaletteColorDistance(palette[k], predict);
199       if (best_score > cur_score) {
200         best_score = cur_score;
201         best_ix = k;
202       }
203     }
204     SwapColor(&palette[best_ix], &palette[i]);
205     predict = palette[i];
206   }
207 }
208 
209 // -----------------------------------------------------------------------------
210 // Modified Zeng method from "A Survey on Palette Reordering
211 // Methods for Improving the Compression of Color-Indexed Images" by Armando J.
212 // Pinho and Antonio J. R. Neves.
213 
214 // Finds the biggest cooccurrence in the matrix.
CoOccurrenceFindMax(const uint32_t * const cooccurrence,uint32_t num_colors,uint8_t * const c1,uint8_t * const c2)215 static void CoOccurrenceFindMax(const uint32_t* const cooccurrence,
216                                 uint32_t num_colors, uint8_t* const c1,
217                                 uint8_t* const c2) {
218   // Find the index that is most frequently located adjacent to other
219   // (different) indexes.
220   uint32_t best_sum = 0u;
221   uint32_t i, j, best_cooccurrence;
222   *c1 = 0u;
223   for (i = 0; i < num_colors; ++i) {
224     uint32_t sum = 0;
225     for (j = 0; j < num_colors; ++j) sum += cooccurrence[i * num_colors + j];
226     if (sum > best_sum) {
227       best_sum = sum;
228       *c1 = i;
229     }
230   }
231   // Find the index that is most frequently found adjacent to *c1.
232   *c2 = 0u;
233   best_cooccurrence = 0u;
234   for (i = 0; i < num_colors; ++i) {
235     if (cooccurrence[*c1 * num_colors + i] > best_cooccurrence) {
236       best_cooccurrence = cooccurrence[*c1 * num_colors + i];
237       *c2 = i;
238     }
239   }
240   assert(*c1 != *c2);
241 }
242 
243 // Builds the cooccurrence matrix
CoOccurrenceBuild(const WebPPicture * const pic,const uint32_t * const palette,uint32_t num_colors,uint32_t * cooccurrence)244 static int CoOccurrenceBuild(const WebPPicture* const pic,
245                              const uint32_t* const palette, uint32_t num_colors,
246                              uint32_t* cooccurrence) {
247   uint32_t *lines, *line_top, *line_current, *line_tmp;
248   int x, y;
249   const uint32_t* src = pic->argb;
250   uint32_t prev_pix = ~src[0];
251   uint32_t prev_idx = 0u;
252   uint32_t idx_map[MAX_PALETTE_SIZE] = {0};
253   uint32_t palette_sorted[MAX_PALETTE_SIZE];
254   lines = (uint32_t*)WebPSafeMalloc(2 * pic->width, sizeof(*lines));
255   if (lines == NULL) {
256     return 0;
257   }
258   line_top = &lines[0];
259   line_current = &lines[pic->width];
260   PrepareMapToPalette(palette, num_colors, palette_sorted, idx_map);
261   for (y = 0; y < pic->height; ++y) {
262     for (x = 0; x < pic->width; ++x) {
263       const uint32_t pix = src[x];
264       if (pix != prev_pix) {
265         prev_idx = idx_map[SearchColorNoIdx(palette_sorted, pix, num_colors)];
266         prev_pix = pix;
267       }
268       line_current[x] = prev_idx;
269       // 4-connectivity is what works best as mentioned in "On the relation
270       // between Memon's and the modified Zeng's palette reordering methods".
271       if (x > 0 && prev_idx != line_current[x - 1]) {
272         const uint32_t left_idx = line_current[x - 1];
273         ++cooccurrence[prev_idx * num_colors + left_idx];
274         ++cooccurrence[left_idx * num_colors + prev_idx];
275       }
276       if (y > 0 && prev_idx != line_top[x]) {
277         const uint32_t top_idx = line_top[x];
278         ++cooccurrence[prev_idx * num_colors + top_idx];
279         ++cooccurrence[top_idx * num_colors + prev_idx];
280       }
281     }
282     line_tmp = line_top;
283     line_top = line_current;
284     line_current = line_tmp;
285     src += pic->argb_stride;
286   }
287   WebPSafeFree(lines);
288   return 1;
289 }
290 
291 struct Sum {
292   uint8_t index;
293   uint32_t sum;
294 };
295 
PaletteSortModifiedZeng(const WebPPicture * const pic,const uint32_t * const palette_in,uint32_t num_colors,uint32_t * const palette)296 static int PaletteSortModifiedZeng(const WebPPicture* const pic,
297                                    const uint32_t* const palette_in,
298                                    uint32_t num_colors,
299                                    uint32_t* const palette) {
300   uint32_t i, j, ind;
301   uint8_t remapping[MAX_PALETTE_SIZE];
302   uint32_t* cooccurrence;
303   struct Sum sums[MAX_PALETTE_SIZE];
304   uint32_t first, last;
305   uint32_t num_sums;
306   // TODO(vrabaud) check whether one color images should use palette or not.
307   if (num_colors <= 1) return 1;
308   // Build the co-occurrence matrix.
309   cooccurrence =
310       (uint32_t*)WebPSafeCalloc(num_colors * num_colors, sizeof(*cooccurrence));
311   if (cooccurrence == NULL) {
312     return 0;
313   }
314   if (!CoOccurrenceBuild(pic, palette_in, num_colors, cooccurrence)) {
315     WebPSafeFree(cooccurrence);
316     return 0;
317   }
318 
319   // Initialize the mapping list with the two best indices.
320   CoOccurrenceFindMax(cooccurrence, num_colors, &remapping[0], &remapping[1]);
321 
322   // We need to append and prepend to the list of remapping. To this end, we
323   // actually define the next start/end of the list as indices in a vector (with
324   // a wrap around when the end is reached).
325   first = 0;
326   last = 1;
327   num_sums = num_colors - 2;  // -2 because we know the first two values
328   if (num_sums > 0) {
329     // Initialize the sums with the first two remappings and find the best one
330     struct Sum* best_sum = &sums[0];
331     best_sum->index = 0u;
332     best_sum->sum = 0u;
333     for (i = 0, j = 0; i < num_colors; ++i) {
334       if (i == remapping[0] || i == remapping[1]) continue;
335       sums[j].index = i;
336       sums[j].sum = cooccurrence[i * num_colors + remapping[0]] +
337                     cooccurrence[i * num_colors + remapping[1]];
338       if (sums[j].sum > best_sum->sum) best_sum = &sums[j];
339       ++j;
340     }
341 
342     while (num_sums > 0) {
343       const uint8_t best_index = best_sum->index;
344       // Compute delta to know if we need to prepend or append the best index.
345       int32_t delta = 0;
346       const int32_t n = num_colors - num_sums;
347       for (ind = first, j = 0; (ind + j) % num_colors != last + 1; ++j) {
348         const uint16_t l_j = remapping[(ind + j) % num_colors];
349         delta += (n - 1 - 2 * (int32_t)j) *
350                  (int32_t)cooccurrence[best_index * num_colors + l_j];
351       }
352       if (delta > 0) {
353         first = (first == 0) ? num_colors - 1 : first - 1;
354         remapping[first] = best_index;
355       } else {
356         ++last;
357         remapping[last] = best_index;
358       }
359       // Remove best_sum from sums.
360       *best_sum = sums[num_sums - 1];
361       --num_sums;
362       // Update all the sums and find the best one.
363       best_sum = &sums[0];
364       for (i = 0; i < num_sums; ++i) {
365         sums[i].sum += cooccurrence[best_index * num_colors + sums[i].index];
366         if (sums[i].sum > best_sum->sum) best_sum = &sums[i];
367       }
368     }
369   }
370   assert((last + 1) % num_colors == first);
371   WebPSafeFree(cooccurrence);
372 
373   // Re-map the palette.
374   for (i = 0; i < num_colors; ++i) {
375     palette[i] = palette_in[remapping[(first + i) % num_colors]];
376   }
377   return 1;
378 }
379 
380 // -----------------------------------------------------------------------------
381 
PaletteSort(PaletteSorting method,const struct WebPPicture * const pic,const uint32_t * const palette_sorted,uint32_t num_colors,uint32_t * const palette)382 int PaletteSort(PaletteSorting method, const struct WebPPicture* const pic,
383                 const uint32_t* const palette_sorted, uint32_t num_colors,
384                 uint32_t* const palette) {
385   switch (method) {
386     case kSortedDefault:
387       // Nothing to do, we have already sorted the palette.
388       memcpy(palette, palette_sorted, num_colors * sizeof(*palette));
389       return 1;
390     case kMinimizeDelta:
391       PaletteSortMinimizeDeltas(palette_sorted, num_colors, palette);
392       return 1;
393     case kModifiedZeng:
394       return PaletteSortModifiedZeng(pic, palette_sorted, num_colors, palette);
395     case kUnusedPalette:
396     case kPaletteSortingNum:
397       break;
398   }
399 
400   assert(0);
401   return 0;
402 }
403