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