1 // Copyright 2012 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 // Author: Jyrki Alakuijala (jyrki@google.com)
11 //
12 #ifdef HAVE_CONFIG_H
13 #include "src/webp/config.h"
14 #endif
15 
16 #include <math.h>
17 
18 #include "src/enc/backward_references_enc.h"
19 #include "src/enc/histogram_enc.h"
20 #include "src/dsp/lossless.h"
21 #include "src/dsp/lossless_common.h"
22 #include "src/utils/utils.h"
23 
24 #define MAX_COST 1.e38
25 
26 // Number of partitions for the three dominant (literal, red and blue) symbol
27 // costs.
28 #define NUM_PARTITIONS 4
29 // The size of the bin-hash corresponding to the three dominant costs.
30 #define BIN_SIZE (NUM_PARTITIONS * NUM_PARTITIONS * NUM_PARTITIONS)
31 // Maximum number of histograms allowed in greedy combining algorithm.
32 #define MAX_HISTO_GREEDY 100
33 
HistogramClear(VP8LHistogram * const p)34 static void HistogramClear(VP8LHistogram* const p) {
35   uint32_t* const literal = p->literal_;
36   const int cache_bits = p->palette_code_bits_;
37   const int histo_size = VP8LGetHistogramSize(cache_bits);
38   memset(p, 0, histo_size);
39   p->palette_code_bits_ = cache_bits;
40   p->literal_ = literal;
41 }
42 
43 // Swap two histogram pointers.
HistogramSwap(VP8LHistogram ** const A,VP8LHistogram ** const B)44 static void HistogramSwap(VP8LHistogram** const A, VP8LHistogram** const B) {
45   VP8LHistogram* const tmp = *A;
46   *A = *B;
47   *B = tmp;
48 }
49 
HistogramCopy(const VP8LHistogram * const src,VP8LHistogram * const dst)50 static void HistogramCopy(const VP8LHistogram* const src,
51                           VP8LHistogram* const dst) {
52   uint32_t* const dst_literal = dst->literal_;
53   const int dst_cache_bits = dst->palette_code_bits_;
54   const int literal_size = VP8LHistogramNumCodes(dst_cache_bits);
55   const int histo_size = VP8LGetHistogramSize(dst_cache_bits);
56   assert(src->palette_code_bits_ == dst_cache_bits);
57   memcpy(dst, src, histo_size);
58   dst->literal_ = dst_literal;
59   memcpy(dst->literal_, src->literal_, literal_size * sizeof(*dst->literal_));
60 }
61 
VP8LGetHistogramSize(int cache_bits)62 int VP8LGetHistogramSize(int cache_bits) {
63   const int literal_size = VP8LHistogramNumCodes(cache_bits);
64   const size_t total_size = sizeof(VP8LHistogram) + sizeof(int) * literal_size;
65   assert(total_size <= (size_t)0x7fffffff);
66   return (int)total_size;
67 }
68 
VP8LFreeHistogram(VP8LHistogram * const histo)69 void VP8LFreeHistogram(VP8LHistogram* const histo) {
70   WebPSafeFree(histo);
71 }
72 
VP8LFreeHistogramSet(VP8LHistogramSet * const histo)73 void VP8LFreeHistogramSet(VP8LHistogramSet* const histo) {
74   WebPSafeFree(histo);
75 }
76 
VP8LHistogramStoreRefs(const VP8LBackwardRefs * const refs,VP8LHistogram * const histo)77 void VP8LHistogramStoreRefs(const VP8LBackwardRefs* const refs,
78                             VP8LHistogram* const histo) {
79   VP8LRefsCursor c = VP8LRefsCursorInit(refs);
80   while (VP8LRefsCursorOk(&c)) {
81     VP8LHistogramAddSinglePixOrCopy(histo, c.cur_pos, NULL, 0);
82     VP8LRefsCursorNext(&c);
83   }
84 }
85 
VP8LHistogramCreate(VP8LHistogram * const p,const VP8LBackwardRefs * const refs,int palette_code_bits)86 void VP8LHistogramCreate(VP8LHistogram* const p,
87                          const VP8LBackwardRefs* const refs,
88                          int palette_code_bits) {
89   if (palette_code_bits >= 0) {
90     p->palette_code_bits_ = palette_code_bits;
91   }
92   HistogramClear(p);
93   VP8LHistogramStoreRefs(refs, p);
94 }
95 
VP8LHistogramInit(VP8LHistogram * const p,int palette_code_bits,int init_arrays)96 void VP8LHistogramInit(VP8LHistogram* const p, int palette_code_bits,
97                        int init_arrays) {
98   p->palette_code_bits_ = palette_code_bits;
99   if (init_arrays) {
100     HistogramClear(p);
101   } else {
102     p->trivial_symbol_ = 0;
103     p->bit_cost_ = 0.;
104     p->literal_cost_ = 0.;
105     p->red_cost_ = 0.;
106     p->blue_cost_ = 0.;
107     memset(p->is_used_, 0, sizeof(p->is_used_));
108   }
109 }
110 
VP8LAllocateHistogram(int cache_bits)111 VP8LHistogram* VP8LAllocateHistogram(int cache_bits) {
112   VP8LHistogram* histo = NULL;
113   const int total_size = VP8LGetHistogramSize(cache_bits);
114   uint8_t* const memory = (uint8_t*)WebPSafeMalloc(total_size, sizeof(*memory));
115   if (memory == NULL) return NULL;
116   histo = (VP8LHistogram*)memory;
117   // literal_ won't necessary be aligned.
118   histo->literal_ = (uint32_t*)(memory + sizeof(VP8LHistogram));
119   VP8LHistogramInit(histo, cache_bits, /*init_arrays=*/ 0);
120   return histo;
121 }
122 
123 // Resets the pointers of the histograms to point to the bit buffer in the set.
HistogramSetResetPointers(VP8LHistogramSet * const set,int cache_bits)124 static void HistogramSetResetPointers(VP8LHistogramSet* const set,
125                                       int cache_bits) {
126   int i;
127   const int histo_size = VP8LGetHistogramSize(cache_bits);
128   uint8_t* memory = (uint8_t*) (set->histograms);
129   memory += set->max_size * sizeof(*set->histograms);
130   for (i = 0; i < set->max_size; ++i) {
131     memory = (uint8_t*) WEBP_ALIGN(memory);
132     set->histograms[i] = (VP8LHistogram*) memory;
133     // literal_ won't necessary be aligned.
134     set->histograms[i]->literal_ = (uint32_t*)(memory + sizeof(VP8LHistogram));
135     memory += histo_size;
136   }
137 }
138 
139 // Returns the total size of the VP8LHistogramSet.
HistogramSetTotalSize(int size,int cache_bits)140 static size_t HistogramSetTotalSize(int size, int cache_bits) {
141   const int histo_size = VP8LGetHistogramSize(cache_bits);
142   return (sizeof(VP8LHistogramSet) + size * (sizeof(VP8LHistogram*) +
143           histo_size + WEBP_ALIGN_CST));
144 }
145 
VP8LAllocateHistogramSet(int size,int cache_bits)146 VP8LHistogramSet* VP8LAllocateHistogramSet(int size, int cache_bits) {
147   int i;
148   VP8LHistogramSet* set;
149   const size_t total_size = HistogramSetTotalSize(size, cache_bits);
150   uint8_t* memory = (uint8_t*)WebPSafeMalloc(total_size, sizeof(*memory));
151   if (memory == NULL) return NULL;
152 
153   set = (VP8LHistogramSet*)memory;
154   memory += sizeof(*set);
155   set->histograms = (VP8LHistogram**)memory;
156   set->max_size = size;
157   set->size = size;
158   HistogramSetResetPointers(set, cache_bits);
159   for (i = 0; i < size; ++i) {
160     VP8LHistogramInit(set->histograms[i], cache_bits, /*init_arrays=*/ 0);
161   }
162   return set;
163 }
164 
VP8LHistogramSetClear(VP8LHistogramSet * const set)165 void VP8LHistogramSetClear(VP8LHistogramSet* const set) {
166   int i;
167   const int cache_bits = set->histograms[0]->palette_code_bits_;
168   const int size = set->max_size;
169   const size_t total_size = HistogramSetTotalSize(size, cache_bits);
170   uint8_t* memory = (uint8_t*)set;
171 
172   memset(memory, 0, total_size);
173   memory += sizeof(*set);
174   set->histograms = (VP8LHistogram**)memory;
175   set->max_size = size;
176   set->size = size;
177   HistogramSetResetPointers(set, cache_bits);
178   for (i = 0; i < size; ++i) {
179     set->histograms[i]->palette_code_bits_ = cache_bits;
180   }
181 }
182 
183 // Removes the histogram 'i' from 'set' by setting it to NULL.
HistogramSetRemoveHistogram(VP8LHistogramSet * const set,int i,int * const num_used)184 static void HistogramSetRemoveHistogram(VP8LHistogramSet* const set, int i,
185                                         int* const num_used) {
186   assert(set->histograms[i] != NULL);
187   set->histograms[i] = NULL;
188   --*num_used;
189   // If we remove the last valid one, shrink until the next valid one.
190   if (i == set->size - 1) {
191     while (set->size >= 1 && set->histograms[set->size - 1] == NULL) {
192       --set->size;
193     }
194   }
195 }
196 
197 // -----------------------------------------------------------------------------
198 
VP8LHistogramAddSinglePixOrCopy(VP8LHistogram * const histo,const PixOrCopy * const v,int (* const distance_modifier)(int,int),int distance_modifier_arg0)199 void VP8LHistogramAddSinglePixOrCopy(VP8LHistogram* const histo,
200                                      const PixOrCopy* const v,
201                                      int (*const distance_modifier)(int, int),
202                                      int distance_modifier_arg0) {
203   if (PixOrCopyIsLiteral(v)) {
204     ++histo->alpha_[PixOrCopyLiteral(v, 3)];
205     ++histo->red_[PixOrCopyLiteral(v, 2)];
206     ++histo->literal_[PixOrCopyLiteral(v, 1)];
207     ++histo->blue_[PixOrCopyLiteral(v, 0)];
208   } else if (PixOrCopyIsCacheIdx(v)) {
209     const int literal_ix =
210         NUM_LITERAL_CODES + NUM_LENGTH_CODES + PixOrCopyCacheIdx(v);
211     assert(histo->palette_code_bits_ != 0);
212     ++histo->literal_[literal_ix];
213   } else {
214     int code, extra_bits;
215     VP8LPrefixEncodeBits(PixOrCopyLength(v), &code, &extra_bits);
216     ++histo->literal_[NUM_LITERAL_CODES + code];
217     if (distance_modifier == NULL) {
218       VP8LPrefixEncodeBits(PixOrCopyDistance(v), &code, &extra_bits);
219     } else {
220       VP8LPrefixEncodeBits(
221           distance_modifier(distance_modifier_arg0, PixOrCopyDistance(v)),
222           &code, &extra_bits);
223     }
224     ++histo->distance_[code];
225   }
226 }
227 
228 // -----------------------------------------------------------------------------
229 // Entropy-related functions.
230 
BitsEntropyRefine(const VP8LBitEntropy * entropy)231 static WEBP_INLINE double BitsEntropyRefine(const VP8LBitEntropy* entropy) {
232   double mix;
233   if (entropy->nonzeros < 5) {
234     if (entropy->nonzeros <= 1) {
235       return 0;
236     }
237     // Two symbols, they will be 0 and 1 in a Huffman code.
238     // Let's mix in a bit of entropy to favor good clustering when
239     // distributions of these are combined.
240     if (entropy->nonzeros == 2) {
241       return 0.99 * entropy->sum + 0.01 * entropy->entropy;
242     }
243     // No matter what the entropy says, we cannot be better than min_limit
244     // with Huffman coding. I am mixing a bit of entropy into the
245     // min_limit since it produces much better (~0.5 %) compression results
246     // perhaps because of better entropy clustering.
247     if (entropy->nonzeros == 3) {
248       mix = 0.95;
249     } else {
250       mix = 0.7;  // nonzeros == 4.
251     }
252   } else {
253     mix = 0.627;
254   }
255 
256   {
257     double min_limit = 2 * entropy->sum - entropy->max_val;
258     min_limit = mix * min_limit + (1.0 - mix) * entropy->entropy;
259     return (entropy->entropy < min_limit) ? min_limit : entropy->entropy;
260   }
261 }
262 
VP8LBitsEntropy(const uint32_t * const array,int n)263 double VP8LBitsEntropy(const uint32_t* const array, int n) {
264   VP8LBitEntropy entropy;
265   VP8LBitsEntropyUnrefined(array, n, &entropy);
266 
267   return BitsEntropyRefine(&entropy);
268 }
269 
InitialHuffmanCost(void)270 static double InitialHuffmanCost(void) {
271   // Small bias because Huffman code length is typically not stored in
272   // full length.
273   static const int kHuffmanCodeOfHuffmanCodeSize = CODE_LENGTH_CODES * 3;
274   static const double kSmallBias = 9.1;
275   return kHuffmanCodeOfHuffmanCodeSize - kSmallBias;
276 }
277 
278 // Finalize the Huffman cost based on streak numbers and length type (<3 or >=3)
FinalHuffmanCost(const VP8LStreaks * const stats)279 static double FinalHuffmanCost(const VP8LStreaks* const stats) {
280   // The constants in this function are experimental and got rounded from
281   // their original values in 1/8 when switched to 1/1024.
282   double retval = InitialHuffmanCost();
283   // Second coefficient: Many zeros in the histogram are covered efficiently
284   // by a run-length encode. Originally 2/8.
285   retval += stats->counts[0] * 1.5625 + 0.234375 * stats->streaks[0][1];
286   // Second coefficient: Constant values are encoded less efficiently, but still
287   // RLE'ed. Originally 6/8.
288   retval += stats->counts[1] * 2.578125 + 0.703125 * stats->streaks[1][1];
289   // 0s are usually encoded more efficiently than non-0s.
290   // Originally 15/8.
291   retval += 1.796875 * stats->streaks[0][0];
292   // Originally 26/8.
293   retval += 3.28125 * stats->streaks[1][0];
294   return retval;
295 }
296 
297 // Get the symbol entropy for the distribution 'population'.
298 // Set 'trivial_sym', if there's only one symbol present in the distribution.
PopulationCost(const uint32_t * const population,int length,uint32_t * const trivial_sym,uint8_t * const is_used)299 static double PopulationCost(const uint32_t* const population, int length,
300                              uint32_t* const trivial_sym,
301                              uint8_t* const is_used) {
302   VP8LBitEntropy bit_entropy;
303   VP8LStreaks stats;
304   VP8LGetEntropyUnrefined(population, length, &bit_entropy, &stats);
305   if (trivial_sym != NULL) {
306     *trivial_sym = (bit_entropy.nonzeros == 1) ? bit_entropy.nonzero_code
307                                                : VP8L_NON_TRIVIAL_SYM;
308   }
309   // The histogram is used if there is at least one non-zero streak.
310   *is_used = (stats.streaks[1][0] != 0 || stats.streaks[1][1] != 0);
311 
312   return BitsEntropyRefine(&bit_entropy) + FinalHuffmanCost(&stats);
313 }
314 
315 // trivial_at_end is 1 if the two histograms only have one element that is
316 // non-zero: both the zero-th one, or both the last one.
GetCombinedEntropy(const uint32_t * const X,const uint32_t * const Y,int length,int is_X_used,int is_Y_used,int trivial_at_end)317 static WEBP_INLINE double GetCombinedEntropy(const uint32_t* const X,
318                                              const uint32_t* const Y,
319                                              int length, int is_X_used,
320                                              int is_Y_used,
321                                              int trivial_at_end) {
322   VP8LStreaks stats;
323   if (trivial_at_end) {
324     // This configuration is due to palettization that transforms an indexed
325     // pixel into 0xff000000 | (pixel << 8) in VP8LBundleColorMap.
326     // BitsEntropyRefine is 0 for histograms with only one non-zero value.
327     // Only FinalHuffmanCost needs to be evaluated.
328     memset(&stats, 0, sizeof(stats));
329     // Deal with the non-zero value at index 0 or length-1.
330     stats.streaks[1][0] = 1;
331     // Deal with the following/previous zero streak.
332     stats.counts[0] = 1;
333     stats.streaks[0][1] = length - 1;
334     return FinalHuffmanCost(&stats);
335   } else {
336     VP8LBitEntropy bit_entropy;
337     if (is_X_used) {
338       if (is_Y_used) {
339         VP8LGetCombinedEntropyUnrefined(X, Y, length, &bit_entropy, &stats);
340       } else {
341         VP8LGetEntropyUnrefined(X, length, &bit_entropy, &stats);
342       }
343     } else {
344       if (is_Y_used) {
345         VP8LGetEntropyUnrefined(Y, length, &bit_entropy, &stats);
346       } else {
347         memset(&stats, 0, sizeof(stats));
348         stats.counts[0] = 1;
349         stats.streaks[0][length > 3] = length;
350         VP8LBitEntropyInit(&bit_entropy);
351       }
352     }
353 
354     return BitsEntropyRefine(&bit_entropy) + FinalHuffmanCost(&stats);
355   }
356 }
357 
358 // Estimates the Entropy + Huffman + other block overhead size cost.
VP8LHistogramEstimateBits(VP8LHistogram * const p)359 double VP8LHistogramEstimateBits(VP8LHistogram* const p) {
360   return
361       PopulationCost(p->literal_, VP8LHistogramNumCodes(p->palette_code_bits_),
362                      NULL, &p->is_used_[0])
363       + PopulationCost(p->red_, NUM_LITERAL_CODES, NULL, &p->is_used_[1])
364       + PopulationCost(p->blue_, NUM_LITERAL_CODES, NULL, &p->is_used_[2])
365       + PopulationCost(p->alpha_, NUM_LITERAL_CODES, NULL, &p->is_used_[3])
366       + PopulationCost(p->distance_, NUM_DISTANCE_CODES, NULL, &p->is_used_[4])
367       + VP8LExtraCost(p->literal_ + NUM_LITERAL_CODES, NUM_LENGTH_CODES)
368       + VP8LExtraCost(p->distance_, NUM_DISTANCE_CODES);
369 }
370 
371 // -----------------------------------------------------------------------------
372 // Various histogram combine/cost-eval functions
373 
GetCombinedHistogramEntropy(const VP8LHistogram * const a,const VP8LHistogram * const b,double cost_threshold,double * cost)374 static int GetCombinedHistogramEntropy(const VP8LHistogram* const a,
375                                        const VP8LHistogram* const b,
376                                        double cost_threshold,
377                                        double* cost) {
378   const int palette_code_bits = a->palette_code_bits_;
379   int trivial_at_end = 0;
380   assert(a->palette_code_bits_ == b->palette_code_bits_);
381   *cost += GetCombinedEntropy(a->literal_, b->literal_,
382                               VP8LHistogramNumCodes(palette_code_bits),
383                               a->is_used_[0], b->is_used_[0], 0);
384   *cost += VP8LExtraCostCombined(a->literal_ + NUM_LITERAL_CODES,
385                                  b->literal_ + NUM_LITERAL_CODES,
386                                  NUM_LENGTH_CODES);
387   if (*cost > cost_threshold) return 0;
388 
389   if (a->trivial_symbol_ != VP8L_NON_TRIVIAL_SYM &&
390       a->trivial_symbol_ == b->trivial_symbol_) {
391     // A, R and B are all 0 or 0xff.
392     const uint32_t color_a = (a->trivial_symbol_ >> 24) & 0xff;
393     const uint32_t color_r = (a->trivial_symbol_ >> 16) & 0xff;
394     const uint32_t color_b = (a->trivial_symbol_ >> 0) & 0xff;
395     if ((color_a == 0 || color_a == 0xff) &&
396         (color_r == 0 || color_r == 0xff) &&
397         (color_b == 0 || color_b == 0xff)) {
398       trivial_at_end = 1;
399     }
400   }
401 
402   *cost +=
403       GetCombinedEntropy(a->red_, b->red_, NUM_LITERAL_CODES, a->is_used_[1],
404                          b->is_used_[1], trivial_at_end);
405   if (*cost > cost_threshold) return 0;
406 
407   *cost +=
408       GetCombinedEntropy(a->blue_, b->blue_, NUM_LITERAL_CODES, a->is_used_[2],
409                          b->is_used_[2], trivial_at_end);
410   if (*cost > cost_threshold) return 0;
411 
412   *cost +=
413       GetCombinedEntropy(a->alpha_, b->alpha_, NUM_LITERAL_CODES,
414                          a->is_used_[3], b->is_used_[3], trivial_at_end);
415   if (*cost > cost_threshold) return 0;
416 
417   *cost +=
418       GetCombinedEntropy(a->distance_, b->distance_, NUM_DISTANCE_CODES,
419                          a->is_used_[4], b->is_used_[4], 0);
420   *cost +=
421       VP8LExtraCostCombined(a->distance_, b->distance_, NUM_DISTANCE_CODES);
422   if (*cost > cost_threshold) return 0;
423 
424   return 1;
425 }
426 
HistogramAdd(const VP8LHistogram * const a,const VP8LHistogram * const b,VP8LHistogram * const out)427 static WEBP_INLINE void HistogramAdd(const VP8LHistogram* const a,
428                                      const VP8LHistogram* const b,
429                                      VP8LHistogram* const out) {
430   VP8LHistogramAdd(a, b, out);
431   out->trivial_symbol_ = (a->trivial_symbol_ == b->trivial_symbol_)
432                        ? a->trivial_symbol_
433                        : VP8L_NON_TRIVIAL_SYM;
434 }
435 
436 // Performs out = a + b, computing the cost C(a+b) - C(a) - C(b) while comparing
437 // to the threshold value 'cost_threshold'. The score returned is
438 //  Score = C(a+b) - C(a) - C(b), where C(a) + C(b) is known and fixed.
439 // Since the previous score passed is 'cost_threshold', we only need to compare
440 // the partial cost against 'cost_threshold + C(a) + C(b)' to possibly bail-out
441 // early.
HistogramAddEval(const VP8LHistogram * const a,const VP8LHistogram * const b,VP8LHistogram * const out,double cost_threshold)442 static double HistogramAddEval(const VP8LHistogram* const a,
443                                const VP8LHistogram* const b,
444                                VP8LHistogram* const out,
445                                double cost_threshold) {
446   double cost = 0;
447   const double sum_cost = a->bit_cost_ + b->bit_cost_;
448   cost_threshold += sum_cost;
449 
450   if (GetCombinedHistogramEntropy(a, b, cost_threshold, &cost)) {
451     HistogramAdd(a, b, out);
452     out->bit_cost_ = cost;
453     out->palette_code_bits_ = a->palette_code_bits_;
454   }
455 
456   return cost - sum_cost;
457 }
458 
459 // Same as HistogramAddEval(), except that the resulting histogram
460 // is not stored. Only the cost C(a+b) - C(a) is evaluated. We omit
461 // the term C(b) which is constant over all the evaluations.
HistogramAddThresh(const VP8LHistogram * const a,const VP8LHistogram * const b,double cost_threshold)462 static double HistogramAddThresh(const VP8LHistogram* const a,
463                                  const VP8LHistogram* const b,
464                                  double cost_threshold) {
465   double cost;
466   assert(a != NULL && b != NULL);
467   cost = -a->bit_cost_;
468   GetCombinedHistogramEntropy(a, b, cost_threshold, &cost);
469   return cost;
470 }
471 
472 // -----------------------------------------------------------------------------
473 
474 // The structure to keep track of cost range for the three dominant entropy
475 // symbols.
476 // TODO(skal): Evaluate if float can be used here instead of double for
477 // representing the entropy costs.
478 typedef struct {
479   double literal_max_;
480   double literal_min_;
481   double red_max_;
482   double red_min_;
483   double blue_max_;
484   double blue_min_;
485 } DominantCostRange;
486 
DominantCostRangeInit(DominantCostRange * const c)487 static void DominantCostRangeInit(DominantCostRange* const c) {
488   c->literal_max_ = 0.;
489   c->literal_min_ = MAX_COST;
490   c->red_max_ = 0.;
491   c->red_min_ = MAX_COST;
492   c->blue_max_ = 0.;
493   c->blue_min_ = MAX_COST;
494 }
495 
UpdateDominantCostRange(const VP8LHistogram * const h,DominantCostRange * const c)496 static void UpdateDominantCostRange(
497     const VP8LHistogram* const h, DominantCostRange* const c) {
498   if (c->literal_max_ < h->literal_cost_) c->literal_max_ = h->literal_cost_;
499   if (c->literal_min_ > h->literal_cost_) c->literal_min_ = h->literal_cost_;
500   if (c->red_max_ < h->red_cost_) c->red_max_ = h->red_cost_;
501   if (c->red_min_ > h->red_cost_) c->red_min_ = h->red_cost_;
502   if (c->blue_max_ < h->blue_cost_) c->blue_max_ = h->blue_cost_;
503   if (c->blue_min_ > h->blue_cost_) c->blue_min_ = h->blue_cost_;
504 }
505 
UpdateHistogramCost(VP8LHistogram * const h)506 static void UpdateHistogramCost(VP8LHistogram* const h) {
507   uint32_t alpha_sym, red_sym, blue_sym;
508   const double alpha_cost =
509       PopulationCost(h->alpha_, NUM_LITERAL_CODES, &alpha_sym,
510                      &h->is_used_[3]);
511   const double distance_cost =
512       PopulationCost(h->distance_, NUM_DISTANCE_CODES, NULL, &h->is_used_[4]) +
513       VP8LExtraCost(h->distance_, NUM_DISTANCE_CODES);
514   const int num_codes = VP8LHistogramNumCodes(h->palette_code_bits_);
515   h->literal_cost_ =
516       PopulationCost(h->literal_, num_codes, NULL, &h->is_used_[0]) +
517           VP8LExtraCost(h->literal_ + NUM_LITERAL_CODES, NUM_LENGTH_CODES);
518   h->red_cost_ =
519       PopulationCost(h->red_, NUM_LITERAL_CODES, &red_sym, &h->is_used_[1]);
520   h->blue_cost_ =
521       PopulationCost(h->blue_, NUM_LITERAL_CODES, &blue_sym, &h->is_used_[2]);
522   h->bit_cost_ = h->literal_cost_ + h->red_cost_ + h->blue_cost_ +
523                  alpha_cost + distance_cost;
524   if ((alpha_sym | red_sym | blue_sym) == VP8L_NON_TRIVIAL_SYM) {
525     h->trivial_symbol_ = VP8L_NON_TRIVIAL_SYM;
526   } else {
527     h->trivial_symbol_ =
528         ((uint32_t)alpha_sym << 24) | (red_sym << 16) | (blue_sym << 0);
529   }
530 }
531 
GetBinIdForEntropy(double min,double max,double val)532 static int GetBinIdForEntropy(double min, double max, double val) {
533   const double range = max - min;
534   if (range > 0.) {
535     const double delta = val - min;
536     return (int)((NUM_PARTITIONS - 1e-6) * delta / range);
537   } else {
538     return 0;
539   }
540 }
541 
GetHistoBinIndex(const VP8LHistogram * const h,const DominantCostRange * const c,int low_effort)542 static int GetHistoBinIndex(const VP8LHistogram* const h,
543                             const DominantCostRange* const c, int low_effort) {
544   int bin_id = GetBinIdForEntropy(c->literal_min_, c->literal_max_,
545                                   h->literal_cost_);
546   assert(bin_id < NUM_PARTITIONS);
547   if (!low_effort) {
548     bin_id = bin_id * NUM_PARTITIONS
549            + GetBinIdForEntropy(c->red_min_, c->red_max_, h->red_cost_);
550     bin_id = bin_id * NUM_PARTITIONS
551            + GetBinIdForEntropy(c->blue_min_, c->blue_max_, h->blue_cost_);
552     assert(bin_id < BIN_SIZE);
553   }
554   return bin_id;
555 }
556 
557 // Construct the histograms from backward references.
HistogramBuild(int xsize,int histo_bits,const VP8LBackwardRefs * const backward_refs,VP8LHistogramSet * const image_histo)558 static void HistogramBuild(
559     int xsize, int histo_bits, const VP8LBackwardRefs* const backward_refs,
560     VP8LHistogramSet* const image_histo) {
561   int x = 0, y = 0;
562   const int histo_xsize = VP8LSubSampleSize(xsize, histo_bits);
563   VP8LHistogram** const histograms = image_histo->histograms;
564   VP8LRefsCursor c = VP8LRefsCursorInit(backward_refs);
565   assert(histo_bits > 0);
566   VP8LHistogramSetClear(image_histo);
567   while (VP8LRefsCursorOk(&c)) {
568     const PixOrCopy* const v = c.cur_pos;
569     const int ix = (y >> histo_bits) * histo_xsize + (x >> histo_bits);
570     VP8LHistogramAddSinglePixOrCopy(histograms[ix], v, NULL, 0);
571     x += PixOrCopyLength(v);
572     while (x >= xsize) {
573       x -= xsize;
574       ++y;
575     }
576     VP8LRefsCursorNext(&c);
577   }
578 }
579 
580 // Copies the histograms and computes its bit_cost.
581 static const uint16_t kInvalidHistogramSymbol = (uint16_t)(-1);
HistogramCopyAndAnalyze(VP8LHistogramSet * const orig_histo,VP8LHistogramSet * const image_histo,int * const num_used,uint16_t * const histogram_symbols)582 static void HistogramCopyAndAnalyze(VP8LHistogramSet* const orig_histo,
583                                     VP8LHistogramSet* const image_histo,
584                                     int* const num_used,
585                                     uint16_t* const histogram_symbols) {
586   int i, cluster_id;
587   int num_used_orig = *num_used;
588   VP8LHistogram** const orig_histograms = orig_histo->histograms;
589   VP8LHistogram** const histograms = image_histo->histograms;
590   assert(image_histo->max_size == orig_histo->max_size);
591   for (cluster_id = 0, i = 0; i < orig_histo->max_size; ++i) {
592     VP8LHistogram* const histo = orig_histograms[i];
593     UpdateHistogramCost(histo);
594 
595     // Skip the histogram if it is completely empty, which can happen for tiles
596     // with no information (when they are skipped because of LZ77).
597     if (!histo->is_used_[0] && !histo->is_used_[1] && !histo->is_used_[2]
598         && !histo->is_used_[3] && !histo->is_used_[4]) {
599       // The first histogram is always used. If an histogram is empty, we set
600       // its id to be the same as the previous one: this will improve
601       // compressibility for later LZ77.
602       assert(i > 0);
603       HistogramSetRemoveHistogram(image_histo, i, num_used);
604       HistogramSetRemoveHistogram(orig_histo, i, &num_used_orig);
605       histogram_symbols[i] = kInvalidHistogramSymbol;
606     } else {
607       // Copy histograms from orig_histo[] to image_histo[].
608       HistogramCopy(histo, histograms[i]);
609       histogram_symbols[i] = cluster_id++;
610       assert(cluster_id <= image_histo->max_size);
611     }
612   }
613 }
614 
615 // Partition histograms to different entropy bins for three dominant (literal,
616 // red and blue) symbol costs and compute the histogram aggregate bit_cost.
HistogramAnalyzeEntropyBin(VP8LHistogramSet * const image_histo,uint16_t * const bin_map,int low_effort)617 static void HistogramAnalyzeEntropyBin(VP8LHistogramSet* const image_histo,
618                                        uint16_t* const bin_map,
619                                        int low_effort) {
620   int i;
621   VP8LHistogram** const histograms = image_histo->histograms;
622   const int histo_size = image_histo->size;
623   DominantCostRange cost_range;
624   DominantCostRangeInit(&cost_range);
625 
626   // Analyze the dominant (literal, red and blue) entropy costs.
627   for (i = 0; i < histo_size; ++i) {
628     if (histograms[i] == NULL) continue;
629     UpdateDominantCostRange(histograms[i], &cost_range);
630   }
631 
632   // bin-hash histograms on three of the dominant (literal, red and blue)
633   // symbol costs and store the resulting bin_id for each histogram.
634   for (i = 0; i < histo_size; ++i) {
635     // bin_map[i] is not set to a special value as its use will later be guarded
636     // by another (histograms[i] == NULL).
637     if (histograms[i] == NULL) continue;
638     bin_map[i] = GetHistoBinIndex(histograms[i], &cost_range, low_effort);
639   }
640 }
641 
642 // Merges some histograms with same bin_id together if it's advantageous.
643 // Sets the remaining histograms to NULL.
HistogramCombineEntropyBin(VP8LHistogramSet * const image_histo,int * num_used,const uint16_t * const clusters,uint16_t * const cluster_mappings,VP8LHistogram * cur_combo,const uint16_t * const bin_map,int num_bins,double combine_cost_factor,int low_effort)644 static void HistogramCombineEntropyBin(VP8LHistogramSet* const image_histo,
645                                        int* num_used,
646                                        const uint16_t* const clusters,
647                                        uint16_t* const cluster_mappings,
648                                        VP8LHistogram* cur_combo,
649                                        const uint16_t* const bin_map,
650                                        int num_bins,
651                                        double combine_cost_factor,
652                                        int low_effort) {
653   VP8LHistogram** const histograms = image_histo->histograms;
654   int idx;
655   struct {
656     int16_t first;    // position of the histogram that accumulates all
657                       // histograms with the same bin_id
658     uint16_t num_combine_failures;   // number of combine failures per bin_id
659   } bin_info[BIN_SIZE];
660 
661   assert(num_bins <= BIN_SIZE);
662   for (idx = 0; idx < num_bins; ++idx) {
663     bin_info[idx].first = -1;
664     bin_info[idx].num_combine_failures = 0;
665   }
666 
667   // By default, a cluster matches itself.
668   for (idx = 0; idx < *num_used; ++idx) cluster_mappings[idx] = idx;
669   for (idx = 0; idx < image_histo->size; ++idx) {
670     int bin_id, first;
671     if (histograms[idx] == NULL) continue;
672     bin_id = bin_map[idx];
673     first = bin_info[bin_id].first;
674     if (first == -1) {
675       bin_info[bin_id].first = idx;
676     } else if (low_effort) {
677       HistogramAdd(histograms[idx], histograms[first], histograms[first]);
678       HistogramSetRemoveHistogram(image_histo, idx, num_used);
679       cluster_mappings[clusters[idx]] = clusters[first];
680     } else {
681       // try to merge #idx into #first (both share the same bin_id)
682       const double bit_cost = histograms[idx]->bit_cost_;
683       const double bit_cost_thresh = -bit_cost * combine_cost_factor;
684       const double curr_cost_diff =
685           HistogramAddEval(histograms[first], histograms[idx],
686                            cur_combo, bit_cost_thresh);
687       if (curr_cost_diff < bit_cost_thresh) {
688         // Try to merge two histograms only if the combo is a trivial one or
689         // the two candidate histograms are already non-trivial.
690         // For some images, 'try_combine' turns out to be false for a lot of
691         // histogram pairs. In that case, we fallback to combining
692         // histograms as usual to avoid increasing the header size.
693         const int try_combine =
694             (cur_combo->trivial_symbol_ != VP8L_NON_TRIVIAL_SYM) ||
695             ((histograms[idx]->trivial_symbol_ == VP8L_NON_TRIVIAL_SYM) &&
696              (histograms[first]->trivial_symbol_ == VP8L_NON_TRIVIAL_SYM));
697         const int max_combine_failures = 32;
698         if (try_combine ||
699             bin_info[bin_id].num_combine_failures >= max_combine_failures) {
700           // move the (better) merged histogram to its final slot
701           HistogramSwap(&cur_combo, &histograms[first]);
702           HistogramSetRemoveHistogram(image_histo, idx, num_used);
703           cluster_mappings[clusters[idx]] = clusters[first];
704         } else {
705           ++bin_info[bin_id].num_combine_failures;
706         }
707       }
708     }
709   }
710   if (low_effort) {
711     // for low_effort case, update the final cost when everything is merged
712     for (idx = 0; idx < image_histo->size; ++idx) {
713       if (histograms[idx] == NULL) continue;
714       UpdateHistogramCost(histograms[idx]);
715     }
716   }
717 }
718 
719 // Implement a Lehmer random number generator with a multiplicative constant of
720 // 48271 and a modulo constant of 2^31 - 1.
MyRand(uint32_t * const seed)721 static uint32_t MyRand(uint32_t* const seed) {
722   *seed = (uint32_t)(((uint64_t)(*seed) * 48271u) % 2147483647u);
723   assert(*seed > 0);
724   return *seed;
725 }
726 
727 // -----------------------------------------------------------------------------
728 // Histogram pairs priority queue
729 
730 // Pair of histograms. Negative idx1 value means that pair is out-of-date.
731 typedef struct {
732   int idx1;
733   int idx2;
734   double cost_diff;
735   double cost_combo;
736 } HistogramPair;
737 
738 typedef struct {
739   HistogramPair* queue;
740   int size;
741   int max_size;
742 } HistoQueue;
743 
HistoQueueInit(HistoQueue * const histo_queue,const int max_size)744 static int HistoQueueInit(HistoQueue* const histo_queue, const int max_size) {
745   histo_queue->size = 0;
746   histo_queue->max_size = max_size;
747   // We allocate max_size + 1 because the last element at index "size" is
748   // used as temporary data (and it could be up to max_size).
749   histo_queue->queue = (HistogramPair*)WebPSafeMalloc(
750       histo_queue->max_size + 1, sizeof(*histo_queue->queue));
751   return histo_queue->queue != NULL;
752 }
753 
HistoQueueClear(HistoQueue * const histo_queue)754 static void HistoQueueClear(HistoQueue* const histo_queue) {
755   assert(histo_queue != NULL);
756   WebPSafeFree(histo_queue->queue);
757   histo_queue->size = 0;
758   histo_queue->max_size = 0;
759 }
760 
761 // Pop a specific pair in the queue by replacing it with the last one
762 // and shrinking the queue.
HistoQueuePopPair(HistoQueue * const histo_queue,HistogramPair * const pair)763 static void HistoQueuePopPair(HistoQueue* const histo_queue,
764                               HistogramPair* const pair) {
765   assert(pair >= histo_queue->queue &&
766          pair < (histo_queue->queue + histo_queue->size));
767   assert(histo_queue->size > 0);
768   *pair = histo_queue->queue[histo_queue->size - 1];
769   --histo_queue->size;
770 }
771 
772 // Check whether a pair in the queue should be updated as head or not.
HistoQueueUpdateHead(HistoQueue * const histo_queue,HistogramPair * const pair)773 static void HistoQueueUpdateHead(HistoQueue* const histo_queue,
774                                  HistogramPair* const pair) {
775   assert(pair->cost_diff < 0.);
776   assert(pair >= histo_queue->queue &&
777          pair < (histo_queue->queue + histo_queue->size));
778   assert(histo_queue->size > 0);
779   if (pair->cost_diff < histo_queue->queue[0].cost_diff) {
780     // Replace the best pair.
781     const HistogramPair tmp = histo_queue->queue[0];
782     histo_queue->queue[0] = *pair;
783     *pair = tmp;
784   }
785 }
786 
787 // Update the cost diff and combo of a pair of histograms. This needs to be
788 // called when the the histograms have been merged with a third one.
HistoQueueUpdatePair(const VP8LHistogram * const h1,const VP8LHistogram * const h2,double threshold,HistogramPair * const pair)789 static void HistoQueueUpdatePair(const VP8LHistogram* const h1,
790                                  const VP8LHistogram* const h2,
791                                  double threshold,
792                                  HistogramPair* const pair) {
793   const double sum_cost = h1->bit_cost_ + h2->bit_cost_;
794   pair->cost_combo = 0.;
795   GetCombinedHistogramEntropy(h1, h2, sum_cost + threshold, &pair->cost_combo);
796   pair->cost_diff = pair->cost_combo - sum_cost;
797 }
798 
799 // Create a pair from indices "idx1" and "idx2" provided its cost
800 // is inferior to "threshold", a negative entropy.
801 // It returns the cost of the pair, or 0. if it superior to threshold.
HistoQueuePush(HistoQueue * const histo_queue,VP8LHistogram ** const histograms,int idx1,int idx2,double threshold)802 static double HistoQueuePush(HistoQueue* const histo_queue,
803                              VP8LHistogram** const histograms, int idx1,
804                              int idx2, double threshold) {
805   const VP8LHistogram* h1;
806   const VP8LHistogram* h2;
807   HistogramPair pair;
808 
809   // Stop here if the queue is full.
810   if (histo_queue->size == histo_queue->max_size) return 0.;
811   assert(threshold <= 0.);
812   if (idx1 > idx2) {
813     const int tmp = idx2;
814     idx2 = idx1;
815     idx1 = tmp;
816   }
817   pair.idx1 = idx1;
818   pair.idx2 = idx2;
819   h1 = histograms[idx1];
820   h2 = histograms[idx2];
821 
822   HistoQueueUpdatePair(h1, h2, threshold, &pair);
823 
824   // Do not even consider the pair if it does not improve the entropy.
825   if (pair.cost_diff >= threshold) return 0.;
826 
827   histo_queue->queue[histo_queue->size++] = pair;
828   HistoQueueUpdateHead(histo_queue, &histo_queue->queue[histo_queue->size - 1]);
829 
830   return pair.cost_diff;
831 }
832 
833 // -----------------------------------------------------------------------------
834 
835 // Combines histograms by continuously choosing the one with the highest cost
836 // reduction.
HistogramCombineGreedy(VP8LHistogramSet * const image_histo,int * const num_used)837 static int HistogramCombineGreedy(VP8LHistogramSet* const image_histo,
838                                   int* const num_used) {
839   int ok = 0;
840   const int image_histo_size = image_histo->size;
841   int i, j;
842   VP8LHistogram** const histograms = image_histo->histograms;
843   // Priority queue of histogram pairs.
844   HistoQueue histo_queue;
845 
846   // image_histo_size^2 for the queue size is safe. If you look at
847   // HistogramCombineGreedy, and imagine that UpdateQueueFront always pushes
848   // data to the queue, you insert at most:
849   // - image_histo_size*(image_histo_size-1)/2 (the first two for loops)
850   // - image_histo_size - 1 in the last for loop at the first iteration of
851   //   the while loop, image_histo_size - 2 at the second iteration ...
852   //   therefore image_histo_size*(image_histo_size-1)/2 overall too
853   if (!HistoQueueInit(&histo_queue, image_histo_size * image_histo_size)) {
854     goto End;
855   }
856 
857   for (i = 0; i < image_histo_size; ++i) {
858     if (image_histo->histograms[i] == NULL) continue;
859     for (j = i + 1; j < image_histo_size; ++j) {
860       // Initialize queue.
861       if (image_histo->histograms[j] == NULL) continue;
862       HistoQueuePush(&histo_queue, histograms, i, j, 0.);
863     }
864   }
865 
866   while (histo_queue.size > 0) {
867     const int idx1 = histo_queue.queue[0].idx1;
868     const int idx2 = histo_queue.queue[0].idx2;
869     HistogramAdd(histograms[idx2], histograms[idx1], histograms[idx1]);
870     histograms[idx1]->bit_cost_ = histo_queue.queue[0].cost_combo;
871 
872     // Remove merged histogram.
873     HistogramSetRemoveHistogram(image_histo, idx2, num_used);
874 
875     // Remove pairs intersecting the just combined best pair.
876     for (i = 0; i < histo_queue.size;) {
877       HistogramPair* const p = histo_queue.queue + i;
878       if (p->idx1 == idx1 || p->idx2 == idx1 ||
879           p->idx1 == idx2 || p->idx2 == idx2) {
880         HistoQueuePopPair(&histo_queue, p);
881       } else {
882         HistoQueueUpdateHead(&histo_queue, p);
883         ++i;
884       }
885     }
886 
887     // Push new pairs formed with combined histogram to the queue.
888     for (i = 0; i < image_histo->size; ++i) {
889       if (i == idx1 || image_histo->histograms[i] == NULL) continue;
890       HistoQueuePush(&histo_queue, image_histo->histograms, idx1, i, 0.);
891     }
892   }
893 
894   ok = 1;
895 
896  End:
897   HistoQueueClear(&histo_queue);
898   return ok;
899 }
900 
901 // Perform histogram aggregation using a stochastic approach.
902 // 'do_greedy' is set to 1 if a greedy approach needs to be performed
903 // afterwards, 0 otherwise.
PairComparison(const void * idx1,const void * idx2)904 static int PairComparison(const void* idx1, const void* idx2) {
905   // To be used with bsearch: <0 when *idx1<*idx2, >0 if >, 0 when ==.
906   return (*(int*) idx1 - *(int*) idx2);
907 }
HistogramCombineStochastic(VP8LHistogramSet * const image_histo,int * const num_used,int min_cluster_size,int * const do_greedy)908 static int HistogramCombineStochastic(VP8LHistogramSet* const image_histo,
909                                       int* const num_used, int min_cluster_size,
910                                       int* const do_greedy) {
911   int j, iter;
912   uint32_t seed = 1;
913   int tries_with_no_success = 0;
914   const int outer_iters = *num_used;
915   const int num_tries_no_success = outer_iters / 2;
916   VP8LHistogram** const histograms = image_histo->histograms;
917   // Priority queue of histogram pairs. Its size of 'kHistoQueueSize'
918   // impacts the quality of the compression and the speed: the smaller the
919   // faster but the worse for the compression.
920   HistoQueue histo_queue;
921   const int kHistoQueueSize = 9;
922   int ok = 0;
923   // mapping from an index in image_histo with no NULL histogram to the full
924   // blown image_histo.
925   int* mappings;
926 
927   if (*num_used < min_cluster_size) {
928     *do_greedy = 1;
929     return 1;
930   }
931 
932   mappings = (int*) WebPSafeMalloc(*num_used, sizeof(*mappings));
933   if (mappings == NULL) return 0;
934   if (!HistoQueueInit(&histo_queue, kHistoQueueSize)) goto End;
935   // Fill the initial mapping.
936   for (j = 0, iter = 0; iter < image_histo->size; ++iter) {
937     if (histograms[iter] == NULL) continue;
938     mappings[j++] = iter;
939   }
940   assert(j == *num_used);
941 
942   // Collapse similar histograms in 'image_histo'.
943   for (iter = 0;
944        iter < outer_iters && *num_used >= min_cluster_size &&
945            ++tries_with_no_success < num_tries_no_success;
946        ++iter) {
947     int* mapping_index;
948     double best_cost =
949         (histo_queue.size == 0) ? 0. : histo_queue.queue[0].cost_diff;
950     int best_idx1 = -1, best_idx2 = 1;
951     const uint32_t rand_range = (*num_used - 1) * (*num_used);
952     // (*num_used) / 2 was chosen empirically. Less means faster but worse
953     // compression.
954     const int num_tries = (*num_used) / 2;
955 
956     // Pick random samples.
957     for (j = 0; *num_used >= 2 && j < num_tries; ++j) {
958       double curr_cost;
959       // Choose two different histograms at random and try to combine them.
960       const uint32_t tmp = MyRand(&seed) % rand_range;
961       uint32_t idx1 = tmp / (*num_used - 1);
962       uint32_t idx2 = tmp % (*num_used - 1);
963       if (idx2 >= idx1) ++idx2;
964       idx1 = mappings[idx1];
965       idx2 = mappings[idx2];
966 
967       // Calculate cost reduction on combination.
968       curr_cost =
969           HistoQueuePush(&histo_queue, histograms, idx1, idx2, best_cost);
970       if (curr_cost < 0) {  // found a better pair?
971         best_cost = curr_cost;
972         // Empty the queue if we reached full capacity.
973         if (histo_queue.size == histo_queue.max_size) break;
974       }
975     }
976     if (histo_queue.size == 0) continue;
977 
978     // Get the best histograms.
979     best_idx1 = histo_queue.queue[0].idx1;
980     best_idx2 = histo_queue.queue[0].idx2;
981     assert(best_idx1 < best_idx2);
982     // Pop best_idx2 from mappings.
983     mapping_index = (int*) bsearch(&best_idx2, mappings, *num_used,
984                                    sizeof(best_idx2), &PairComparison);
985     assert(mapping_index != NULL);
986     memmove(mapping_index, mapping_index + 1, sizeof(*mapping_index) *
987         ((*num_used) - (mapping_index - mappings) - 1));
988     // Merge the histograms and remove best_idx2 from the queue.
989     HistogramAdd(histograms[best_idx2], histograms[best_idx1],
990                  histograms[best_idx1]);
991     histograms[best_idx1]->bit_cost_ = histo_queue.queue[0].cost_combo;
992     HistogramSetRemoveHistogram(image_histo, best_idx2, num_used);
993     // Parse the queue and update each pair that deals with best_idx1,
994     // best_idx2 or image_histo_size.
995     for (j = 0; j < histo_queue.size;) {
996       HistogramPair* const p = histo_queue.queue + j;
997       const int is_idx1_best = p->idx1 == best_idx1 || p->idx1 == best_idx2;
998       const int is_idx2_best = p->idx2 == best_idx1 || p->idx2 == best_idx2;
999       int do_eval = 0;
1000       // The front pair could have been duplicated by a random pick so
1001       // check for it all the time nevertheless.
1002       if (is_idx1_best && is_idx2_best) {
1003         HistoQueuePopPair(&histo_queue, p);
1004         continue;
1005       }
1006       // Any pair containing one of the two best indices should only refer to
1007       // best_idx1. Its cost should also be updated.
1008       if (is_idx1_best) {
1009         p->idx1 = best_idx1;
1010         do_eval = 1;
1011       } else if (is_idx2_best) {
1012         p->idx2 = best_idx1;
1013         do_eval = 1;
1014       }
1015       // Make sure the index order is respected.
1016       if (p->idx1 > p->idx2) {
1017         const int tmp = p->idx2;
1018         p->idx2 = p->idx1;
1019         p->idx1 = tmp;
1020       }
1021       if (do_eval) {
1022         // Re-evaluate the cost of an updated pair.
1023         HistoQueueUpdatePair(histograms[p->idx1], histograms[p->idx2], 0., p);
1024         if (p->cost_diff >= 0.) {
1025           HistoQueuePopPair(&histo_queue, p);
1026           continue;
1027         }
1028       }
1029       HistoQueueUpdateHead(&histo_queue, p);
1030       ++j;
1031     }
1032     tries_with_no_success = 0;
1033   }
1034   *do_greedy = (*num_used <= min_cluster_size);
1035   ok = 1;
1036 
1037 End:
1038   HistoQueueClear(&histo_queue);
1039   WebPSafeFree(mappings);
1040   return ok;
1041 }
1042 
1043 // -----------------------------------------------------------------------------
1044 // Histogram refinement
1045 
1046 // Find the best 'out' histogram for each of the 'in' histograms.
1047 // At call-time, 'out' contains the histograms of the clusters.
1048 // Note: we assume that out[]->bit_cost_ is already up-to-date.
HistogramRemap(const VP8LHistogramSet * const in,VP8LHistogramSet * const out,uint16_t * const symbols)1049 static void HistogramRemap(const VP8LHistogramSet* const in,
1050                            VP8LHistogramSet* const out,
1051                            uint16_t* const symbols) {
1052   int i;
1053   VP8LHistogram** const in_histo = in->histograms;
1054   VP8LHistogram** const out_histo = out->histograms;
1055   const int in_size = out->max_size;
1056   const int out_size = out->size;
1057   if (out_size > 1) {
1058     for (i = 0; i < in_size; ++i) {
1059       int best_out = 0;
1060       double best_bits = MAX_COST;
1061       int k;
1062       if (in_histo[i] == NULL) {
1063         // Arbitrarily set to the previous value if unused to help future LZ77.
1064         symbols[i] = symbols[i - 1];
1065         continue;
1066       }
1067       for (k = 0; k < out_size; ++k) {
1068         double cur_bits;
1069         cur_bits = HistogramAddThresh(out_histo[k], in_histo[i], best_bits);
1070         if (k == 0 || cur_bits < best_bits) {
1071           best_bits = cur_bits;
1072           best_out = k;
1073         }
1074       }
1075       symbols[i] = best_out;
1076     }
1077   } else {
1078     assert(out_size == 1);
1079     for (i = 0; i < in_size; ++i) {
1080       symbols[i] = 0;
1081     }
1082   }
1083 
1084   // Recompute each out based on raw and symbols.
1085   VP8LHistogramSetClear(out);
1086   out->size = out_size;
1087 
1088   for (i = 0; i < in_size; ++i) {
1089     int idx;
1090     if (in_histo[i] == NULL) continue;
1091     idx = symbols[i];
1092     HistogramAdd(in_histo[i], out_histo[idx], out_histo[idx]);
1093   }
1094 }
1095 
GetCombineCostFactor(int histo_size,int quality)1096 static double GetCombineCostFactor(int histo_size, int quality) {
1097   double combine_cost_factor = 0.16;
1098   if (quality < 90) {
1099     if (histo_size > 256) combine_cost_factor /= 2.;
1100     if (histo_size > 512) combine_cost_factor /= 2.;
1101     if (histo_size > 1024) combine_cost_factor /= 2.;
1102     if (quality <= 50) combine_cost_factor /= 2.;
1103   }
1104   return combine_cost_factor;
1105 }
1106 
1107 // Given a HistogramSet 'set', the mapping of clusters 'cluster_mapping' and the
1108 // current assignment of the cells in 'symbols', merge the clusters and
1109 // assign the smallest possible clusters values.
OptimizeHistogramSymbols(const VP8LHistogramSet * const set,uint16_t * const cluster_mappings,int num_clusters,uint16_t * const cluster_mappings_tmp,uint16_t * const symbols)1110 static void OptimizeHistogramSymbols(const VP8LHistogramSet* const set,
1111                                      uint16_t* const cluster_mappings,
1112                                      int num_clusters,
1113                                      uint16_t* const cluster_mappings_tmp,
1114                                      uint16_t* const symbols) {
1115   int i, cluster_max;
1116   int do_continue = 1;
1117   // First, assign the lowest cluster to each pixel.
1118   while (do_continue) {
1119     do_continue = 0;
1120     for (i = 0; i < num_clusters; ++i) {
1121       int k;
1122       k = cluster_mappings[i];
1123       while (k != cluster_mappings[k]) {
1124         cluster_mappings[k] = cluster_mappings[cluster_mappings[k]];
1125         k = cluster_mappings[k];
1126       }
1127       if (k != cluster_mappings[i]) {
1128         do_continue = 1;
1129         cluster_mappings[i] = k;
1130       }
1131     }
1132   }
1133   // Create a mapping from a cluster id to its minimal version.
1134   cluster_max = 0;
1135   memset(cluster_mappings_tmp, 0,
1136          set->max_size * sizeof(*cluster_mappings_tmp));
1137   assert(cluster_mappings[0] == 0);
1138   // Re-map the ids.
1139   for (i = 0; i < set->max_size; ++i) {
1140     int cluster;
1141     if (symbols[i] == kInvalidHistogramSymbol) continue;
1142     cluster = cluster_mappings[symbols[i]];
1143     assert(symbols[i] < num_clusters);
1144     if (cluster > 0 && cluster_mappings_tmp[cluster] == 0) {
1145       ++cluster_max;
1146       cluster_mappings_tmp[cluster] = cluster_max;
1147     }
1148     symbols[i] = cluster_mappings_tmp[cluster];
1149   }
1150 
1151   // Make sure all cluster values are used.
1152   cluster_max = 0;
1153   for (i = 0; i < set->max_size; ++i) {
1154     if (symbols[i] == kInvalidHistogramSymbol) continue;
1155     if (symbols[i] <= cluster_max) continue;
1156     ++cluster_max;
1157     assert(symbols[i] == cluster_max);
1158   }
1159 }
1160 
RemoveEmptyHistograms(VP8LHistogramSet * const image_histo)1161 static void RemoveEmptyHistograms(VP8LHistogramSet* const image_histo) {
1162   uint32_t size;
1163   int i;
1164   for (i = 0, size = 0; i < image_histo->size; ++i) {
1165     if (image_histo->histograms[i] == NULL) continue;
1166     image_histo->histograms[size++] = image_histo->histograms[i];
1167   }
1168   image_histo->size = size;
1169 }
1170 
VP8LGetHistoImageSymbols(int xsize,int ysize,const VP8LBackwardRefs * const refs,int quality,int low_effort,int histo_bits,int cache_bits,VP8LHistogramSet * const image_histo,VP8LHistogram * const tmp_histo,uint16_t * const histogram_symbols)1171 int VP8LGetHistoImageSymbols(int xsize, int ysize,
1172                              const VP8LBackwardRefs* const refs,
1173                              int quality, int low_effort,
1174                              int histo_bits, int cache_bits,
1175                              VP8LHistogramSet* const image_histo,
1176                              VP8LHistogram* const tmp_histo,
1177                              uint16_t* const histogram_symbols) {
1178   int ok = 0;
1179   const int histo_xsize = histo_bits ? VP8LSubSampleSize(xsize, histo_bits) : 1;
1180   const int histo_ysize = histo_bits ? VP8LSubSampleSize(ysize, histo_bits) : 1;
1181   const int image_histo_raw_size = histo_xsize * histo_ysize;
1182   VP8LHistogramSet* const orig_histo =
1183       VP8LAllocateHistogramSet(image_histo_raw_size, cache_bits);
1184   // Don't attempt linear bin-partition heuristic for
1185   // histograms of small sizes (as bin_map will be very sparse) and
1186   // maximum quality q==100 (to preserve the compression gains at that level).
1187   const int entropy_combine_num_bins = low_effort ? NUM_PARTITIONS : BIN_SIZE;
1188   int entropy_combine;
1189   uint16_t* const map_tmp =
1190       WebPSafeMalloc(2 * image_histo_raw_size, sizeof(map_tmp));
1191   uint16_t* const cluster_mappings = map_tmp + image_histo_raw_size;
1192   int num_used = image_histo_raw_size;
1193   if (orig_histo == NULL || map_tmp == NULL) goto Error;
1194 
1195   // Construct the histograms from backward references.
1196   HistogramBuild(xsize, histo_bits, refs, orig_histo);
1197   // Copies the histograms and computes its bit_cost.
1198   // histogram_symbols is optimized
1199   HistogramCopyAndAnalyze(orig_histo, image_histo, &num_used,
1200                           histogram_symbols);
1201 
1202   entropy_combine =
1203       (num_used > entropy_combine_num_bins * 2) && (quality < 100);
1204 
1205   if (entropy_combine) {
1206     uint16_t* const bin_map = map_tmp;
1207     const double combine_cost_factor =
1208         GetCombineCostFactor(image_histo_raw_size, quality);
1209     const uint32_t num_clusters = num_used;
1210 
1211     HistogramAnalyzeEntropyBin(image_histo, bin_map, low_effort);
1212     // Collapse histograms with similar entropy.
1213     HistogramCombineEntropyBin(image_histo, &num_used, histogram_symbols,
1214                                cluster_mappings, tmp_histo, bin_map,
1215                                entropy_combine_num_bins, combine_cost_factor,
1216                                low_effort);
1217     OptimizeHistogramSymbols(image_histo, cluster_mappings, num_clusters,
1218                              map_tmp, histogram_symbols);
1219   }
1220 
1221   // Don't combine the histograms using stochastic and greedy heuristics for
1222   // low-effort compression mode.
1223   if (!low_effort || !entropy_combine) {
1224     const float x = quality / 100.f;
1225     // cubic ramp between 1 and MAX_HISTO_GREEDY:
1226     const int threshold_size = (int)(1 + (x * x * x) * (MAX_HISTO_GREEDY - 1));
1227     int do_greedy;
1228     if (!HistogramCombineStochastic(image_histo, &num_used, threshold_size,
1229                                     &do_greedy)) {
1230       goto Error;
1231     }
1232     if (do_greedy) {
1233       RemoveEmptyHistograms(image_histo);
1234       if (!HistogramCombineGreedy(image_histo, &num_used)) {
1235         goto Error;
1236       }
1237     }
1238   }
1239 
1240   // Find the optimal map from original histograms to the final ones.
1241   RemoveEmptyHistograms(image_histo);
1242   HistogramRemap(orig_histo, image_histo, histogram_symbols);
1243 
1244   ok = 1;
1245 
1246  Error:
1247   VP8LFreeHistogramSet(orig_histo);
1248   WebPSafeFree(map_tmp);
1249   return ok;
1250 }
1251