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