OLD | NEW |
1 // Copyright 2012 Google Inc. All Rights Reserved. | 1 // Copyright 2012 Google Inc. All Rights Reserved. |
2 // | 2 // |
3 // Use of this source code is governed by a BSD-style license | 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 | 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 | 5 // tree. An additional intellectual property rights grant can be found |
6 // in the file PATENTS. All contributing project authors may | 6 // in the file PATENTS. All contributing project authors may |
7 // be found in the AUTHORS file in the root of the source tree. | 7 // be found in the AUTHORS file in the root of the source tree. |
8 // ----------------------------------------------------------------------------- | 8 // ----------------------------------------------------------------------------- |
9 // | 9 // |
10 // Author: Jyrki Alakuijala (jyrki@google.com) | 10 // Author: Jyrki Alakuijala (jyrki@google.com) |
11 // | 11 // |
12 #ifdef HAVE_CONFIG_H | 12 #ifdef HAVE_CONFIG_H |
13 #include "../webp/config.h" | 13 #include "../webp/config.h" |
14 #endif | 14 #endif |
15 | 15 |
16 #include <math.h> | 16 #include <math.h> |
17 | 17 |
18 #include "./backward_references.h" | 18 #include "./backward_references.h" |
19 #include "./histogram.h" | 19 #include "./histogram.h" |
20 #include "../dsp/lossless.h" | 20 #include "../dsp/lossless.h" |
21 #include "../utils/utils.h" | 21 #include "../utils/utils.h" |
22 | 22 |
23 #define ALIGN_CST 15 | |
24 #define DO_ALIGN(PTR) ((uintptr_t)((PTR) + ALIGN_CST) & ~ALIGN_CST) | |
25 | |
26 #define MAX_COST 1.e38 | 23 #define MAX_COST 1.e38 |
27 | 24 |
28 // Number of partitions for the three dominant (literal, red and blue) symbol | 25 // Number of partitions for the three dominant (literal, red and blue) symbol |
29 // costs. | 26 // costs. |
30 #define NUM_PARTITIONS 4 | 27 #define NUM_PARTITIONS 4 |
31 // The size of the bin-hash corresponding to the three dominant costs. | 28 // The size of the bin-hash corresponding to the three dominant costs. |
32 #define BIN_SIZE (NUM_PARTITIONS * NUM_PARTITIONS * NUM_PARTITIONS) | 29 #define BIN_SIZE (NUM_PARTITIONS * NUM_PARTITIONS * NUM_PARTITIONS) |
| 30 // Maximum number of histograms allowed in greedy combining algorithm. |
| 31 #define MAX_HISTO_GREEDY 100 |
33 | 32 |
34 static void HistogramClear(VP8LHistogram* const p) { | 33 static void HistogramClear(VP8LHistogram* const p) { |
35 uint32_t* const literal = p->literal_; | 34 uint32_t* const literal = p->literal_; |
36 const int cache_bits = p->palette_code_bits_; | 35 const int cache_bits = p->palette_code_bits_; |
37 const int histo_size = VP8LGetHistogramSize(cache_bits); | 36 const int histo_size = VP8LGetHistogramSize(cache_bits); |
38 memset(p, 0, histo_size); | 37 memset(p, 0, histo_size); |
39 p->palette_code_bits_ = cache_bits; | 38 p->palette_code_bits_ = cache_bits; |
40 p->literal_ = literal; | 39 p->literal_ = literal; |
41 } | 40 } |
42 | 41 |
| 42 // Swap two histogram pointers. |
| 43 static void HistogramSwap(VP8LHistogram** const A, VP8LHistogram** const B) { |
| 44 VP8LHistogram* const tmp = *A; |
| 45 *A = *B; |
| 46 *B = tmp; |
| 47 } |
| 48 |
43 static void HistogramCopy(const VP8LHistogram* const src, | 49 static void HistogramCopy(const VP8LHistogram* const src, |
44 VP8LHistogram* const dst) { | 50 VP8LHistogram* const dst) { |
45 uint32_t* const dst_literal = dst->literal_; | 51 uint32_t* const dst_literal = dst->literal_; |
46 const int dst_cache_bits = dst->palette_code_bits_; | 52 const int dst_cache_bits = dst->palette_code_bits_; |
47 const int histo_size = VP8LGetHistogramSize(dst_cache_bits); | 53 const int histo_size = VP8LGetHistogramSize(dst_cache_bits); |
48 assert(src->palette_code_bits_ == dst_cache_bits); | 54 assert(src->palette_code_bits_ == dst_cache_bits); |
49 memcpy(dst, src, histo_size); | 55 memcpy(dst, src, histo_size); |
50 dst->literal_ = dst_literal; | 56 dst->literal_ = dst_literal; |
51 } | 57 } |
52 | 58 |
(...skipping 46 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
99 histo->literal_ = (uint32_t*)(memory + sizeof(VP8LHistogram)); | 105 histo->literal_ = (uint32_t*)(memory + sizeof(VP8LHistogram)); |
100 VP8LHistogramInit(histo, cache_bits); | 106 VP8LHistogramInit(histo, cache_bits); |
101 return histo; | 107 return histo; |
102 } | 108 } |
103 | 109 |
104 VP8LHistogramSet* VP8LAllocateHistogramSet(int size, int cache_bits) { | 110 VP8LHistogramSet* VP8LAllocateHistogramSet(int size, int cache_bits) { |
105 int i; | 111 int i; |
106 VP8LHistogramSet* set; | 112 VP8LHistogramSet* set; |
107 const int histo_size = VP8LGetHistogramSize(cache_bits); | 113 const int histo_size = VP8LGetHistogramSize(cache_bits); |
108 const size_t total_size = | 114 const size_t total_size = |
109 sizeof(*set) + size * (sizeof(*set->histograms) + histo_size + ALIGN_CST); | 115 sizeof(*set) + size * (sizeof(*set->histograms) + |
| 116 histo_size + WEBP_ALIGN_CST); |
110 uint8_t* memory = (uint8_t*)WebPSafeMalloc(total_size, sizeof(*memory)); | 117 uint8_t* memory = (uint8_t*)WebPSafeMalloc(total_size, sizeof(*memory)); |
111 if (memory == NULL) return NULL; | 118 if (memory == NULL) return NULL; |
112 | 119 |
113 set = (VP8LHistogramSet*)memory; | 120 set = (VP8LHistogramSet*)memory; |
114 memory += sizeof(*set); | 121 memory += sizeof(*set); |
115 set->histograms = (VP8LHistogram**)memory; | 122 set->histograms = (VP8LHistogram**)memory; |
116 memory += size * sizeof(*set->histograms); | 123 memory += size * sizeof(*set->histograms); |
117 set->max_size = size; | 124 set->max_size = size; |
118 set->size = size; | 125 set->size = size; |
119 for (i = 0; i < size; ++i) { | 126 for (i = 0; i < size; ++i) { |
120 memory = (uint8_t*)DO_ALIGN(memory); | 127 memory = (uint8_t*)WEBP_ALIGN(memory); |
121 set->histograms[i] = (VP8LHistogram*)memory; | 128 set->histograms[i] = (VP8LHistogram*)memory; |
122 // literal_ won't necessary be aligned. | 129 // literal_ won't necessary be aligned. |
123 set->histograms[i]->literal_ = (uint32_t*)(memory + sizeof(VP8LHistogram)); | 130 set->histograms[i]->literal_ = (uint32_t*)(memory + sizeof(VP8LHistogram)); |
124 VP8LHistogramInit(set->histograms[i], cache_bits); | 131 VP8LHistogramInit(set->histograms[i], cache_bits); |
125 memory += histo_size; | 132 memory += histo_size; |
126 } | 133 } |
127 return set; | 134 return set; |
128 } | 135 } |
129 | 136 |
130 // ----------------------------------------------------------------------------- | 137 // ----------------------------------------------------------------------------- |
(...skipping 11 matching lines...) Expand all Loading... |
142 ++histo->literal_[literal_ix]; | 149 ++histo->literal_[literal_ix]; |
143 } else { | 150 } else { |
144 int code, extra_bits; | 151 int code, extra_bits; |
145 VP8LPrefixEncodeBits(PixOrCopyLength(v), &code, &extra_bits); | 152 VP8LPrefixEncodeBits(PixOrCopyLength(v), &code, &extra_bits); |
146 ++histo->literal_[NUM_LITERAL_CODES + code]; | 153 ++histo->literal_[NUM_LITERAL_CODES + code]; |
147 VP8LPrefixEncodeBits(PixOrCopyDistance(v), &code, &extra_bits); | 154 VP8LPrefixEncodeBits(PixOrCopyDistance(v), &code, &extra_bits); |
148 ++histo->distance_[code]; | 155 ++histo->distance_[code]; |
149 } | 156 } |
150 } | 157 } |
151 | 158 |
152 static WEBP_INLINE double BitsEntropyRefine(int nonzeros, int sum, int max_val, | 159 // ----------------------------------------------------------------------------- |
153 double retval) { | 160 // Entropy-related functions. |
| 161 |
| 162 static WEBP_INLINE double BitsEntropyRefine(const VP8LBitEntropy* entropy) { |
154 double mix; | 163 double mix; |
155 if (nonzeros < 5) { | 164 if (entropy->nonzeros < 5) { |
156 if (nonzeros <= 1) { | 165 if (entropy->nonzeros <= 1) { |
157 return 0; | 166 return 0; |
158 } | 167 } |
159 // Two symbols, they will be 0 and 1 in a Huffman code. | 168 // Two symbols, they will be 0 and 1 in a Huffman code. |
160 // Let's mix in a bit of entropy to favor good clustering when | 169 // Let's mix in a bit of entropy to favor good clustering when |
161 // distributions of these are combined. | 170 // distributions of these are combined. |
162 if (nonzeros == 2) { | 171 if (entropy->nonzeros == 2) { |
163 return 0.99 * sum + 0.01 * retval; | 172 return 0.99 * entropy->sum + 0.01 * entropy->entropy; |
164 } | 173 } |
165 // No matter what the entropy says, we cannot be better than min_limit | 174 // No matter what the entropy says, we cannot be better than min_limit |
166 // with Huffman coding. I am mixing a bit of entropy into the | 175 // with Huffman coding. I am mixing a bit of entropy into the |
167 // min_limit since it produces much better (~0.5 %) compression results | 176 // min_limit since it produces much better (~0.5 %) compression results |
168 // perhaps because of better entropy clustering. | 177 // perhaps because of better entropy clustering. |
169 if (nonzeros == 3) { | 178 if (entropy->nonzeros == 3) { |
170 mix = 0.95; | 179 mix = 0.95; |
171 } else { | 180 } else { |
172 mix = 0.7; // nonzeros == 4. | 181 mix = 0.7; // nonzeros == 4. |
173 } | 182 } |
174 } else { | 183 } else { |
175 mix = 0.627; | 184 mix = 0.627; |
176 } | 185 } |
177 | 186 |
178 { | 187 { |
179 double min_limit = 2 * sum - max_val; | 188 double min_limit = 2 * entropy->sum - entropy->max_val; |
180 min_limit = mix * min_limit + (1.0 - mix) * retval; | 189 min_limit = mix * min_limit + (1.0 - mix) * entropy->entropy; |
181 return (retval < min_limit) ? min_limit : retval; | 190 return (entropy->entropy < min_limit) ? min_limit : entropy->entropy; |
182 } | 191 } |
183 } | 192 } |
184 | 193 |
185 static double BitsEntropy(const uint32_t* const array, int n) { | 194 double VP8LBitsEntropy(const uint32_t* const array, int n, |
186 double retval = 0.; | 195 uint32_t* const trivial_symbol) { |
187 uint32_t sum = 0; | 196 VP8LBitEntropy entropy; |
188 int nonzeros = 0; | 197 VP8LBitsEntropyUnrefined(array, n, &entropy); |
189 uint32_t max_val = 0; | 198 if (trivial_symbol != NULL) { |
190 int i; | 199 *trivial_symbol = |
191 for (i = 0; i < n; ++i) { | 200 (entropy.nonzeros == 1) ? entropy.nonzero_code : VP8L_NON_TRIVIAL_SYM; |
192 if (array[i] != 0) { | |
193 sum += array[i]; | |
194 ++nonzeros; | |
195 retval -= VP8LFastSLog2(array[i]); | |
196 if (max_val < array[i]) { | |
197 max_val = array[i]; | |
198 } | |
199 } | |
200 } | 201 } |
201 retval += VP8LFastSLog2(sum); | |
202 return BitsEntropyRefine(nonzeros, sum, max_val, retval); | |
203 } | |
204 | 202 |
205 static double BitsEntropyCombined(const uint32_t* const X, | 203 return BitsEntropyRefine(&entropy); |
206 const uint32_t* const Y, int n) { | |
207 double retval = 0.; | |
208 int sum = 0; | |
209 int nonzeros = 0; | |
210 int max_val = 0; | |
211 int i; | |
212 for (i = 0; i < n; ++i) { | |
213 const int xy = X[i] + Y[i]; | |
214 if (xy != 0) { | |
215 sum += xy; | |
216 ++nonzeros; | |
217 retval -= VP8LFastSLog2(xy); | |
218 if (max_val < xy) { | |
219 max_val = xy; | |
220 } | |
221 } | |
222 } | |
223 retval += VP8LFastSLog2(sum); | |
224 return BitsEntropyRefine(nonzeros, sum, max_val, retval); | |
225 } | 204 } |
226 | 205 |
227 static double InitialHuffmanCost(void) { | 206 static double InitialHuffmanCost(void) { |
228 // Small bias because Huffman code length is typically not stored in | 207 // Small bias because Huffman code length is typically not stored in |
229 // full length. | 208 // full length. |
230 static const int kHuffmanCodeOfHuffmanCodeSize = CODE_LENGTH_CODES * 3; | 209 static const int kHuffmanCodeOfHuffmanCodeSize = CODE_LENGTH_CODES * 3; |
231 static const double kSmallBias = 9.1; | 210 static const double kSmallBias = 9.1; |
232 return kHuffmanCodeOfHuffmanCodeSize - kSmallBias; | 211 return kHuffmanCodeOfHuffmanCodeSize - kSmallBias; |
233 } | 212 } |
234 | 213 |
235 // Finalize the Huffman cost based on streak numbers and length type (<3 or >=3) | 214 // Finalize the Huffman cost based on streak numbers and length type (<3 or >=3) |
236 static double FinalHuffmanCost(const VP8LStreaks* const stats) { | 215 static double FinalHuffmanCost(const VP8LStreaks* const stats) { |
237 double retval = InitialHuffmanCost(); | 216 double retval = InitialHuffmanCost(); |
238 retval += stats->counts[0] * 1.5625 + 0.234375 * stats->streaks[0][1]; | 217 retval += stats->counts[0] * 1.5625 + 0.234375 * stats->streaks[0][1]; |
239 retval += stats->counts[1] * 2.578125 + 0.703125 * stats->streaks[1][1]; | 218 retval += stats->counts[1] * 2.578125 + 0.703125 * stats->streaks[1][1]; |
240 retval += 1.796875 * stats->streaks[0][0]; | 219 retval += 1.796875 * stats->streaks[0][0]; |
241 retval += 3.28125 * stats->streaks[1][0]; | 220 retval += 3.28125 * stats->streaks[1][0]; |
242 return retval; | 221 return retval; |
243 } | 222 } |
244 | 223 |
245 // Trampolines | 224 // Get the symbol entropy for the distribution 'population'. |
246 static double HuffmanCost(const uint32_t* const population, int length) { | 225 // Set 'trivial_sym', if there's only one symbol present in the distribution. |
247 const VP8LStreaks stats = VP8LHuffmanCostCount(population, length); | 226 static double PopulationCost(const uint32_t* const population, int length, |
248 return FinalHuffmanCost(&stats); | 227 uint32_t* const trivial_sym) { |
| 228 VP8LBitEntropy bit_entropy; |
| 229 VP8LStreaks stats; |
| 230 VP8LGetEntropyUnrefined(population, length, &bit_entropy, &stats); |
| 231 if (trivial_sym != NULL) { |
| 232 *trivial_sym = (bit_entropy.nonzeros == 1) ? bit_entropy.nonzero_code |
| 233 : VP8L_NON_TRIVIAL_SYM; |
| 234 } |
| 235 |
| 236 return BitsEntropyRefine(&bit_entropy) + FinalHuffmanCost(&stats); |
249 } | 237 } |
250 | 238 |
251 static double HuffmanCostCombined(const uint32_t* const X, | 239 static WEBP_INLINE double GetCombinedEntropy(const uint32_t* const X, |
252 const uint32_t* const Y, int length) { | 240 const uint32_t* const Y, |
253 const VP8LStreaks stats = VP8LHuffmanCostCombinedCount(X, Y, length); | 241 int length) { |
254 return FinalHuffmanCost(&stats); | 242 VP8LBitEntropy bit_entropy; |
255 } | 243 VP8LStreaks stats; |
| 244 VP8LGetCombinedEntropyUnrefined(X, Y, length, &bit_entropy, &stats); |
256 | 245 |
257 // Aggregated costs | 246 return BitsEntropyRefine(&bit_entropy) + FinalHuffmanCost(&stats); |
258 static double PopulationCost(const uint32_t* const population, int length) { | |
259 return BitsEntropy(population, length) + HuffmanCost(population, length); | |
260 } | |
261 | |
262 static double GetCombinedEntropy(const uint32_t* const X, | |
263 const uint32_t* const Y, int length) { | |
264 return BitsEntropyCombined(X, Y, length) + HuffmanCostCombined(X, Y, length); | |
265 } | 247 } |
266 | 248 |
267 // Estimates the Entropy + Huffman + other block overhead size cost. | 249 // Estimates the Entropy + Huffman + other block overhead size cost. |
268 double VP8LHistogramEstimateBits(const VP8LHistogram* const p) { | 250 double VP8LHistogramEstimateBits(const VP8LHistogram* const p) { |
269 return | 251 return |
270 PopulationCost(p->literal_, VP8LHistogramNumCodes(p->palette_code_bits_)) | 252 PopulationCost( |
271 + PopulationCost(p->red_, NUM_LITERAL_CODES) | 253 p->literal_, VP8LHistogramNumCodes(p->palette_code_bits_), NULL) |
272 + PopulationCost(p->blue_, NUM_LITERAL_CODES) | 254 + PopulationCost(p->red_, NUM_LITERAL_CODES, NULL) |
273 + PopulationCost(p->alpha_, NUM_LITERAL_CODES) | 255 + PopulationCost(p->blue_, NUM_LITERAL_CODES, NULL) |
274 + PopulationCost(p->distance_, NUM_DISTANCE_CODES) | 256 + PopulationCost(p->alpha_, NUM_LITERAL_CODES, NULL) |
| 257 + PopulationCost(p->distance_, NUM_DISTANCE_CODES, NULL) |
275 + VP8LExtraCost(p->literal_ + NUM_LITERAL_CODES, NUM_LENGTH_CODES) | 258 + VP8LExtraCost(p->literal_ + NUM_LITERAL_CODES, NUM_LENGTH_CODES) |
276 + VP8LExtraCost(p->distance_, NUM_DISTANCE_CODES); | 259 + VP8LExtraCost(p->distance_, NUM_DISTANCE_CODES); |
277 } | 260 } |
278 | |
279 double VP8LHistogramEstimateBitsBulk(const VP8LHistogram* const p) { | |
280 return | |
281 BitsEntropy(p->literal_, VP8LHistogramNumCodes(p->palette_code_bits_)) | |
282 + BitsEntropy(p->red_, NUM_LITERAL_CODES) | |
283 + BitsEntropy(p->blue_, NUM_LITERAL_CODES) | |
284 + BitsEntropy(p->alpha_, NUM_LITERAL_CODES) | |
285 + BitsEntropy(p->distance_, NUM_DISTANCE_CODES) | |
286 + VP8LExtraCost(p->literal_ + NUM_LITERAL_CODES, NUM_LENGTH_CODES) | |
287 + VP8LExtraCost(p->distance_, NUM_DISTANCE_CODES); | |
288 } | |
289 | 261 |
290 // ----------------------------------------------------------------------------- | 262 // ----------------------------------------------------------------------------- |
291 // Various histogram combine/cost-eval functions | 263 // Various histogram combine/cost-eval functions |
292 | 264 |
293 static int GetCombinedHistogramEntropy(const VP8LHistogram* const a, | 265 static int GetCombinedHistogramEntropy(const VP8LHistogram* const a, |
294 const VP8LHistogram* const b, | 266 const VP8LHistogram* const b, |
295 double cost_threshold, | 267 double cost_threshold, |
296 double* cost) { | 268 double* cost) { |
297 const int palette_code_bits = a->palette_code_bits_; | 269 const int palette_code_bits = a->palette_code_bits_; |
298 assert(a->palette_code_bits_ == b->palette_code_bits_); | 270 assert(a->palette_code_bits_ == b->palette_code_bits_); |
299 *cost += GetCombinedEntropy(a->literal_, b->literal_, | 271 *cost += GetCombinedEntropy(a->literal_, b->literal_, |
300 VP8LHistogramNumCodes(palette_code_bits)); | 272 VP8LHistogramNumCodes(palette_code_bits)); |
301 *cost += VP8LExtraCostCombined(a->literal_ + NUM_LITERAL_CODES, | 273 *cost += VP8LExtraCostCombined(a->literal_ + NUM_LITERAL_CODES, |
302 b->literal_ + NUM_LITERAL_CODES, | 274 b->literal_ + NUM_LITERAL_CODES, |
303 NUM_LENGTH_CODES); | 275 NUM_LENGTH_CODES); |
304 if (*cost > cost_threshold) return 0; | 276 if (*cost > cost_threshold) return 0; |
305 | 277 |
306 *cost += GetCombinedEntropy(a->red_, b->red_, NUM_LITERAL_CODES); | 278 *cost += GetCombinedEntropy(a->red_, b->red_, NUM_LITERAL_CODES); |
307 if (*cost > cost_threshold) return 0; | 279 if (*cost > cost_threshold) return 0; |
308 | 280 |
309 *cost += GetCombinedEntropy(a->blue_, b->blue_, NUM_LITERAL_CODES); | 281 *cost += GetCombinedEntropy(a->blue_, b->blue_, NUM_LITERAL_CODES); |
310 if (*cost > cost_threshold) return 0; | 282 if (*cost > cost_threshold) return 0; |
311 | 283 |
312 *cost += GetCombinedEntropy(a->alpha_, b->alpha_, NUM_LITERAL_CODES); | 284 *cost += GetCombinedEntropy(a->alpha_, b->alpha_, NUM_LITERAL_CODES); |
313 if (*cost > cost_threshold) return 0; | 285 if (*cost > cost_threshold) return 0; |
314 | 286 |
315 *cost += GetCombinedEntropy(a->distance_, b->distance_, NUM_DISTANCE_CODES); | 287 *cost += GetCombinedEntropy(a->distance_, b->distance_, NUM_DISTANCE_CODES); |
316 *cost += VP8LExtraCostCombined(a->distance_, b->distance_, | 288 *cost += |
317 NUM_DISTANCE_CODES); | 289 VP8LExtraCostCombined(a->distance_, b->distance_, NUM_DISTANCE_CODES); |
318 if (*cost > cost_threshold) return 0; | 290 if (*cost > cost_threshold) return 0; |
319 | 291 |
320 return 1; | 292 return 1; |
321 } | 293 } |
322 | 294 |
323 // Performs out = a + b, computing the cost C(a+b) - C(a) - C(b) while comparing | 295 // Performs out = a + b, computing the cost C(a+b) - C(a) - C(b) while comparing |
324 // to the threshold value 'cost_threshold'. The score returned is | 296 // to the threshold value 'cost_threshold'. The score returned is |
325 // Score = C(a+b) - C(a) - C(b), where C(a) + C(b) is known and fixed. | 297 // Score = C(a+b) - C(a) - C(b), where C(a) + C(b) is known and fixed. |
326 // Since the previous score passed is 'cost_threshold', we only need to compare | 298 // Since the previous score passed is 'cost_threshold', we only need to compare |
327 // the partial cost against 'cost_threshold + C(a) + C(b)' to possibly bail-out | 299 // the partial cost against 'cost_threshold + C(a) + C(b)' to possibly bail-out |
328 // early. | 300 // early. |
329 static double HistogramAddEval(const VP8LHistogram* const a, | 301 static double HistogramAddEval(const VP8LHistogram* const a, |
330 const VP8LHistogram* const b, | 302 const VP8LHistogram* const b, |
331 VP8LHistogram* const out, | 303 VP8LHistogram* const out, |
332 double cost_threshold) { | 304 double cost_threshold) { |
333 double cost = 0; | 305 double cost = 0; |
334 const double sum_cost = a->bit_cost_ + b->bit_cost_; | 306 const double sum_cost = a->bit_cost_ + b->bit_cost_; |
335 cost_threshold += sum_cost; | 307 cost_threshold += sum_cost; |
336 | 308 |
337 if (GetCombinedHistogramEntropy(a, b, cost_threshold, &cost)) { | 309 if (GetCombinedHistogramEntropy(a, b, cost_threshold, &cost)) { |
338 VP8LHistogramAdd(a, b, out); | 310 VP8LHistogramAdd(a, b, out); |
339 out->bit_cost_ = cost; | 311 out->bit_cost_ = cost; |
340 out->palette_code_bits_ = a->palette_code_bits_; | 312 out->palette_code_bits_ = a->palette_code_bits_; |
| 313 out->trivial_symbol_ = (a->trivial_symbol_ == b->trivial_symbol_) ? |
| 314 a->trivial_symbol_ : VP8L_NON_TRIVIAL_SYM; |
341 } | 315 } |
342 | 316 |
343 return cost - sum_cost; | 317 return cost - sum_cost; |
344 } | 318 } |
345 | 319 |
346 // Same as HistogramAddEval(), except that the resulting histogram | 320 // Same as HistogramAddEval(), except that the resulting histogram |
347 // is not stored. Only the cost C(a+b) - C(a) is evaluated. We omit | 321 // is not stored. Only the cost C(a+b) - C(a) is evaluated. We omit |
348 // the term C(b) which is constant over all the evaluations. | 322 // the term C(b) which is constant over all the evaluations. |
349 static double HistogramAddThresh(const VP8LHistogram* const a, | 323 static double HistogramAddThresh(const VP8LHistogram* const a, |
350 const VP8LHistogram* const b, | 324 const VP8LHistogram* const b, |
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
382 const VP8LHistogram* const h, DominantCostRange* const c) { | 356 const VP8LHistogram* const h, DominantCostRange* const c) { |
383 if (c->literal_max_ < h->literal_cost_) c->literal_max_ = h->literal_cost_; | 357 if (c->literal_max_ < h->literal_cost_) c->literal_max_ = h->literal_cost_; |
384 if (c->literal_min_ > h->literal_cost_) c->literal_min_ = h->literal_cost_; | 358 if (c->literal_min_ > h->literal_cost_) c->literal_min_ = h->literal_cost_; |
385 if (c->red_max_ < h->red_cost_) c->red_max_ = h->red_cost_; | 359 if (c->red_max_ < h->red_cost_) c->red_max_ = h->red_cost_; |
386 if (c->red_min_ > h->red_cost_) c->red_min_ = h->red_cost_; | 360 if (c->red_min_ > h->red_cost_) c->red_min_ = h->red_cost_; |
387 if (c->blue_max_ < h->blue_cost_) c->blue_max_ = h->blue_cost_; | 361 if (c->blue_max_ < h->blue_cost_) c->blue_max_ = h->blue_cost_; |
388 if (c->blue_min_ > h->blue_cost_) c->blue_min_ = h->blue_cost_; | 362 if (c->blue_min_ > h->blue_cost_) c->blue_min_ = h->blue_cost_; |
389 } | 363 } |
390 | 364 |
391 static void UpdateHistogramCost(VP8LHistogram* const h) { | 365 static void UpdateHistogramCost(VP8LHistogram* const h) { |
392 const double alpha_cost = PopulationCost(h->alpha_, NUM_LITERAL_CODES); | 366 uint32_t alpha_sym, red_sym, blue_sym; |
| 367 const double alpha_cost = |
| 368 PopulationCost(h->alpha_, NUM_LITERAL_CODES, &alpha_sym); |
393 const double distance_cost = | 369 const double distance_cost = |
394 PopulationCost(h->distance_, NUM_DISTANCE_CODES) + | 370 PopulationCost(h->distance_, NUM_DISTANCE_CODES, NULL) + |
395 VP8LExtraCost(h->distance_, NUM_DISTANCE_CODES); | 371 VP8LExtraCost(h->distance_, NUM_DISTANCE_CODES); |
396 const int num_codes = VP8LHistogramNumCodes(h->palette_code_bits_); | 372 const int num_codes = VP8LHistogramNumCodes(h->palette_code_bits_); |
397 h->literal_cost_ = PopulationCost(h->literal_, num_codes) + | 373 h->literal_cost_ = PopulationCost(h->literal_, num_codes, NULL) + |
398 VP8LExtraCost(h->literal_ + NUM_LITERAL_CODES, | 374 VP8LExtraCost(h->literal_ + NUM_LITERAL_CODES, |
399 NUM_LENGTH_CODES); | 375 NUM_LENGTH_CODES); |
400 h->red_cost_ = PopulationCost(h->red_, NUM_LITERAL_CODES); | 376 h->red_cost_ = PopulationCost(h->red_, NUM_LITERAL_CODES, &red_sym); |
401 h->blue_cost_ = PopulationCost(h->blue_, NUM_LITERAL_CODES); | 377 h->blue_cost_ = PopulationCost(h->blue_, NUM_LITERAL_CODES, &blue_sym); |
402 h->bit_cost_ = h->literal_cost_ + h->red_cost_ + h->blue_cost_ + | 378 h->bit_cost_ = h->literal_cost_ + h->red_cost_ + h->blue_cost_ + |
403 alpha_cost + distance_cost; | 379 alpha_cost + distance_cost; |
| 380 if ((alpha_sym | red_sym | blue_sym) == VP8L_NON_TRIVIAL_SYM) { |
| 381 h->trivial_symbol_ = VP8L_NON_TRIVIAL_SYM; |
| 382 } else { |
| 383 h->trivial_symbol_ = |
| 384 ((uint32_t)alpha_sym << 24) | (red_sym << 16) | (blue_sym << 0); |
| 385 } |
404 } | 386 } |
405 | 387 |
406 static int GetBinIdForEntropy(double min, double max, double val) { | 388 static int GetBinIdForEntropy(double min, double max, double val) { |
407 const double range = max - min + 1e-6; | 389 const double range = max - min + 1e-6; |
408 const double delta = val - min; | 390 const double delta = val - min; |
409 return (int)(NUM_PARTITIONS * delta / range); | 391 return (int)(NUM_PARTITIONS * delta / range); |
410 } | 392 } |
411 | 393 |
412 // TODO(vikasa): Evaluate, if there's any correlation between red & blue. | 394 static int GetHistoBinIndexLowEffort( |
| 395 const VP8LHistogram* const h, const DominantCostRange* const c) { |
| 396 const int bin_id = GetBinIdForEntropy(c->literal_min_, c->literal_max_, |
| 397 h->literal_cost_); |
| 398 assert(bin_id < NUM_PARTITIONS); |
| 399 return bin_id; |
| 400 } |
| 401 |
413 static int GetHistoBinIndex( | 402 static int GetHistoBinIndex( |
414 const VP8LHistogram* const h, const DominantCostRange* const c) { | 403 const VP8LHistogram* const h, const DominantCostRange* const c) { |
415 const int bin_id = | 404 const int bin_id = |
416 GetBinIdForEntropy(c->blue_min_, c->blue_max_, h->blue_cost_) + | 405 GetBinIdForEntropy(c->blue_min_, c->blue_max_, h->blue_cost_) + |
417 NUM_PARTITIONS * GetBinIdForEntropy(c->red_min_, c->red_max_, | 406 NUM_PARTITIONS * GetBinIdForEntropy(c->red_min_, c->red_max_, |
418 h->red_cost_) + | 407 h->red_cost_) + |
419 NUM_PARTITIONS * NUM_PARTITIONS * GetBinIdForEntropy(c->literal_min_, | 408 NUM_PARTITIONS * NUM_PARTITIONS * GetBinIdForEntropy(c->literal_min_, |
420 c->literal_max_, | 409 c->literal_max_, |
421 h->literal_cost_); | 410 h->literal_cost_); |
422 assert(bin_id < BIN_SIZE); | 411 assert(bin_id < BIN_SIZE); |
423 return bin_id; | 412 return bin_id; |
424 } | 413 } |
425 | 414 |
426 // Construct the histograms from backward references. | 415 // Construct the histograms from backward references. |
427 static void HistogramBuild( | 416 static void HistogramBuild( |
428 int xsize, int histo_bits, const VP8LBackwardRefs* const backward_refs, | 417 int xsize, int histo_bits, const VP8LBackwardRefs* const backward_refs, |
429 VP8LHistogramSet* const image_histo) { | 418 VP8LHistogramSet* const image_histo) { |
430 int x = 0, y = 0; | 419 int x = 0, y = 0; |
431 const int histo_xsize = VP8LSubSampleSize(xsize, histo_bits); | 420 const int histo_xsize = VP8LSubSampleSize(xsize, histo_bits); |
432 VP8LHistogram** const histograms = image_histo->histograms; | 421 VP8LHistogram** const histograms = image_histo->histograms; |
433 VP8LRefsCursor c = VP8LRefsCursorInit(backward_refs); | 422 VP8LRefsCursor c = VP8LRefsCursorInit(backward_refs); |
434 assert(histo_bits > 0); | 423 assert(histo_bits > 0); |
435 // Construct the Histo from a given backward references. | |
436 while (VP8LRefsCursorOk(&c)) { | 424 while (VP8LRefsCursorOk(&c)) { |
437 const PixOrCopy* const v = c.cur_pos; | 425 const PixOrCopy* const v = c.cur_pos; |
438 const int ix = (y >> histo_bits) * histo_xsize + (x >> histo_bits); | 426 const int ix = (y >> histo_bits) * histo_xsize + (x >> histo_bits); |
439 VP8LHistogramAddSinglePixOrCopy(histograms[ix], v); | 427 VP8LHistogramAddSinglePixOrCopy(histograms[ix], v); |
440 x += PixOrCopyLength(v); | 428 x += PixOrCopyLength(v); |
441 while (x >= xsize) { | 429 while (x >= xsize) { |
442 x -= xsize; | 430 x -= xsize; |
443 ++y; | 431 ++y; |
444 } | 432 } |
445 VP8LRefsCursorNext(&c); | 433 VP8LRefsCursorNext(&c); |
(...skipping 10 matching lines...) Expand all Loading... |
456 for (i = 0; i < histo_size; ++i) { | 444 for (i = 0; i < histo_size; ++i) { |
457 VP8LHistogram* const histo = orig_histograms[i]; | 445 VP8LHistogram* const histo = orig_histograms[i]; |
458 UpdateHistogramCost(histo); | 446 UpdateHistogramCost(histo); |
459 // Copy histograms from orig_histo[] to image_histo[]. | 447 // Copy histograms from orig_histo[] to image_histo[]. |
460 HistogramCopy(histo, histograms[i]); | 448 HistogramCopy(histo, histograms[i]); |
461 } | 449 } |
462 } | 450 } |
463 | 451 |
464 // Partition histograms to different entropy bins for three dominant (literal, | 452 // Partition histograms to different entropy bins for three dominant (literal, |
465 // red and blue) symbol costs and compute the histogram aggregate bit_cost. | 453 // red and blue) symbol costs and compute the histogram aggregate bit_cost. |
466 static void HistogramAnalyzeEntropyBin( | 454 static void HistogramAnalyzeEntropyBin(VP8LHistogramSet* const image_histo, |
467 VP8LHistogramSet* const image_histo, int16_t* const bin_map) { | 455 int16_t* const bin_map, int low_effort) { |
468 int i; | 456 int i; |
469 VP8LHistogram** const histograms = image_histo->histograms; | 457 VP8LHistogram** const histograms = image_histo->histograms; |
470 const int histo_size = image_histo->size; | 458 const int histo_size = image_histo->size; |
471 const int bin_depth = histo_size + 1; | 459 const int bin_depth = histo_size + 1; |
472 DominantCostRange cost_range; | 460 DominantCostRange cost_range; |
473 DominantCostRangeInit(&cost_range); | 461 DominantCostRangeInit(&cost_range); |
474 | 462 |
475 // Analyze the dominant (literal, red and blue) entropy costs. | 463 // Analyze the dominant (literal, red and blue) entropy costs. |
476 for (i = 0; i < histo_size; ++i) { | 464 for (i = 0; i < histo_size; ++i) { |
477 VP8LHistogram* const histo = histograms[i]; | 465 VP8LHistogram* const histo = histograms[i]; |
478 UpdateDominantCostRange(histo, &cost_range); | 466 UpdateDominantCostRange(histo, &cost_range); |
479 } | 467 } |
480 | 468 |
481 // bin-hash histograms on three of the dominant (literal, red and blue) | 469 // bin-hash histograms on three of the dominant (literal, red and blue) |
482 // symbol costs. | 470 // symbol costs. |
483 for (i = 0; i < histo_size; ++i) { | 471 for (i = 0; i < histo_size; ++i) { |
484 int num_histos; | 472 int num_histos; |
485 VP8LHistogram* const histo = histograms[i]; | 473 VP8LHistogram* const histo = histograms[i]; |
486 const int16_t bin_id = (int16_t)GetHistoBinIndex(histo, &cost_range); | 474 const int16_t bin_id = low_effort ? |
| 475 (int16_t)GetHistoBinIndexLowEffort(histo, &cost_range) : |
| 476 (int16_t)GetHistoBinIndex(histo, &cost_range); |
487 const int bin_offset = bin_id * bin_depth; | 477 const int bin_offset = bin_id * bin_depth; |
488 // bin_map[n][0] for every bin 'n' maintains the counter for the number of | 478 // bin_map[n][0] for every bin 'n' maintains the counter for the number of |
489 // histograms in that bin. | 479 // histograms in that bin. |
490 // Get and increment the num_histos in that bin. | 480 // Get and increment the num_histos in that bin. |
491 num_histos = ++bin_map[bin_offset]; | 481 num_histos = ++bin_map[bin_offset]; |
492 assert(bin_offset + num_histos < bin_depth * BIN_SIZE); | 482 assert(bin_offset + num_histos < bin_depth * BIN_SIZE); |
493 // Add histogram i'th index at num_histos (last) position in the bin_map. | 483 // Add histogram i'th index at num_histos (last) position in the bin_map. |
494 bin_map[bin_offset + num_histos] = i; | 484 bin_map[bin_offset + num_histos] = i; |
495 } | 485 } |
496 } | 486 } |
497 | 487 |
498 // Compact the histogram set by moving the valid one left in the set to the | 488 // Compact the histogram set by removing unused entries. |
499 // head and moving the ones that have been merged to other histograms towards | |
500 // the end. | |
501 // TODO(vikasa): Evaluate if this method can be avoided by altering the code | |
502 // logic of HistogramCombineEntropyBin main loop. | |
503 static void HistogramCompactBins(VP8LHistogramSet* const image_histo) { | 489 static void HistogramCompactBins(VP8LHistogramSet* const image_histo) { |
504 int start = 0; | |
505 int end = image_histo->size - 1; | |
506 VP8LHistogram** const histograms = image_histo->histograms; | 490 VP8LHistogram** const histograms = image_histo->histograms; |
507 while (start < end) { | 491 int i, j; |
508 while (start <= end && histograms[start] != NULL && | 492 |
509 histograms[start]->bit_cost_ != 0.) { | 493 for (i = 0, j = 0; i < image_histo->size; ++i) { |
510 ++start; | 494 if (histograms[i] != NULL && histograms[i]->bit_cost_ != 0.) { |
511 } | 495 if (j < i) { |
512 while (start <= end && histograms[end]->bit_cost_ == 0.) { | 496 histograms[j] = histograms[i]; |
513 histograms[end] = NULL; | 497 histograms[i] = NULL; |
514 --end; | 498 } |
515 } | 499 ++j; |
516 if (start < end) { | |
517 assert(histograms[start] != NULL); | |
518 assert(histograms[end] != NULL); | |
519 HistogramCopy(histograms[end], histograms[start]); | |
520 histograms[end] = NULL; | |
521 --end; | |
522 } | 500 } |
523 } | 501 } |
524 image_histo->size = end + 1; | 502 image_histo->size = j; |
525 } | 503 } |
526 | 504 |
527 static void HistogramCombineEntropyBin(VP8LHistogramSet* const image_histo, | 505 static VP8LHistogram* HistogramCombineEntropyBin( |
528 VP8LHistogram* const histos, | 506 VP8LHistogramSet* const image_histo, |
529 int16_t* const bin_map, int bin_depth, | 507 VP8LHistogram* cur_combo, |
530 double combine_cost_factor) { | 508 int16_t* const bin_map, int bin_depth, int num_bins, |
| 509 double combine_cost_factor, int low_effort) { |
531 int bin_id; | 510 int bin_id; |
532 VP8LHistogram* cur_combo = histos; | |
533 VP8LHistogram** const histograms = image_histo->histograms; | 511 VP8LHistogram** const histograms = image_histo->histograms; |
534 | 512 |
535 for (bin_id = 0; bin_id < BIN_SIZE; ++bin_id) { | 513 for (bin_id = 0; bin_id < num_bins; ++bin_id) { |
536 const int bin_offset = bin_id * bin_depth; | 514 const int bin_offset = bin_id * bin_depth; |
537 const int num_histos = bin_map[bin_offset]; | 515 const int num_histos = bin_map[bin_offset]; |
538 const int idx1 = bin_map[bin_offset + 1]; | 516 const int idx1 = bin_map[bin_offset + 1]; |
| 517 int num_combine_failures = 0; |
539 int n; | 518 int n; |
540 for (n = 2; n <= num_histos; ++n) { | 519 for (n = 2; n <= num_histos; ++n) { |
541 const int idx2 = bin_map[bin_offset + n]; | 520 const int idx2 = bin_map[bin_offset + n]; |
542 const double bit_cost_idx2 = histograms[idx2]->bit_cost_; | 521 if (low_effort) { |
543 if (bit_cost_idx2 > 0.) { | 522 // Merge all histograms with the same bin index, irrespective of cost of |
544 const double bit_cost_thresh = -bit_cost_idx2 * combine_cost_factor; | 523 // the merged histograms. |
545 const double curr_cost_diff = | 524 VP8LHistogramAdd(histograms[idx1], histograms[idx2], histograms[idx1]); |
546 HistogramAddEval(histograms[idx1], histograms[idx2], | 525 histograms[idx2]->bit_cost_ = 0.; |
547 cur_combo, bit_cost_thresh); | 526 } else { |
548 if (curr_cost_diff < bit_cost_thresh) { | 527 const double bit_cost_idx2 = histograms[idx2]->bit_cost_; |
549 HistogramCopy(cur_combo, histograms[idx1]); | 528 if (bit_cost_idx2 > 0.) { |
550 histograms[idx2]->bit_cost_ = 0.; | 529 const double bit_cost_thresh = -bit_cost_idx2 * combine_cost_factor; |
| 530 const double curr_cost_diff = |
| 531 HistogramAddEval(histograms[idx1], histograms[idx2], |
| 532 cur_combo, bit_cost_thresh); |
| 533 if (curr_cost_diff < bit_cost_thresh) { |
| 534 // Try to merge two histograms only if the combo is a trivial one or |
| 535 // the two candidate histograms are already non-trivial. |
| 536 // For some images, 'try_combine' turns out to be false for a lot of |
| 537 // histogram pairs. In that case, we fallback to combining |
| 538 // histograms as usual to avoid increasing the header size. |
| 539 const int try_combine = |
| 540 (cur_combo->trivial_symbol_ != VP8L_NON_TRIVIAL_SYM) || |
| 541 ((histograms[idx1]->trivial_symbol_ == VP8L_NON_TRIVIAL_SYM) && |
| 542 (histograms[idx2]->trivial_symbol_ == VP8L_NON_TRIVIAL_SYM)); |
| 543 const int max_combine_failures = 32; |
| 544 if (try_combine || (num_combine_failures >= max_combine_failures)) { |
| 545 HistogramSwap(&cur_combo, &histograms[idx1]); |
| 546 histograms[idx2]->bit_cost_ = 0.; |
| 547 } else { |
| 548 ++num_combine_failures; |
| 549 } |
| 550 } |
551 } | 551 } |
552 } | 552 } |
553 } | 553 } |
| 554 if (low_effort) { |
| 555 // Update the bit_cost for the merged histograms (per bin index). |
| 556 UpdateHistogramCost(histograms[idx1]); |
| 557 } |
554 } | 558 } |
555 HistogramCompactBins(image_histo); | 559 HistogramCompactBins(image_histo); |
| 560 return cur_combo; |
556 } | 561 } |
557 | 562 |
558 static uint32_t MyRand(uint32_t *seed) { | 563 static uint32_t MyRand(uint32_t *seed) { |
559 *seed *= 16807U; | 564 *seed *= 16807U; |
560 if (*seed == 0) { | 565 if (*seed == 0) { |
561 *seed = 1; | 566 *seed = 1; |
562 } | 567 } |
563 return *seed; | 568 return *seed; |
564 } | 569 } |
565 | 570 |
566 static void HistogramCombine(VP8LHistogramSet* const image_histo, | 571 // ----------------------------------------------------------------------------- |
567 VP8LHistogramSet* const histos, int quality) { | 572 // Histogram pairs priority queue |
| 573 |
| 574 // Pair of histograms. Negative idx1 value means that pair is out-of-date. |
| 575 typedef struct { |
| 576 int idx1; |
| 577 int idx2; |
| 578 double cost_diff; |
| 579 double cost_combo; |
| 580 } HistogramPair; |
| 581 |
| 582 typedef struct { |
| 583 HistogramPair* queue; |
| 584 int size; |
| 585 int max_size; |
| 586 } HistoQueue; |
| 587 |
| 588 static int HistoQueueInit(HistoQueue* const histo_queue, const int max_index) { |
| 589 histo_queue->size = 0; |
| 590 // max_index^2 for the queue size is safe. If you look at |
| 591 // HistogramCombineGreedy, and imagine that UpdateQueueFront always pushes |
| 592 // data to the queue, you insert at most: |
| 593 // - max_index*(max_index-1)/2 (the first two for loops) |
| 594 // - max_index - 1 in the last for loop at the first iteration of the while |
| 595 // loop, max_index - 2 at the second iteration ... therefore |
| 596 // max_index*(max_index-1)/2 overall too |
| 597 histo_queue->max_size = max_index * max_index; |
| 598 // We allocate max_size + 1 because the last element at index "size" is |
| 599 // used as temporary data (and it could be up to max_size). |
| 600 histo_queue->queue = WebPSafeMalloc(histo_queue->max_size + 1, |
| 601 sizeof(*histo_queue->queue)); |
| 602 return histo_queue->queue != NULL; |
| 603 } |
| 604 |
| 605 static void HistoQueueClear(HistoQueue* const histo_queue) { |
| 606 assert(histo_queue != NULL); |
| 607 WebPSafeFree(histo_queue->queue); |
| 608 } |
| 609 |
| 610 static void SwapHistogramPairs(HistogramPair *p1, |
| 611 HistogramPair *p2) { |
| 612 const HistogramPair tmp = *p1; |
| 613 *p1 = *p2; |
| 614 *p2 = tmp; |
| 615 } |
| 616 |
| 617 // Given a valid priority queue in range [0, queue_size) this function checks |
| 618 // whether histo_queue[queue_size] should be accepted and swaps it with the |
| 619 // front if it is smaller. Otherwise, it leaves it as is. |
| 620 static void UpdateQueueFront(HistoQueue* const histo_queue) { |
| 621 if (histo_queue->queue[histo_queue->size].cost_diff >= 0) return; |
| 622 |
| 623 if (histo_queue->queue[histo_queue->size].cost_diff < |
| 624 histo_queue->queue[0].cost_diff) { |
| 625 SwapHistogramPairs(histo_queue->queue, |
| 626 histo_queue->queue + histo_queue->size); |
| 627 } |
| 628 ++histo_queue->size; |
| 629 |
| 630 // We cannot add more elements than the capacity. |
| 631 // The allocation adds an extra element to the official capacity so that |
| 632 // histo_queue->queue[histo_queue->max_size] is read/written within bound. |
| 633 assert(histo_queue->size <= histo_queue->max_size); |
| 634 } |
| 635 |
| 636 // ----------------------------------------------------------------------------- |
| 637 |
| 638 static void PreparePair(VP8LHistogram** histograms, int idx1, int idx2, |
| 639 HistogramPair* const pair, |
| 640 VP8LHistogram* const histos) { |
| 641 if (idx1 > idx2) { |
| 642 const int tmp = idx2; |
| 643 idx2 = idx1; |
| 644 idx1 = tmp; |
| 645 } |
| 646 pair->idx1 = idx1; |
| 647 pair->idx2 = idx2; |
| 648 pair->cost_diff = |
| 649 HistogramAddEval(histograms[idx1], histograms[idx2], histos, 0); |
| 650 pair->cost_combo = histos->bit_cost_; |
| 651 } |
| 652 |
| 653 // Combines histograms by continuously choosing the one with the highest cost |
| 654 // reduction. |
| 655 static int HistogramCombineGreedy(VP8LHistogramSet* const image_histo, |
| 656 VP8LHistogram* const histos) { |
| 657 int ok = 0; |
| 658 int image_histo_size = image_histo->size; |
| 659 int i, j; |
| 660 VP8LHistogram** const histograms = image_histo->histograms; |
| 661 // Indexes of remaining histograms. |
| 662 int* const clusters = WebPSafeMalloc(image_histo_size, sizeof(*clusters)); |
| 663 // Priority queue of histogram pairs. |
| 664 HistoQueue histo_queue; |
| 665 |
| 666 if (!HistoQueueInit(&histo_queue, image_histo_size) || clusters == NULL) { |
| 667 goto End; |
| 668 } |
| 669 |
| 670 for (i = 0; i < image_histo_size; ++i) { |
| 671 // Initialize clusters indexes. |
| 672 clusters[i] = i; |
| 673 for (j = i + 1; j < image_histo_size; ++j) { |
| 674 // Initialize positions array. |
| 675 PreparePair(histograms, i, j, &histo_queue.queue[histo_queue.size], |
| 676 histos); |
| 677 UpdateQueueFront(&histo_queue); |
| 678 } |
| 679 } |
| 680 |
| 681 while (image_histo_size > 1 && histo_queue.size > 0) { |
| 682 HistogramPair* copy_to; |
| 683 const int idx1 = histo_queue.queue[0].idx1; |
| 684 const int idx2 = histo_queue.queue[0].idx2; |
| 685 VP8LHistogramAdd(histograms[idx2], histograms[idx1], histograms[idx1]); |
| 686 histograms[idx1]->bit_cost_ = histo_queue.queue[0].cost_combo; |
| 687 // Remove merged histogram. |
| 688 for (i = 0; i + 1 < image_histo_size; ++i) { |
| 689 if (clusters[i] >= idx2) { |
| 690 clusters[i] = clusters[i + 1]; |
| 691 } |
| 692 } |
| 693 --image_histo_size; |
| 694 |
| 695 // Remove pairs intersecting the just combined best pair. This will |
| 696 // therefore pop the head of the queue. |
| 697 copy_to = histo_queue.queue; |
| 698 for (i = 0; i < histo_queue.size; ++i) { |
| 699 HistogramPair* const p = histo_queue.queue + i; |
| 700 if (p->idx1 == idx1 || p->idx2 == idx1 || |
| 701 p->idx1 == idx2 || p->idx2 == idx2) { |
| 702 // Do not copy the invalid pair. |
| 703 continue; |
| 704 } |
| 705 if (p->cost_diff < histo_queue.queue[0].cost_diff) { |
| 706 // Replace the top of the queue if we found better. |
| 707 SwapHistogramPairs(histo_queue.queue, p); |
| 708 } |
| 709 SwapHistogramPairs(copy_to, p); |
| 710 ++copy_to; |
| 711 } |
| 712 histo_queue.size = (int)(copy_to - histo_queue.queue); |
| 713 |
| 714 // Push new pairs formed with combined histogram to the queue. |
| 715 for (i = 0; i < image_histo_size; ++i) { |
| 716 if (clusters[i] != idx1) { |
| 717 PreparePair(histograms, idx1, clusters[i], |
| 718 &histo_queue.queue[histo_queue.size], histos); |
| 719 UpdateQueueFront(&histo_queue); |
| 720 } |
| 721 } |
| 722 } |
| 723 // Move remaining histograms to the beginning of the array. |
| 724 for (i = 0; i < image_histo_size; ++i) { |
| 725 if (i != clusters[i]) { // swap the two histograms |
| 726 HistogramSwap(&histograms[i], &histograms[clusters[i]]); |
| 727 } |
| 728 } |
| 729 |
| 730 image_histo->size = image_histo_size; |
| 731 ok = 1; |
| 732 |
| 733 End: |
| 734 WebPSafeFree(clusters); |
| 735 HistoQueueClear(&histo_queue); |
| 736 return ok; |
| 737 } |
| 738 |
| 739 static VP8LHistogram* HistogramCombineStochastic( |
| 740 VP8LHistogramSet* const image_histo, |
| 741 VP8LHistogram* tmp_histo, |
| 742 VP8LHistogram* best_combo, |
| 743 int quality, int min_cluster_size) { |
568 int iter; | 744 int iter; |
569 uint32_t seed = 0; | 745 uint32_t seed = 0; |
570 int tries_with_no_success = 0; | 746 int tries_with_no_success = 0; |
571 int image_histo_size = image_histo->size; | 747 int image_histo_size = image_histo->size; |
572 const int iter_mult = (quality < 25) ? 2 : 2 + (quality - 25) / 8; | 748 const int iter_mult = (quality < 25) ? 2 : 2 + (quality - 25) / 8; |
573 const int outer_iters = image_histo_size * iter_mult; | 749 const int outer_iters = image_histo_size * iter_mult; |
574 const int num_pairs = image_histo_size / 2; | 750 const int num_pairs = image_histo_size / 2; |
575 const int num_tries_no_success = outer_iters / 2; | 751 const int num_tries_no_success = outer_iters / 2; |
576 const int min_cluster_size = 2; | |
577 VP8LHistogram** const histograms = image_histo->histograms; | 752 VP8LHistogram** const histograms = image_histo->histograms; |
578 VP8LHistogram* cur_combo = histos->histograms[0]; // trial histogram | |
579 VP8LHistogram* best_combo = histos->histograms[1]; // best histogram so far | |
580 | 753 |
581 // Collapse similar histograms in 'image_histo'. | 754 // Collapse similar histograms in 'image_histo'. |
| 755 ++min_cluster_size; |
582 for (iter = 0; | 756 for (iter = 0; |
583 iter < outer_iters && image_histo_size >= min_cluster_size; | 757 iter < outer_iters && image_histo_size >= min_cluster_size; |
584 ++iter) { | 758 ++iter) { |
585 double best_cost_diff = 0.; | 759 double best_cost_diff = 0.; |
586 int best_idx1 = -1, best_idx2 = 1; | 760 int best_idx1 = -1, best_idx2 = 1; |
587 int j; | 761 int j; |
588 const int num_tries = | 762 const int num_tries = |
589 (num_pairs < image_histo_size) ? num_pairs : image_histo_size; | 763 (num_pairs < image_histo_size) ? num_pairs : image_histo_size; |
590 seed += iter; | 764 seed += iter; |
591 for (j = 0; j < num_tries; ++j) { | 765 for (j = 0; j < num_tries; ++j) { |
592 double curr_cost_diff; | 766 double curr_cost_diff; |
593 // Choose two histograms at random and try to combine them. | 767 // Choose two histograms at random and try to combine them. |
594 const uint32_t idx1 = MyRand(&seed) % image_histo_size; | 768 const uint32_t idx1 = MyRand(&seed) % image_histo_size; |
595 const uint32_t tmp = (j & 7) + 1; | 769 const uint32_t tmp = (j & 7) + 1; |
596 const uint32_t diff = | 770 const uint32_t diff = |
597 (tmp < 3) ? tmp : MyRand(&seed) % (image_histo_size - 1); | 771 (tmp < 3) ? tmp : MyRand(&seed) % (image_histo_size - 1); |
598 const uint32_t idx2 = (idx1 + diff + 1) % image_histo_size; | 772 const uint32_t idx2 = (idx1 + diff + 1) % image_histo_size; |
599 if (idx1 == idx2) { | 773 if (idx1 == idx2) { |
600 continue; | 774 continue; |
601 } | 775 } |
602 | 776 |
603 // Calculate cost reduction on combining. | 777 // Calculate cost reduction on combining. |
604 curr_cost_diff = HistogramAddEval(histograms[idx1], histograms[idx2], | 778 curr_cost_diff = HistogramAddEval(histograms[idx1], histograms[idx2], |
605 cur_combo, best_cost_diff); | 779 tmp_histo, best_cost_diff); |
606 if (curr_cost_diff < best_cost_diff) { // found a better pair? | 780 if (curr_cost_diff < best_cost_diff) { // found a better pair? |
607 { // swap cur/best combo histograms | 781 HistogramSwap(&best_combo, &tmp_histo); |
608 VP8LHistogram* const tmp_histo = cur_combo; | |
609 cur_combo = best_combo; | |
610 best_combo = tmp_histo; | |
611 } | |
612 best_cost_diff = curr_cost_diff; | 782 best_cost_diff = curr_cost_diff; |
613 best_idx1 = idx1; | 783 best_idx1 = idx1; |
614 best_idx2 = idx2; | 784 best_idx2 = idx2; |
615 } | 785 } |
616 } | 786 } |
617 | 787 |
618 if (best_idx1 >= 0) { | 788 if (best_idx1 >= 0) { |
619 HistogramCopy(best_combo, histograms[best_idx1]); | 789 HistogramSwap(&best_combo, &histograms[best_idx1]); |
620 // swap best_idx2 slot with last one (which is now unused) | 790 // swap best_idx2 slot with last one (which is now unused) |
621 --image_histo_size; | 791 --image_histo_size; |
622 if (best_idx2 != image_histo_size) { | 792 if (best_idx2 != image_histo_size) { |
623 HistogramCopy(histograms[image_histo_size], histograms[best_idx2]); | 793 HistogramSwap(&histograms[image_histo_size], &histograms[best_idx2]); |
624 histograms[image_histo_size] = NULL; | 794 histograms[image_histo_size] = NULL; |
625 } | 795 } |
626 tries_with_no_success = 0; | 796 tries_with_no_success = 0; |
627 } | 797 } |
628 if (++tries_with_no_success >= num_tries_no_success) { | 798 if (++tries_with_no_success >= num_tries_no_success) { |
629 break; | 799 break; |
630 } | 800 } |
631 } | 801 } |
632 image_histo->size = image_histo_size; | 802 image_histo->size = image_histo_size; |
| 803 return best_combo; |
633 } | 804 } |
634 | 805 |
635 // ----------------------------------------------------------------------------- | 806 // ----------------------------------------------------------------------------- |
636 // Histogram refinement | 807 // Histogram refinement |
637 | 808 |
638 // Find the best 'out' histogram for each of the 'in' histograms. | 809 // Find the best 'out' histogram for each of the 'in' histograms. |
639 // Note: we assume that out[]->bit_cost_ is already up-to-date. | 810 // Note: we assume that out[]->bit_cost_ is already up-to-date. |
640 static void HistogramRemap(const VP8LHistogramSet* const orig_histo, | 811 static void HistogramRemap(const VP8LHistogramSet* const orig_histo, |
641 const VP8LHistogramSet* const image_histo, | 812 const VP8LHistogramSet* const image_histo, |
642 uint16_t* const symbols) { | 813 uint16_t* const symbols) { |
643 int i; | 814 int i; |
644 VP8LHistogram** const orig_histograms = orig_histo->histograms; | 815 VP8LHistogram** const orig_histograms = orig_histo->histograms; |
645 VP8LHistogram** const histograms = image_histo->histograms; | 816 VP8LHistogram** const histograms = image_histo->histograms; |
646 for (i = 0; i < orig_histo->size; ++i) { | 817 const int orig_histo_size = orig_histo->size; |
647 int best_out = 0; | 818 const int image_histo_size = image_histo->size; |
648 double best_bits = | 819 if (image_histo_size > 1) { |
649 HistogramAddThresh(histograms[0], orig_histograms[i], MAX_COST); | 820 for (i = 0; i < orig_histo_size; ++i) { |
650 int k; | 821 int best_out = 0; |
651 for (k = 1; k < image_histo->size; ++k) { | 822 double best_bits = |
652 const double cur_bits = | 823 HistogramAddThresh(histograms[0], orig_histograms[i], MAX_COST); |
653 HistogramAddThresh(histograms[k], orig_histograms[i], best_bits); | 824 int k; |
654 if (cur_bits < best_bits) { | 825 for (k = 1; k < image_histo_size; ++k) { |
655 best_bits = cur_bits; | 826 const double cur_bits = |
656 best_out = k; | 827 HistogramAddThresh(histograms[k], orig_histograms[i], best_bits); |
| 828 if (cur_bits < best_bits) { |
| 829 best_bits = cur_bits; |
| 830 best_out = k; |
| 831 } |
657 } | 832 } |
| 833 symbols[i] = best_out; |
658 } | 834 } |
659 symbols[i] = best_out; | 835 } else { |
| 836 assert(image_histo_size == 1); |
| 837 for (i = 0; i < orig_histo_size; ++i) { |
| 838 symbols[i] = 0; |
| 839 } |
660 } | 840 } |
661 | 841 |
662 // Recompute each out based on raw and symbols. | 842 // Recompute each out based on raw and symbols. |
663 for (i = 0; i < image_histo->size; ++i) { | 843 for (i = 0; i < image_histo_size; ++i) { |
664 HistogramClear(histograms[i]); | 844 HistogramClear(histograms[i]); |
665 } | 845 } |
666 | 846 |
667 for (i = 0; i < orig_histo->size; ++i) { | 847 for (i = 0; i < orig_histo_size; ++i) { |
668 const int idx = symbols[i]; | 848 const int idx = symbols[i]; |
669 VP8LHistogramAdd(orig_histograms[i], histograms[idx], histograms[idx]); | 849 VP8LHistogramAdd(orig_histograms[i], histograms[idx], histograms[idx]); |
670 } | 850 } |
671 } | 851 } |
672 | 852 |
673 static double GetCombineCostFactor(int histo_size, int quality) { | 853 static double GetCombineCostFactor(int histo_size, int quality) { |
674 double combine_cost_factor = 0.16; | 854 double combine_cost_factor = 0.16; |
675 if (histo_size > 256) combine_cost_factor /= 2.; | 855 if (quality < 90) { |
676 if (histo_size > 512) combine_cost_factor /= 2.; | 856 if (histo_size > 256) combine_cost_factor /= 2.; |
677 if (histo_size > 1024) combine_cost_factor /= 2.; | 857 if (histo_size > 512) combine_cost_factor /= 2.; |
678 if (quality <= 50) combine_cost_factor /= 2.; | 858 if (histo_size > 1024) combine_cost_factor /= 2.; |
| 859 if (quality <= 50) combine_cost_factor /= 2.; |
| 860 } |
679 return combine_cost_factor; | 861 return combine_cost_factor; |
680 } | 862 } |
681 | 863 |
682 int VP8LGetHistoImageSymbols(int xsize, int ysize, | 864 int VP8LGetHistoImageSymbols(int xsize, int ysize, |
683 const VP8LBackwardRefs* const refs, | 865 const VP8LBackwardRefs* const refs, |
684 int quality, int histo_bits, int cache_bits, | 866 int quality, int low_effort, |
| 867 int histo_bits, int cache_bits, |
685 VP8LHistogramSet* const image_histo, | 868 VP8LHistogramSet* const image_histo, |
| 869 VP8LHistogramSet* const tmp_histos, |
686 uint16_t* const histogram_symbols) { | 870 uint16_t* const histogram_symbols) { |
687 int ok = 0; | 871 int ok = 0; |
688 const int histo_xsize = histo_bits ? VP8LSubSampleSize(xsize, histo_bits) : 1; | 872 const int histo_xsize = histo_bits ? VP8LSubSampleSize(xsize, histo_bits) : 1; |
689 const int histo_ysize = histo_bits ? VP8LSubSampleSize(ysize, histo_bits) : 1; | 873 const int histo_ysize = histo_bits ? VP8LSubSampleSize(ysize, histo_bits) : 1; |
690 const int image_histo_raw_size = histo_xsize * histo_ysize; | 874 const int image_histo_raw_size = histo_xsize * histo_ysize; |
| 875 const int entropy_combine_num_bins = low_effort ? NUM_PARTITIONS : BIN_SIZE; |
691 | 876 |
692 // The bin_map for every bin follows following semantics: | 877 // The bin_map for every bin follows following semantics: |
693 // bin_map[n][0] = num_histo; // The number of histograms in that bin. | 878 // bin_map[n][0] = num_histo; // The number of histograms in that bin. |
694 // bin_map[n][1] = index of first histogram in that bin; | 879 // bin_map[n][1] = index of first histogram in that bin; |
695 // bin_map[n][num_histo] = index of last histogram in that bin; | 880 // bin_map[n][num_histo] = index of last histogram in that bin; |
696 // bin_map[n][num_histo + 1] ... bin_map[n][bin_depth - 1] = un-used indices. | 881 // bin_map[n][num_histo + 1] ... bin_map[n][bin_depth - 1] = unused indices. |
697 const int bin_depth = image_histo_raw_size + 1; | 882 const int bin_depth = image_histo_raw_size + 1; |
698 int16_t* bin_map = NULL; | 883 int16_t* bin_map = NULL; |
699 VP8LHistogramSet* const histos = VP8LAllocateHistogramSet(2, cache_bits); | |
700 VP8LHistogramSet* const orig_histo = | 884 VP8LHistogramSet* const orig_histo = |
701 VP8LAllocateHistogramSet(image_histo_raw_size, cache_bits); | 885 VP8LAllocateHistogramSet(image_histo_raw_size, cache_bits); |
| 886 VP8LHistogram* cur_combo; |
| 887 const int entropy_combine = |
| 888 (orig_histo->size > entropy_combine_num_bins * 2) && (quality < 100); |
702 | 889 |
703 if (orig_histo == NULL || histos == NULL) { | 890 if (orig_histo == NULL) goto Error; |
704 goto Error; | |
705 } | |
706 | 891 |
707 // Don't attempt linear bin-partition heuristic for: | 892 // Don't attempt linear bin-partition heuristic for: |
708 // histograms of small sizes, as bin_map will be very sparse and; | 893 // histograms of small sizes, as bin_map will be very sparse and; |
709 // Higher qualities (> 90), to preserve the compression gains at those | 894 // Maximum quality (q==100), to preserve the compression gains at that level. |
710 // quality settings. | 895 if (entropy_combine) { |
711 if (orig_histo->size > 2 * BIN_SIZE && quality < 90) { | 896 const int bin_map_size = bin_depth * entropy_combine_num_bins; |
712 const int bin_map_size = bin_depth * BIN_SIZE; | |
713 bin_map = (int16_t*)WebPSafeCalloc(bin_map_size, sizeof(*bin_map)); | 897 bin_map = (int16_t*)WebPSafeCalloc(bin_map_size, sizeof(*bin_map)); |
714 if (bin_map == NULL) goto Error; | 898 if (bin_map == NULL) goto Error; |
715 } | 899 } |
716 | 900 |
717 // Construct the histograms from backward references. | 901 // Construct the histograms from backward references. |
718 HistogramBuild(xsize, histo_bits, refs, orig_histo); | 902 HistogramBuild(xsize, histo_bits, refs, orig_histo); |
719 // Copies the histograms and computes its bit_cost. | 903 // Copies the histograms and computes its bit_cost. |
720 HistogramCopyAndAnalyze(orig_histo, image_histo); | 904 HistogramCopyAndAnalyze(orig_histo, image_histo); |
721 | 905 |
722 if (bin_map != NULL) { | 906 cur_combo = tmp_histos->histograms[1]; // pick up working slot |
| 907 if (entropy_combine) { |
723 const double combine_cost_factor = | 908 const double combine_cost_factor = |
724 GetCombineCostFactor(image_histo_raw_size, quality); | 909 GetCombineCostFactor(image_histo_raw_size, quality); |
725 HistogramAnalyzeEntropyBin(orig_histo, bin_map); | 910 HistogramAnalyzeEntropyBin(orig_histo, bin_map, low_effort); |
726 // Collapse histograms with similar entropy. | 911 // Collapse histograms with similar entropy. |
727 HistogramCombineEntropyBin(image_histo, histos->histograms[0], | 912 cur_combo = HistogramCombineEntropyBin(image_histo, cur_combo, bin_map, |
728 bin_map, bin_depth, combine_cost_factor); | 913 bin_depth, entropy_combine_num_bins, |
| 914 combine_cost_factor, low_effort); |
729 } | 915 } |
730 | 916 |
731 // Collapse similar histograms by random histogram-pair compares. | 917 // Don't combine the histograms using stochastic and greedy heuristics for |
732 HistogramCombine(image_histo, histos, quality); | 918 // low-effort compression mode. |
| 919 if (!low_effort || !entropy_combine) { |
| 920 const float x = quality / 100.f; |
| 921 // cubic ramp between 1 and MAX_HISTO_GREEDY: |
| 922 const int threshold_size = (int)(1 + (x * x * x) * (MAX_HISTO_GREEDY - 1)); |
| 923 cur_combo = HistogramCombineStochastic(image_histo, |
| 924 tmp_histos->histograms[0], |
| 925 cur_combo, quality, threshold_size); |
| 926 if ((image_histo->size <= threshold_size) && |
| 927 !HistogramCombineGreedy(image_histo, cur_combo)) { |
| 928 goto Error; |
| 929 } |
| 930 } |
733 | 931 |
| 932 // TODO(vikasa): Optimize HistogramRemap for low-effort compression mode also. |
734 // Find the optimal map from original histograms to the final ones. | 933 // Find the optimal map from original histograms to the final ones. |
735 HistogramRemap(orig_histo, image_histo, histogram_symbols); | 934 HistogramRemap(orig_histo, image_histo, histogram_symbols); |
736 | 935 |
737 ok = 1; | 936 ok = 1; |
738 | 937 |
739 Error: | 938 Error: |
740 WebPSafeFree(bin_map); | 939 WebPSafeFree(bin_map); |
741 VP8LFreeHistogramSet(orig_histo); | 940 VP8LFreeHistogramSet(orig_histo); |
742 VP8LFreeHistogramSet(histos); | |
743 return ok; | 941 return ok; |
744 } | 942 } |
OLD | NEW |