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