/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 | 1.76M | #define NUM_PARTITIONS 4 |
33 | | // The size of the bin-hash corresponding to the three dominant costs. |
34 | 6.55k | #define BIN_SIZE (NUM_PARTITIONS * NUM_PARTITIONS * NUM_PARTITIONS) |
35 | | // Maximum number of histograms allowed in greedy combining algorithm. |
36 | 6.55k | #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 | 722k | static int GetHistogramSize(int cache_bits) { |
43 | 722k | const int literal_size = VP8LHistogramNumCodes(cache_bits); |
44 | 722k | const size_t total_size = sizeof(VP8LHistogram) + sizeof(int) * literal_size; |
45 | 722k | assert(total_size <= (size_t)0x7fffffff); |
46 | 722k | return (int)total_size; |
47 | 722k | } |
48 | | |
49 | 2.61M | static void HistogramStatsClear(VP8LHistogram* const h) { |
50 | 2.61M | int i; |
51 | 15.7M | for (i = 0; i < 5; ++i) { |
52 | 13.0M | h->trivial_symbol[i] = VP8L_NON_TRIVIAL_SYM; |
53 | | // By default, the histogram is assumed to be used. |
54 | 13.0M | h->is_used[i] = 1; |
55 | 13.0M | } |
56 | 2.61M | h->bit_cost = 0; |
57 | 2.61M | memset(h->costs, 0, sizeof(h->costs)); |
58 | 2.61M | } |
59 | | |
60 | 106k | static void HistogramClear(VP8LHistogram* const h) { |
61 | 106k | uint32_t* const literal = h->literal; |
62 | 106k | const int cache_bits = h->palette_code_bits; |
63 | 106k | const int histo_size = GetHistogramSize(cache_bits); |
64 | 106k | memset(h, 0, histo_size); |
65 | 106k | h->palette_code_bits = cache_bits; |
66 | 106k | h->literal = literal; |
67 | 106k | HistogramStatsClear(h); |
68 | 106k | } |
69 | | |
70 | | // Swap two histogram pointers. |
71 | 327k | static void HistogramSwap(VP8LHistogram** const h1, VP8LHistogram** const h2) { |
72 | 327k | VP8LHistogram* const tmp = *h1; |
73 | 327k | *h1 = *h2; |
74 | 327k | *h2 = tmp; |
75 | 327k | } |
76 | | |
77 | | static void HistogramCopy(const VP8LHistogram* const src, |
78 | 446k | VP8LHistogram* const dst) { |
79 | 446k | uint32_t* const dst_literal = dst->literal; |
80 | 446k | const int dst_cache_bits = dst->palette_code_bits; |
81 | 446k | const int literal_size = VP8LHistogramNumCodes(dst_cache_bits); |
82 | 446k | const int histo_size = GetHistogramSize(dst_cache_bits); |
83 | 446k | assert(src->palette_code_bits == dst_cache_bits); |
84 | 446k | memcpy(dst, src, histo_size); |
85 | 446k | dst->literal = dst_literal; |
86 | 446k | memcpy(dst->literal, src->literal, literal_size * sizeof(*dst->literal)); |
87 | 446k | } |
88 | | |
89 | 103k | void VP8LFreeHistogram(VP8LHistogram* const h) { WebPSafeFree(h); } |
90 | | |
91 | 22.3k | void VP8LFreeHistogramSet(VP8LHistogramSet* const histograms) { |
92 | 22.3k | WebPSafeFree(histograms); |
93 | 22.3k | } |
94 | | |
95 | | void VP8LHistogramCreate(VP8LHistogram* const h, |
96 | | const VP8LBackwardRefs* const refs, |
97 | 25.8k | int palette_code_bits) { |
98 | 25.8k | if (palette_code_bits >= 0) { |
99 | 25.8k | h->palette_code_bits = palette_code_bits; |
100 | 25.8k | } |
101 | 25.8k | HistogramClear(h); |
102 | 25.8k | VP8LHistogramStoreRefs(refs, /*distance_modifier=*/NULL, |
103 | 25.8k | /*distance_modifier_arg0=*/0, h); |
104 | 25.8k | } |
105 | | |
106 | | void VP8LHistogramInit(VP8LHistogram* const h, int palette_code_bits, |
107 | 2.59M | int init_arrays) { |
108 | 2.59M | h->palette_code_bits = palette_code_bits; |
109 | 2.59M | if (init_arrays) { |
110 | 80.7k | HistogramClear(h); |
111 | 2.51M | } else { |
112 | 2.51M | HistogramStatsClear(h); |
113 | 2.51M | } |
114 | 2.59M | } |
115 | | |
116 | 98.5k | VP8LHistogram* VP8LAllocateHistogram(int cache_bits) { |
117 | 98.5k | VP8LHistogram* histo = NULL; |
118 | 98.5k | const int total_size = GetHistogramSize(cache_bits); |
119 | 98.5k | uint8_t* const memory = (uint8_t*)WebPSafeMalloc(total_size, sizeof(*memory)); |
120 | 98.5k | if (memory == NULL) return NULL; |
121 | 98.5k | histo = (VP8LHistogram*)memory; |
122 | | // 'literal' won't necessary be aligned. |
123 | 98.5k | histo->literal = (uint32_t*)(memory + sizeof(VP8LHistogram)); |
124 | 98.5k | VP8LHistogramInit(histo, cache_bits, /*init_arrays=*/0); |
125 | 98.5k | return histo; |
126 | 98.5k | } |
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 | 35.4k | int cache_bits) { |
131 | 35.4k | int i; |
132 | 35.4k | const int histo_size = GetHistogramSize(cache_bits); |
133 | 35.4k | uint8_t* memory = (uint8_t*)(set->histograms); |
134 | 35.4k | memory += set->max_size * sizeof(*set->histograms); |
135 | 4.86M | for (i = 0; i < set->max_size; ++i) { |
136 | 4.82M | memory = (uint8_t*)WEBP_ALIGN(memory); |
137 | 4.82M | set->histograms[i] = (VP8LHistogram*)memory; |
138 | | // 'literal' won't necessary be aligned. |
139 | 4.82M | set->histograms[i]->literal = (uint32_t*)(memory + sizeof(VP8LHistogram)); |
140 | 4.82M | memory += histo_size; |
141 | 4.82M | } |
142 | 35.4k | } |
143 | | |
144 | | // Returns the total size of the VP8LHistogramSet. |
145 | 35.4k | static size_t HistogramSetTotalSize(int size, int cache_bits) { |
146 | 35.4k | const int histo_size = GetHistogramSize(cache_bits); |
147 | 35.4k | return (sizeof(VP8LHistogramSet) + |
148 | 35.4k | size * (sizeof(VP8LHistogram*) + histo_size + WEBP_ALIGN_CST)); |
149 | 35.4k | } |
150 | | |
151 | 17.7k | VP8LHistogramSet* VP8LAllocateHistogramSet(int size, int cache_bits) { |
152 | 17.7k | int i; |
153 | 17.7k | VP8LHistogramSet* set; |
154 | 17.7k | const size_t total_size = HistogramSetTotalSize(size, cache_bits); |
155 | 17.7k | uint8_t* memory = (uint8_t*)WebPSafeMalloc(total_size, sizeof(*memory)); |
156 | 17.7k | if (memory == NULL) return NULL; |
157 | | |
158 | 17.7k | set = (VP8LHistogramSet*)memory; |
159 | 17.7k | memory += sizeof(*set); |
160 | 17.7k | set->histograms = (VP8LHistogram**)memory; |
161 | 17.7k | set->max_size = size; |
162 | 17.7k | set->size = size; |
163 | 17.7k | HistogramSetResetPointers(set, cache_bits); |
164 | 2.43M | for (i = 0; i < size; ++i) { |
165 | 2.41M | VP8LHistogramInit(set->histograms[i], cache_bits, /*init_arrays=*/0); |
166 | 2.41M | } |
167 | 17.7k | return set; |
168 | 17.7k | } |
169 | | |
170 | 17.7k | void VP8LHistogramSetClear(VP8LHistogramSet* const set) { |
171 | 17.7k | int i; |
172 | 17.7k | const int cache_bits = set->histograms[0]->palette_code_bits; |
173 | 17.7k | const int size = set->max_size; |
174 | 17.7k | const size_t total_size = HistogramSetTotalSize(size, cache_bits); |
175 | 17.7k | uint8_t* memory = (uint8_t*)set; |
176 | | |
177 | 17.7k | memset(memory, 0, total_size); |
178 | 17.7k | memory += sizeof(*set); |
179 | 17.7k | set->histograms = (VP8LHistogram**)memory; |
180 | 17.7k | set->max_size = size; |
181 | 17.7k | set->size = size; |
182 | 17.7k | HistogramSetResetPointers(set, cache_bits); |
183 | 2.43M | for (i = 0; i < size; ++i) { |
184 | 2.41M | set->histograms[i]->palette_code_bits = cache_bits; |
185 | 2.41M | } |
186 | 17.7k | } |
187 | | |
188 | | // Removes the histogram 'i' from 'set'. |
189 | 429k | static void HistogramSetRemoveHistogram(VP8LHistogramSet* const set, int i) { |
190 | 429k | set->histograms[i] = set->histograms[set->size - 1]; |
191 | 429k | --set->size; |
192 | 429k | assert(set->size > 0); |
193 | 429k | } |
194 | | |
195 | | // ----------------------------------------------------------------------------- |
196 | | |
197 | | static void HistogramAddSinglePixOrCopy( |
198 | | VP8LHistogram* const histo, const PixOrCopy* const v, |
199 | 981M | int (*const distance_modifier)(int, int), int distance_modifier_arg0) { |
200 | 981M | if (PixOrCopyIsLiteral(v)) { |
201 | 764M | ++histo->alpha[PixOrCopyLiteral(v, 3)]; |
202 | 764M | ++histo->red[PixOrCopyLiteral(v, 2)]; |
203 | 764M | ++histo->literal[PixOrCopyLiteral(v, 1)]; |
204 | 764M | ++histo->blue[PixOrCopyLiteral(v, 0)]; |
205 | 764M | } else if (PixOrCopyIsCacheIdx(v)) { |
206 | 149M | const int literal_ix = |
207 | 149M | NUM_LITERAL_CODES + NUM_LENGTH_CODES + PixOrCopyCacheIdx(v); |
208 | 149M | assert(histo->palette_code_bits != 0); |
209 | 149M | ++histo->literal[literal_ix]; |
210 | 149M | } else { |
211 | 67.8M | int code, extra_bits; |
212 | 67.8M | VP8LPrefixEncodeBits(PixOrCopyLength(v), &code, &extra_bits); |
213 | 67.8M | ++histo->literal[NUM_LITERAL_CODES + code]; |
214 | 67.8M | if (distance_modifier == NULL) { |
215 | 51.7M | VP8LPrefixEncodeBits(PixOrCopyDistance(v), &code, &extra_bits); |
216 | 51.7M | } else { |
217 | 16.0M | VP8LPrefixEncodeBits( |
218 | 16.0M | distance_modifier(distance_modifier_arg0, PixOrCopyDistance(v)), |
219 | 16.0M | &code, &extra_bits); |
220 | 16.0M | } |
221 | 67.8M | ++histo->distance[code]; |
222 | 67.8M | } |
223 | 981M | } |
224 | | |
225 | | void VP8LHistogramStoreRefs(const VP8LBackwardRefs* const refs, |
226 | | int (*const distance_modifier)(int, int), |
227 | | int distance_modifier_arg0, |
228 | 36.0k | VP8LHistogram* const histo) { |
229 | 36.0k | VP8LRefsCursor c = VP8LRefsCursorInit(refs); |
230 | 808M | while (VP8LRefsCursorOk(&c)) { |
231 | 808M | HistogramAddSinglePixOrCopy(histo, c.cur_pos, distance_modifier, |
232 | 808M | distance_modifier_arg0); |
233 | 808M | VP8LRefsCursorNext(&c); |
234 | 808M | } |
235 | 36.0k | } |
236 | | |
237 | | // ----------------------------------------------------------------------------- |
238 | | // Entropy-related functions. |
239 | | |
240 | 20.6M | static WEBP_INLINE uint64_t BitsEntropyRefine(const VP8LBitEntropy* entropy) { |
241 | 20.6M | uint64_t mix; |
242 | 20.6M | if (entropy->nonzeros < 5) { |
243 | 7.50M | if (entropy->nonzeros <= 1) { |
244 | 6.24M | return 0; |
245 | 6.24M | } |
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 | 1.25M | if (entropy->nonzeros == 2) { |
250 | 703k | return DivRound(99 * ((uint64_t)entropy->sum << LOG_2_PRECISION_BITS) + |
251 | 703k | entropy->entropy, |
252 | 703k | 100); |
253 | 703k | } |
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 | 552k | if (entropy->nonzeros == 3) { |
259 | 290k | mix = 950; |
260 | 290k | } else { |
261 | 262k | mix = 700; // nonzeros == 4. |
262 | 262k | } |
263 | 13.1M | } else { |
264 | 13.1M | mix = 627; |
265 | 13.1M | } |
266 | | |
267 | 13.7M | { |
268 | 13.7M | uint64_t min_limit = (uint64_t)(2 * entropy->sum - entropy->max_val) |
269 | 13.7M | << LOG_2_PRECISION_BITS; |
270 | 13.7M | min_limit = |
271 | 13.7M | DivRound(mix * min_limit + (1000 - mix) * entropy->entropy, 1000); |
272 | 13.7M | return (entropy->entropy < min_limit) ? min_limit : entropy->entropy; |
273 | 20.6M | } |
274 | 20.6M | } |
275 | | |
276 | 34.3k | uint64_t VP8LBitsEntropy(const uint32_t* const array, int n) { |
277 | 34.3k | VP8LBitEntropy entropy; |
278 | 34.3k | VP8LBitsEntropyUnrefined(array, n, &entropy); |
279 | | |
280 | 34.3k | return BitsEntropyRefine(&entropy); |
281 | 34.3k | } |
282 | | |
283 | 20.6M | static uint64_t InitialHuffmanCost(void) { |
284 | | // Small bias because Huffman code length is typically not stored in |
285 | | // full length. |
286 | 20.6M | static const uint64_t kHuffmanCodeOfHuffmanCodeSize = CODE_LENGTH_CODES * 3; |
287 | | // Subtract a bias of 9.1. |
288 | 20.6M | return (kHuffmanCodeOfHuffmanCodeSize << LOG_2_PRECISION_BITS) - |
289 | 20.6M | DivRound(91ll << LOG_2_PRECISION_BITS, 10); |
290 | 20.6M | } |
291 | | |
292 | | // Finalize the Huffman cost based on streak numbers and length type (<3 or >=3) |
293 | 20.6M | 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 | 20.6M | 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 | 20.6M | 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 | 20.6M | 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 | 20.6M | retval_extra += 1840 * stats->streaks[0][0]; |
306 | | // Originally 26/8. |
307 | 20.6M | retval_extra += 3360 * stats->streaks[1][0]; |
308 | 20.6M | return retval + ((uint64_t)retval_extra << (LOG_2_PRECISION_BITS - 10)); |
309 | 20.6M | } |
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 | 6.52M | uint8_t* const is_used) { |
316 | 6.52M | VP8LBitEntropy bit_entropy; |
317 | 6.52M | VP8LStreaks stats; |
318 | 6.52M | VP8LGetEntropyUnrefined(population, length, &bit_entropy, &stats); |
319 | 6.52M | if (trivial_sym != NULL) { |
320 | 6.02M | *trivial_sym = (bit_entropy.nonzeros == 1) ? bit_entropy.nonzero_code |
321 | 6.02M | : VP8L_NON_TRIVIAL_SYM; |
322 | 6.02M | } |
323 | 6.52M | if (is_used != NULL) { |
324 | | // The histogram is used if there is at least one non-zero streak. |
325 | 6.02M | *is_used = (stats.streaks[1][0] != 0 || stats.streaks[1][1] != 0); |
326 | 6.02M | } |
327 | | |
328 | 6.52M | return BitsEntropyRefine(&bit_entropy) + FinalHuffmanCost(&stats); |
329 | 6.52M | } |
330 | | |
331 | | static WEBP_INLINE void GetPopulationInfo(const VP8LHistogram* const histo, |
332 | | HistogramIndex index, |
333 | | const uint32_t** population, |
334 | 47.9M | int* length) { |
335 | 47.9M | switch (index) { |
336 | 23.7M | case LITERAL: |
337 | 23.7M | *population = histo->literal; |
338 | 23.7M | *length = VP8LHistogramNumCodes(histo->palette_code_bits); |
339 | 23.7M | break; |
340 | 4.18M | case RED: |
341 | 4.18M | *population = histo->red; |
342 | 4.18M | *length = NUM_LITERAL_CODES; |
343 | 4.18M | break; |
344 | 4.17M | case BLUE: |
345 | 4.17M | *population = histo->blue; |
346 | 4.17M | *length = NUM_LITERAL_CODES; |
347 | 4.17M | break; |
348 | 4.21M | case ALPHA: |
349 | 4.21M | *population = histo->alpha; |
350 | 4.21M | *length = NUM_LITERAL_CODES; |
351 | 4.21M | break; |
352 | 11.6M | case DISTANCE: |
353 | 11.6M | *population = histo->distance; |
354 | 11.6M | *length = NUM_DISTANCE_CODES; |
355 | 11.6M | break; |
356 | 47.9M | } |
357 | 47.9M | } |
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 | 33.3M | HistogramIndex index) { |
366 | 33.3M | const uint32_t* X; |
367 | 33.3M | const uint32_t* Y; |
368 | 33.3M | int length; |
369 | 33.3M | VP8LStreaks stats; |
370 | 33.3M | VP8LBitEntropy bit_entropy; |
371 | 33.3M | const int is_h1_used = h1->is_used[index]; |
372 | 33.3M | const int is_h2_used = h2->is_used[index]; |
373 | 33.3M | const int is_trivial = h1->trivial_symbol[index] != VP8L_NON_TRIVIAL_SYM && |
374 | 15.2M | h1->trivial_symbol[index] == h2->trivial_symbol[index]; |
375 | | |
376 | 33.3M | if (is_trivial || !is_h1_used || !is_h2_used) { |
377 | 19.1M | if (is_h1_used) return h1->costs[index]; |
378 | 3.60M | return h2->costs[index]; |
379 | 19.1M | } |
380 | 33.3M | assert(is_h1_used && is_h2_used); |
381 | | |
382 | 14.1M | GetPopulationInfo(h1, index, &X, &length); |
383 | 14.1M | GetPopulationInfo(h2, index, &Y, &length); |
384 | 14.1M | VP8LGetCombinedEntropyUnrefined(X, Y, length, &bit_entropy, &stats); |
385 | 14.1M | return BitsEntropyRefine(&bit_entropy) + FinalHuffmanCost(&stats); |
386 | 33.3M | } |
387 | | |
388 | | // Estimates the Entropy + Huffman + other block overhead size cost. |
389 | 101k | uint64_t VP8LHistogramEstimateBits(const VP8LHistogram* const h) { |
390 | 101k | int i; |
391 | 101k | uint64_t cost = 0; |
392 | 607k | for (i = 0; i < 5; ++i) { |
393 | 505k | int length; |
394 | 505k | const uint32_t* population; |
395 | 505k | GetPopulationInfo(h, (HistogramIndex)i, &population, &length); |
396 | 505k | cost += PopulationCost(population, length, /*trivial_sym=*/NULL, |
397 | 505k | /*is_used=*/NULL); |
398 | 505k | } |
399 | 101k | cost += ((uint64_t)(VP8LExtraCost(h->literal + NUM_LITERAL_CODES, |
400 | 101k | NUM_LENGTH_CODES) + |
401 | 101k | VP8LExtraCost(h->distance, NUM_DISTANCE_CODES)) |
402 | 101k | << LOG_2_PRECISION_BITS); |
403 | 101k | return cost; |
404 | 101k | } |
405 | | |
406 | | // ----------------------------------------------------------------------------- |
407 | | // Various histogram combine/cost-eval functions |
408 | | |
409 | | // Set a + b in b, saturating at WEBP_INT64_MAX. |
410 | 10.4M | static WEBP_INLINE void SaturateAdd(uint64_t a, int64_t* b) { |
411 | 10.4M | if (*b < 0 || (int64_t)a <= WEBP_INT64_MAX - *b) { |
412 | 10.1M | *b += (int64_t)a; |
413 | 10.1M | } else { |
414 | 323k | *b = WEBP_INT64_MAX; |
415 | 323k | } |
416 | 10.4M | } |
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 | 10.4M | int64_t cost_threshold_in, uint64_t* cost, uint64_t costs[5]) { |
423 | 10.4M | int i; |
424 | 10.4M | const uint64_t cost_threshold = (uint64_t)cost_threshold_in; |
425 | 10.4M | assert(a->palette_code_bits == b->palette_code_bits); |
426 | 10.4M | if (cost_threshold_in <= 0) return 0; |
427 | 10.4M | *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 | 34.5M | for (i = 0; i < 5; ++i) { |
432 | 33.3M | costs[i] = GetCombinedEntropy(a, b, (HistogramIndex)i); |
433 | 33.3M | *cost += costs[i]; |
434 | 33.3M | if (*cost >= cost_threshold) return 0; |
435 | 33.3M | } |
436 | | |
437 | 1.24M | return 1; |
438 | 10.4M | } |
439 | | |
440 | | static WEBP_INLINE void HistogramAdd(const VP8LHistogram* const h1, |
441 | | const VP8LHistogram* const h2, |
442 | 878k | VP8LHistogram* const hout) { |
443 | 878k | int i; |
444 | 878k | assert(h1->palette_code_bits == h2->palette_code_bits); |
445 | | |
446 | 5.26M | for (i = 0; i < 5; ++i) { |
447 | 4.39M | int length; |
448 | 4.39M | const uint32_t *p1, *p2, *pout_const; |
449 | 4.39M | uint32_t* pout; |
450 | 4.39M | GetPopulationInfo(h1, (HistogramIndex)i, &p1, &length); |
451 | 4.39M | GetPopulationInfo(h2, (HistogramIndex)i, &p2, &length); |
452 | 4.39M | GetPopulationInfo(hout, (HistogramIndex)i, &pout_const, &length); |
453 | 4.39M | pout = (uint32_t*)pout_const; |
454 | 4.39M | if (h2 == hout) { |
455 | 2.74M | if (h1->is_used[i]) { |
456 | 1.95M | if (hout->is_used[i]) { |
457 | 1.86M | VP8LAddVectorEq(p1, pout, length); |
458 | 1.86M | } else { |
459 | 82.4k | memcpy(pout, p1, length * sizeof(pout[0])); |
460 | 82.4k | } |
461 | 1.95M | } |
462 | 2.74M | } else { |
463 | 1.64M | if (h1->is_used[i]) { |
464 | 1.16M | if (h2->is_used[i]) { |
465 | 1.15M | VP8LAddVector(p1, p2, pout, length); |
466 | 1.15M | } else { |
467 | 12.7k | memcpy(pout, p1, length * sizeof(pout[0])); |
468 | 12.7k | } |
469 | 1.16M | } else if (h2->is_used[i]) { |
470 | 304 | memcpy(pout, p2, length * sizeof(pout[0])); |
471 | 478k | } else { |
472 | 478k | memset(pout, 0, length * sizeof(pout[0])); |
473 | 478k | } |
474 | 1.64M | } |
475 | 4.39M | } |
476 | | |
477 | 5.26M | for (i = 0; i < 5; ++i) { |
478 | 4.39M | hout->trivial_symbol[i] = h1->trivial_symbol[i] == h2->trivial_symbol[i] |
479 | 4.39M | ? h1->trivial_symbol[i] |
480 | 4.39M | : VP8L_NON_TRIVIAL_SYM; |
481 | 4.39M | hout->is_used[i] = h1->is_used[i] || h2->is_used[i]; |
482 | 4.39M | } |
483 | 878k | } |
484 | | |
485 | | static void UpdateHistogramCost(uint64_t bit_cost, uint64_t costs[5], |
486 | 431k | VP8LHistogram* const h) { |
487 | 431k | int i; |
488 | 431k | h->bit_cost = bit_cost; |
489 | 2.59M | for (i = 0; i < 5; ++i) { |
490 | 2.15M | h->costs[i] = costs[i]; |
491 | 2.15M | } |
492 | 431k | } |
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 | 363k | int64_t cost_threshold) { |
506 | 363k | const uint64_t sum_cost = a->bit_cost + b->bit_cost; |
507 | 363k | uint64_t bit_cost, costs[5]; |
508 | 363k | SaturateAdd(sum_cost, &cost_threshold); |
509 | 363k | if (!GetCombinedHistogramEntropy(a, b, cost_threshold, &bit_cost, costs)) { |
510 | 34.0k | return 0; |
511 | 34.0k | } |
512 | | |
513 | 329k | HistogramAdd(a, b, out); |
514 | 329k | UpdateHistogramCost(bit_cost, costs, out); |
515 | 329k | return 1; |
516 | 363k | } |
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 | 5.69M | int64_t* cost_out) { |
527 | 5.69M | uint64_t cost, costs[5]; |
528 | 5.69M | assert(a != NULL && b != NULL); |
529 | 5.69M | SaturateAdd(a->bit_cost, &cost_threshold); |
530 | 5.69M | if (!GetCombinedHistogramEntropy(a, b, cost_threshold, &cost, costs)) { |
531 | 4.93M | return 0; |
532 | 4.93M | } |
533 | | |
534 | 764k | *cost_out = (int64_t)cost - (int64_t)a->bit_cost; |
535 | 764k | return 1; |
536 | 5.69M | } |
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 | 732 | static void DominantCostRangeInit(DominantCostRange* const c) { |
552 | 732 | c->literal_max = 0; |
553 | 732 | c->literal_min = WEBP_UINT64_MAX; |
554 | 732 | c->red_max = 0; |
555 | 732 | c->red_min = WEBP_UINT64_MAX; |
556 | 732 | c->blue_max = 0; |
557 | 732 | c->blue_min = WEBP_UINT64_MAX; |
558 | 732 | } |
559 | | |
560 | | static void UpdateDominantCostRange(const VP8LHistogram* const h, |
561 | 366k | DominantCostRange* const c) { |
562 | 366k | if (c->literal_max < h->costs[LITERAL]) c->literal_max = h->costs[LITERAL]; |
563 | 366k | if (c->literal_min > h->costs[LITERAL]) c->literal_min = h->costs[LITERAL]; |
564 | 366k | if (c->red_max < h->costs[RED]) c->red_max = h->costs[RED]; |
565 | 366k | if (c->red_min > h->costs[RED]) c->red_min = h->costs[RED]; |
566 | 366k | if (c->blue_max < h->costs[BLUE]) c->blue_max = h->costs[BLUE]; |
567 | 366k | if (c->blue_min > h->costs[BLUE]) c->blue_min = h->costs[BLUE]; |
568 | 366k | } |
569 | | |
570 | 1.20M | static void ComputeHistogramCost(VP8LHistogram* const h) { |
571 | 1.20M | 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 | 7.22M | for (i = 0; i < 5; ++i) { |
575 | 6.02M | const uint32_t* population; |
576 | 6.02M | int length; |
577 | 6.02M | GetPopulationInfo(h, i, &population, &length); |
578 | 6.02M | h->costs[i] = PopulationCost(population, length, &h->trivial_symbol[i], |
579 | 6.02M | &h->is_used[i]); |
580 | 6.02M | } |
581 | 1.20M | h->bit_cost = h->costs[LITERAL] + h->costs[RED] + h->costs[BLUE] + |
582 | 1.20M | h->costs[ALPHA] + h->costs[DISTANCE]; |
583 | 1.20M | } |
584 | | |
585 | 1.09M | static int GetBinIdForEntropy(uint64_t min, uint64_t max, uint64_t val) { |
586 | 1.09M | const uint64_t range = max - min; |
587 | 1.09M | if (range > 0) { |
588 | 1.01M | const uint64_t delta = val - min; |
589 | 1.01M | return (int)((NUM_PARTITIONS - 1e-6) * delta / range); |
590 | 1.01M | } else { |
591 | 86.3k | return 0; |
592 | 86.3k | } |
593 | 1.09M | } |
594 | | |
595 | | static int GetHistoBinIndex(const VP8LHistogram* const h, |
596 | 366k | const DominantCostRange* const c, int low_effort) { |
597 | 366k | int bin_id = |
598 | 366k | GetBinIdForEntropy(c->literal_min, c->literal_max, h->costs[LITERAL]); |
599 | 366k | assert(bin_id < NUM_PARTITIONS); |
600 | 366k | if (!low_effort) { |
601 | 366k | bin_id = bin_id * NUM_PARTITIONS + |
602 | 366k | GetBinIdForEntropy(c->red_min, c->red_max, h->costs[RED]); |
603 | 366k | bin_id = bin_id * NUM_PARTITIONS + |
604 | 366k | GetBinIdForEntropy(c->blue_min, c->blue_max, h->costs[BLUE]); |
605 | 366k | assert(bin_id < BIN_SIZE); |
606 | 366k | } |
607 | 366k | return bin_id; |
608 | 366k | } |
609 | | |
610 | | // Construct the histograms from backward references. |
611 | | static void HistogramBuild(int xsize, int histo_bits, |
612 | | const VP8LBackwardRefs* const backward_refs, |
613 | 6.55k | VP8LHistogramSet* const image_histo) { |
614 | 6.55k | int x = 0, y = 0; |
615 | 6.55k | const int histo_xsize = VP8LSubSampleSize(xsize, histo_bits); |
616 | 6.55k | VP8LHistogram** const histograms = image_histo->histograms; |
617 | 6.55k | VP8LRefsCursor c = VP8LRefsCursorInit(backward_refs); |
618 | 6.55k | assert(histo_bits > 0); |
619 | 6.55k | VP8LHistogramSetClear(image_histo); |
620 | 173M | while (VP8LRefsCursorOk(&c)) { |
621 | 173M | const PixOrCopy* const v = c.cur_pos; |
622 | 173M | const int ix = (y >> histo_bits) * histo_xsize + (x >> histo_bits); |
623 | 173M | HistogramAddSinglePixOrCopy(histograms[ix], v, NULL, 0); |
624 | 173M | x += PixOrCopyLength(v); |
625 | 176M | while (x >= xsize) { |
626 | 2.96M | x -= xsize; |
627 | 2.96M | ++y; |
628 | 2.96M | } |
629 | 173M | VP8LRefsCursorNext(&c); |
630 | 173M | } |
631 | 6.55k | } |
632 | | |
633 | | // Copies the histograms and computes its bit_cost. |
634 | | static void HistogramCopyAndAnalyze(VP8LHistogramSet* const orig_histo, |
635 | 6.55k | VP8LHistogramSet* const image_histo) { |
636 | 6.55k | int i; |
637 | 6.55k | VP8LHistogram** const orig_histograms = orig_histo->histograms; |
638 | 6.55k | VP8LHistogram** const histograms = image_histo->histograms; |
639 | 6.55k | assert(image_histo->max_size == orig_histo->max_size); |
640 | 6.55k | image_histo->size = 0; |
641 | 1.21M | for (i = 0; i < orig_histo->max_size; ++i) { |
642 | 1.20M | VP8LHistogram* const histo = orig_histograms[i]; |
643 | 1.20M | 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 | 1.20M | if (!histo->is_used[LITERAL] && !histo->is_used[RED] && |
648 | 757k | !histo->is_used[BLUE] && !histo->is_used[ALPHA] && |
649 | 757k | !histo->is_used[DISTANCE]) { |
650 | | // The first histogram is always used. |
651 | 757k | assert(i > 0); |
652 | 757k | orig_histograms[i] = NULL; |
653 | 757k | } else { |
654 | | // Copy histograms from orig_histo[] to image_histo[]. |
655 | 446k | HistogramCopy(histo, histograms[image_histo->size]); |
656 | 446k | ++image_histo->size; |
657 | 446k | } |
658 | 1.20M | } |
659 | 6.55k | } |
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 | 732 | int low_effort) { |
665 | 732 | int i; |
666 | 732 | VP8LHistogram** const histograms = image_histo->histograms; |
667 | 732 | const int histo_size = image_histo->size; |
668 | 732 | DominantCostRange cost_range; |
669 | 732 | DominantCostRangeInit(&cost_range); |
670 | | |
671 | | // Analyze the dominant (literal, red and blue) entropy costs. |
672 | 367k | for (i = 0; i < histo_size; ++i) { |
673 | 366k | UpdateDominantCostRange(histograms[i], &cost_range); |
674 | 366k | } |
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 | 367k | for (i = 0; i < histo_size; ++i) { |
679 | 366k | histograms[i]->bin_id = |
680 | 366k | GetHistoBinIndex(histograms[i], &cost_range, low_effort); |
681 | 366k | } |
682 | 732 | } |
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 | 732 | int low_effort) { |
691 | 732 | VP8LHistogram** const histograms = image_histo->histograms; |
692 | 732 | int idx; |
693 | 732 | struct { |
694 | 732 | int16_t first; // position of the histogram that accumulates all |
695 | | // histograms with the same bin_id |
696 | 732 | uint16_t num_combine_failures; // number of combine failures per bin_id |
697 | 732 | } bin_info[BIN_SIZE]; |
698 | | |
699 | 732 | assert(num_bins <= BIN_SIZE); |
700 | 47.5k | for (idx = 0; idx < num_bins; ++idx) { |
701 | 46.8k | bin_info[idx].first = -1; |
702 | 46.8k | bin_info[idx].num_combine_failures = 0; |
703 | 46.8k | } |
704 | | |
705 | 367k | for (idx = 0; idx < image_histo->size;) { |
706 | 366k | const int bin_id = histograms[idx]->bin_id; |
707 | 366k | const int first = bin_info[bin_id].first; |
708 | 366k | if (first == -1) { |
709 | 3.16k | bin_info[bin_id].first = idx; |
710 | 3.16k | ++idx; |
711 | 363k | } else if (low_effort) { |
712 | 0 | HistogramAdd(histograms[idx], histograms[first], histograms[first]); |
713 | 0 | HistogramSetRemoveHistogram(image_histo, idx); |
714 | 363k | } else { |
715 | | // try to merge #idx into #first (both share the same bin_id) |
716 | 363k | const uint64_t bit_cost = histograms[idx]->bit_cost; |
717 | 363k | const int64_t bit_cost_thresh = |
718 | 363k | -DivRound((int64_t)bit_cost * combine_cost_factor, 100); |
719 | 363k | if (HistogramAddEval(histograms[first], histograms[idx], cur_combo, |
720 | 363k | bit_cost_thresh)) { |
721 | 329k | 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 | 329k | int try_combine = |
728 | 329k | cur_combo->trivial_symbol[RED] != VP8L_NON_TRIVIAL_SYM && |
729 | 170k | cur_combo->trivial_symbol[BLUE] != VP8L_NON_TRIVIAL_SYM && |
730 | 170k | cur_combo->trivial_symbol[ALPHA] != VP8L_NON_TRIVIAL_SYM; |
731 | 329k | if (!try_combine) { |
732 | 163k | try_combine = |
733 | 163k | histograms[idx]->trivial_symbol[RED] == VP8L_NON_TRIVIAL_SYM || |
734 | 3.83k | histograms[idx]->trivial_symbol[BLUE] == VP8L_NON_TRIVIAL_SYM || |
735 | 3.83k | histograms[idx]->trivial_symbol[ALPHA] == VP8L_NON_TRIVIAL_SYM; |
736 | 163k | try_combine &= |
737 | 163k | histograms[first]->trivial_symbol[RED] == VP8L_NON_TRIVIAL_SYM || |
738 | 3.83k | histograms[first]->trivial_symbol[BLUE] == VP8L_NON_TRIVIAL_SYM || |
739 | 3.83k | histograms[first]->trivial_symbol[ALPHA] == VP8L_NON_TRIVIAL_SYM; |
740 | 163k | } |
741 | 329k | if (try_combine || |
742 | 327k | bin_info[bin_id].num_combine_failures >= max_combine_failures) { |
743 | | // move the (better) merged histogram to its final slot |
744 | 327k | HistogramSwap(&cur_combo, &histograms[first]); |
745 | 327k | HistogramSetRemoveHistogram(image_histo, idx); |
746 | 327k | } else { |
747 | 2.07k | ++bin_info[bin_id].num_combine_failures; |
748 | 2.07k | ++idx; |
749 | 2.07k | } |
750 | 329k | } else { |
751 | 34.0k | ++idx; |
752 | 34.0k | } |
753 | 363k | } |
754 | 366k | } |
755 | 732 | 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 | 732 | } |
762 | | |
763 | | // Implement a Lehmer random number generator with a multiplicative constant of |
764 | | // 48271 and a modulo constant of 2^31 - 1. |
765 | 4.34M | static uint32_t MyRand(uint32_t* const seed) { |
766 | 4.34M | *seed = (uint32_t)(((uint64_t)(*seed) * 48271u) % 2147483647u); |
767 | 4.34M | assert(*seed > 0); |
768 | 4.34M | return *seed; |
769 | 4.34M | } |
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 | 8.59k | static int HistoQueueInit(HistoQueue* const histo_queue, const int max_size) { |
790 | 8.59k | histo_queue->size = 0; |
791 | 8.59k | 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 | 8.59k | histo_queue->queue = (HistogramPair*)WebPSafeMalloc( |
795 | 8.59k | histo_queue->max_size + 1, sizeof(*histo_queue->queue)); |
796 | 8.59k | return histo_queue->queue != NULL; |
797 | 8.59k | } |
798 | | |
799 | 8.59k | static void HistoQueueClear(HistoQueue* const histo_queue) { |
800 | 8.59k | assert(histo_queue != NULL); |
801 | 8.59k | WebPSafeFree(histo_queue->queue); |
802 | 8.59k | histo_queue->size = 0; |
803 | 8.59k | histo_queue->max_size = 0; |
804 | 8.59k | } |
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 | 108k | HistogramPair* const pair) { |
810 | 108k | assert(pair >= histo_queue->queue && |
811 | 108k | pair < (histo_queue->queue + histo_queue->size)); |
812 | 108k | assert(histo_queue->size > 0); |
813 | 108k | *pair = histo_queue->queue[histo_queue->size - 1]; |
814 | 108k | --histo_queue->size; |
815 | 108k | } |
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 | 447k | HistogramPair* const pair) { |
820 | 447k | assert(pair->cost_diff < 0); |
821 | 447k | assert(pair >= histo_queue->queue && |
822 | 447k | pair < (histo_queue->queue + histo_queue->size)); |
823 | 447k | assert(histo_queue->size > 0); |
824 | 447k | if (pair->cost_diff < histo_queue->queue[0].cost_diff) { |
825 | | // Replace the best pair. |
826 | 101k | const HistogramPair tmp = histo_queue->queue[0]; |
827 | 101k | histo_queue->queue[0] = *pair; |
828 | 101k | *pair = tmp; |
829 | 101k | } |
830 | 447k | } |
831 | | |
832 | | // Replaces the bad_id with good_id in the pair. |
833 | | static void HistoQueueFixPair(int bad_id, int good_id, |
834 | 379k | HistogramPair* const pair) { |
835 | 379k | if (pair->idx1 == bad_id) pair->idx1 = good_id; |
836 | 379k | if (pair->idx2 == bad_id) pair->idx2 = good_id; |
837 | 379k | if (pair->idx1 > pair->idx2) { |
838 | 8.48k | const int tmp = pair->idx1; |
839 | 8.48k | pair->idx1 = pair->idx2; |
840 | 8.48k | pair->idx2 = tmp; |
841 | 8.48k | } |
842 | 379k | } |
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 | 4.40M | HistogramPair* const pair) { |
852 | 4.40M | const int64_t sum_cost = h1->bit_cost + h2->bit_cost; |
853 | 4.40M | SaturateAdd(sum_cost, &cost_threshold); |
854 | 4.40M | if (!GetCombinedHistogramEntropy(h1, h2, cost_threshold, &pair->cost_combo, |
855 | 4.40M | pair->costs)) { |
856 | 4.24M | return 0; |
857 | 4.24M | } |
858 | 152k | pair->cost_diff = (int64_t)pair->cost_combo - sum_cost; |
859 | 152k | return 1; |
860 | 4.40M | } |
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 | 4.35M | int idx2, int64_t threshold) { |
868 | 4.35M | const VP8LHistogram* h1; |
869 | 4.35M | const VP8LHistogram* h2; |
870 | 4.35M | HistogramPair pair; |
871 | | |
872 | | // Stop here if the queue is full. |
873 | 4.35M | if (histo_queue->size == histo_queue->max_size) return 0; |
874 | 4.35M | assert(threshold <= 0); |
875 | 4.35M | if (idx1 > idx2) { |
876 | 2.17M | const int tmp = idx2; |
877 | 2.17M | idx2 = idx1; |
878 | 2.17M | idx1 = tmp; |
879 | 2.17M | } |
880 | 4.35M | pair.idx1 = idx1; |
881 | 4.35M | pair.idx2 = idx2; |
882 | 4.35M | h1 = histograms[idx1]; |
883 | 4.35M | h2 = histograms[idx2]; |
884 | | |
885 | | // Do not even consider the pair if it does not improve the entropy. |
886 | 4.35M | if (!HistoQueueUpdatePair(h1, h2, threshold, &pair)) return 0; |
887 | | |
888 | 111k | histo_queue->queue[histo_queue->size++] = pair; |
889 | 111k | HistoQueueUpdateHead(histo_queue, &histo_queue->queue[histo_queue->size - 1]); |
890 | | |
891 | 111k | return pair.cost_diff; |
892 | 4.35M | } |
893 | | |
894 | | // ----------------------------------------------------------------------------- |
895 | | |
896 | | // Combines histograms by continuously choosing the one with the highest cost |
897 | | // reduction. |
898 | 6.27k | static int HistogramCombineGreedy(VP8LHistogramSet* const image_histo) { |
899 | 6.27k | int ok = 0; |
900 | 6.27k | const int image_histo_size = image_histo->size; |
901 | 6.27k | int i, j; |
902 | 6.27k | VP8LHistogram** const histograms = image_histo->histograms; |
903 | | // Priority queue of histogram pairs. |
904 | 6.27k | 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 | 6.27k | if (!HistoQueueInit(&histo_queue, image_histo_size * image_histo_size)) { |
914 | 0 | goto End; |
915 | 0 | } |
916 | | |
917 | | // Initialize the queue. |
918 | 17.4k | for (i = 0; i < image_histo_size; ++i) { |
919 | 18.7k | for (j = i + 1; j < image_histo_size; ++j) { |
920 | 7.57k | HistoQueuePush(&histo_queue, histograms, i, j, 0); |
921 | 7.57k | } |
922 | 11.2k | } |
923 | | |
924 | 9.90k | while (histo_queue.size > 0) { |
925 | 3.63k | const int idx1 = histo_queue.queue[0].idx1; |
926 | 3.63k | const int idx2 = histo_queue.queue[0].idx2; |
927 | 3.63k | HistogramAdd(histograms[idx2], histograms[idx1], histograms[idx1]); |
928 | 3.63k | UpdateHistogramCost(histo_queue.queue[0].cost_combo, |
929 | 3.63k | histo_queue.queue[0].costs, histograms[idx1]); |
930 | | |
931 | | // Remove merged histogram. |
932 | 3.63k | HistogramSetRemoveHistogram(image_histo, idx2); |
933 | | |
934 | | // Remove pairs intersecting the just combined best pair. |
935 | 10.3k | for (i = 0; i < histo_queue.size;) { |
936 | 6.70k | HistogramPair* const p = histo_queue.queue + i; |
937 | 6.70k | if (p->idx1 == idx1 || p->idx2 == idx1 || p->idx1 == idx2 || |
938 | 6.67k | p->idx2 == idx2) { |
939 | 6.67k | HistoQueuePopPair(&histo_queue, p); |
940 | 6.67k | } else { |
941 | 33 | HistoQueueFixPair(image_histo->size, idx2, p); |
942 | 33 | HistoQueueUpdateHead(&histo_queue, p); |
943 | 33 | ++i; |
944 | 33 | } |
945 | 6.70k | } |
946 | | |
947 | | // Push new pairs formed with combined histogram to the queue. |
948 | 9.34k | for (i = 0; i < image_histo->size; ++i) { |
949 | 5.71k | if (i == idx1) continue; |
950 | 2.08k | HistoQueuePush(&histo_queue, image_histo->histograms, idx1, i, 0); |
951 | 2.08k | } |
952 | 3.63k | } |
953 | | |
954 | 6.27k | ok = 1; |
955 | | |
956 | 6.27k | End: |
957 | 6.27k | HistoQueueClear(&histo_queue); |
958 | 6.27k | return ok; |
959 | 6.27k | } |
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 | 6.55k | int* const do_greedy) { |
967 | 6.55k | int j, iter; |
968 | 6.55k | uint32_t seed = 1; |
969 | 6.55k | int tries_with_no_success = 0; |
970 | 6.55k | const int outer_iters = image_histo->size; |
971 | 6.55k | const int num_tries_no_success = outer_iters / 2; |
972 | 6.55k | 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 | 6.55k | HistoQueue histo_queue; |
977 | 6.55k | const int kHistoQueueSize = 9; |
978 | 6.55k | int ok = 0; |
979 | | |
980 | 6.55k | if (image_histo->size < min_cluster_size) { |
981 | 4.23k | *do_greedy = 1; |
982 | 4.23k | return 1; |
983 | 4.23k | } |
984 | | |
985 | 2.31k | if (!HistoQueueInit(&histo_queue, kHistoQueueSize)) goto End; |
986 | | |
987 | | // Collapse similar histograms in 'image_histo'. |
988 | 110k | for (iter = 0; iter < outer_iters && image_histo->size >= min_cluster_size && |
989 | 108k | ++tries_with_no_success < num_tries_no_success; |
990 | 108k | ++iter) { |
991 | 108k | int64_t best_cost = |
992 | 108k | (histo_queue.size == 0) ? 0 : histo_queue.queue[0].cost_diff; |
993 | 108k | int best_idx1 = -1, best_idx2 = 1; |
994 | 108k | 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 | 108k | const int num_tries = (image_histo->size) / 2; |
998 | | |
999 | | // Pick random samples. |
1000 | 4.44M | for (j = 0; image_histo->size >= 2 && j < num_tries; ++j) { |
1001 | 4.34M | int64_t curr_cost; |
1002 | | // Choose two different histograms at random and try to combine them. |
1003 | 4.34M | const uint32_t tmp = MyRand(&seed) % rand_range; |
1004 | 4.34M | uint32_t idx1 = tmp / (image_histo->size - 1); |
1005 | 4.34M | uint32_t idx2 = tmp % (image_histo->size - 1); |
1006 | 4.34M | if (idx2 >= idx1) ++idx2; |
1007 | | |
1008 | | // Calculate cost reduction on combination. |
1009 | 4.34M | curr_cost = |
1010 | 4.34M | HistoQueuePush(&histo_queue, histograms, idx1, idx2, best_cost); |
1011 | 4.34M | if (curr_cost < 0) { // found a better pair? |
1012 | 104k | best_cost = curr_cost; |
1013 | | // Empty the queue if we reached full capacity. |
1014 | 104k | if (histo_queue.size == histo_queue.max_size) break; |
1015 | 104k | } |
1016 | 4.34M | } |
1017 | 108k | if (histo_queue.size == 0) continue; |
1018 | | |
1019 | | // Get the best histograms. |
1020 | 99.0k | best_idx1 = histo_queue.queue[0].idx1; |
1021 | 99.0k | best_idx2 = histo_queue.queue[0].idx2; |
1022 | 99.0k | assert(best_idx1 < best_idx2); |
1023 | | // Merge the histograms and remove best_idx2 from the queue. |
1024 | 99.0k | HistogramAdd(histograms[best_idx2], histograms[best_idx1], |
1025 | 99.0k | histograms[best_idx1]); |
1026 | 99.0k | UpdateHistogramCost(histo_queue.queue[0].cost_combo, |
1027 | 99.0k | histo_queue.queue[0].costs, histograms[best_idx1]); |
1028 | 99.0k | 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 | 536k | for (j = 0; j < histo_queue.size;) { |
1032 | 437k | HistogramPair* const p = histo_queue.queue + j; |
1033 | 437k | const int is_idx1_best = p->idx1 == best_idx1 || p->idx1 == best_idx2; |
1034 | 437k | 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 | 437k | if (is_idx1_best && is_idx2_best) { |
1038 | 99.3k | HistoQueuePopPair(&histo_queue, p); |
1039 | 99.3k | continue; |
1040 | 99.3k | } |
1041 | | // Any pair containing one of the two best indices should only refer to |
1042 | | // best_idx1. Its cost should also be updated. |
1043 | 338k | if (is_idx1_best || is_idx2_best) { |
1044 | 43.9k | HistoQueueFixPair(best_idx2, best_idx1, p); |
1045 | | // Re-evaluate the cost of an updated pair. |
1046 | 43.9k | if (!HistoQueueUpdatePair(histograms[p->idx1], histograms[p->idx2], 0, |
1047 | 43.9k | p)) { |
1048 | 2.45k | HistoQueuePopPair(&histo_queue, p); |
1049 | 2.45k | continue; |
1050 | 2.45k | } |
1051 | 43.9k | } |
1052 | 335k | HistoQueueFixPair(image_histo->size, best_idx2, p); |
1053 | 335k | HistoQueueUpdateHead(&histo_queue, p); |
1054 | 335k | ++j; |
1055 | 335k | } |
1056 | 99.0k | tries_with_no_success = 0; |
1057 | 99.0k | } |
1058 | 2.31k | *do_greedy = (image_histo->size <= min_cluster_size); |
1059 | 2.31k | ok = 1; |
1060 | | |
1061 | 2.31k | End: |
1062 | 2.31k | HistoQueueClear(&histo_queue); |
1063 | 2.31k | return ok; |
1064 | 2.31k | } |
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 | 6.55k | uint32_t* const symbols) { |
1075 | 6.55k | int i; |
1076 | 6.55k | VP8LHistogram** const in_histo = in->histograms; |
1077 | 6.55k | VP8LHistogram** const out_histo = out->histograms; |
1078 | 6.55k | const int in_size = out->max_size; |
1079 | 6.55k | const int out_size = out->size; |
1080 | 6.55k | if (out_size > 1) { |
1081 | 737k | for (i = 0; i < in_size; ++i) { |
1082 | 736k | int best_out = 0; |
1083 | 736k | int64_t best_bits = WEBP_INT64_MAX; |
1084 | 736k | int k; |
1085 | 736k | if (in_histo[i] == NULL) { |
1086 | | // Arbitrarily set to the previous value if unused to help future LZ77. |
1087 | 412k | symbols[i] = symbols[i - 1]; |
1088 | 412k | continue; |
1089 | 412k | } |
1090 | 6.01M | for (k = 0; k < out_size; ++k) { |
1091 | 5.69M | int64_t cur_bits; |
1092 | 5.69M | if (HistogramAddThresh(out_histo[k], in_histo[i], best_bits, |
1093 | 5.69M | &cur_bits)) { |
1094 | 764k | best_bits = cur_bits; |
1095 | 764k | best_out = k; |
1096 | 764k | } |
1097 | 5.69M | } |
1098 | 323k | symbols[i] = best_out; |
1099 | 323k | } |
1100 | 5.40k | } else { |
1101 | 5.40k | assert(out_size == 1); |
1102 | 473k | for (i = 0; i < in_size; ++i) { |
1103 | 467k | symbols[i] = 0; |
1104 | 467k | } |
1105 | 5.40k | } |
1106 | | |
1107 | | // Recompute each out based on raw and symbols. |
1108 | 6.55k | VP8LHistogramSetClear(out); |
1109 | 6.55k | out->size = out_size; |
1110 | | |
1111 | 1.21M | for (i = 0; i < in_size; ++i) { |
1112 | 1.20M | int idx; |
1113 | 1.20M | if (in_histo[i] == NULL) continue; |
1114 | 446k | idx = symbols[i]; |
1115 | 446k | HistogramAdd(in_histo[i], out_histo[idx], out_histo[idx]); |
1116 | 446k | } |
1117 | 6.55k | } |
1118 | | |
1119 | 732 | static int32_t GetCombineCostFactor(int histo_size, int quality) { |
1120 | 732 | int32_t combine_cost_factor = 16; |
1121 | 732 | if (quality < 90) { |
1122 | 732 | if (histo_size > 256) combine_cost_factor /= 2; |
1123 | 732 | if (histo_size > 512) combine_cost_factor /= 2; |
1124 | 732 | if (histo_size > 1024) combine_cost_factor /= 2; |
1125 | 732 | if (quality <= 50) combine_cost_factor /= 2; |
1126 | 732 | } |
1127 | 732 | return combine_cost_factor; |
1128 | 732 | } |
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 | 6.55k | int* const percent) { |
1138 | 6.55k | const int histo_xsize = |
1139 | 6.55k | histogram_bits ? VP8LSubSampleSize(xsize, histogram_bits) : 1; |
1140 | 6.55k | const int histo_ysize = |
1141 | 6.55k | histogram_bits ? VP8LSubSampleSize(ysize, histogram_bits) : 1; |
1142 | 6.55k | const int image_histo_raw_size = histo_xsize * histo_ysize; |
1143 | 6.55k | VP8LHistogramSet* const orig_histo = |
1144 | 6.55k | 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 | 6.55k | const int entropy_combine_num_bins = low_effort ? NUM_PARTITIONS : BIN_SIZE; |
1149 | 6.55k | int entropy_combine; |
1150 | 6.55k | 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 | 6.55k | HistogramBuild(xsize, histogram_bits, refs, orig_histo); |
1157 | 6.55k | HistogramCopyAndAnalyze(orig_histo, image_histo); |
1158 | 6.55k | entropy_combine = |
1159 | 6.55k | (image_histo->size > entropy_combine_num_bins * 2) && (quality < 100); |
1160 | | |
1161 | 6.55k | if (entropy_combine) { |
1162 | 732 | const int32_t combine_cost_factor = |
1163 | 732 | GetCombineCostFactor(image_histo_raw_size, quality); |
1164 | | |
1165 | 732 | HistogramAnalyzeEntropyBin(image_histo, low_effort); |
1166 | | // Collapse histograms with similar entropy. |
1167 | 732 | HistogramCombineEntropyBin(image_histo, tmp_histo, entropy_combine_num_bins, |
1168 | 732 | combine_cost_factor, low_effort); |
1169 | 732 | } |
1170 | | |
1171 | | // Don't combine the histograms using stochastic and greedy heuristics for |
1172 | | // low-effort compression mode. |
1173 | 6.55k | if (!low_effort || !entropy_combine) { |
1174 | | // cubic ramp between 1 and MAX_HISTO_GREEDY: |
1175 | 6.55k | const int threshold_size = |
1176 | 6.55k | (int)(1 + DivRound(quality * quality * quality * (MAX_HISTO_GREEDY - 1), |
1177 | 6.55k | 100 * 100 * 100)); |
1178 | 6.55k | int do_greedy; |
1179 | 6.55k | 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 | 6.55k | if (do_greedy) { |
1184 | 6.27k | if (!HistogramCombineGreedy(image_histo)) { |
1185 | 0 | WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY); |
1186 | 0 | goto Error; |
1187 | 0 | } |
1188 | 6.27k | } |
1189 | 6.55k | } |
1190 | | |
1191 | | // Find the optimal map from original histograms to the final ones. |
1192 | 6.55k | HistogramRemap(orig_histo, image_histo, histogram_symbols); |
1193 | | |
1194 | 6.55k | if (!WebPReportProgress(pic, *percent + percent_range, percent)) { |
1195 | 0 | goto Error; |
1196 | 0 | } |
1197 | | |
1198 | 6.55k | Error: |
1199 | 6.55k | VP8LFreeHistogramSet(orig_histo); |
1200 | 6.55k | return (pic->error_code == VP8_ENC_OK); |
1201 | 6.55k | } |