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