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