1
// Copyright 2012 Google Inc. All Rights Reserved.
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
// -----------------------------------------------------------------------------
10
// Author: Jyrki Alakuijala (jyrki@google.com)
19
#include "./backward_references.h"
20
#include "./histogram.h"
21
#include "../dsp/lossless.h"
22
#include "../utils/utils.h"
24
static void HistogramClear(VP8LHistogram* const p) {
25
memset(p->literal_, 0, sizeof(p->literal_));
26
memset(p->red_, 0, sizeof(p->red_));
27
memset(p->blue_, 0, sizeof(p->blue_));
28
memset(p->alpha_, 0, sizeof(p->alpha_));
29
memset(p->distance_, 0, sizeof(p->distance_));
33
void VP8LHistogramStoreRefs(const VP8LBackwardRefs* const refs,
34
VP8LHistogram* const histo) {
36
for (i = 0; i < refs->size; ++i) {
37
VP8LHistogramAddSinglePixOrCopy(histo, &refs->refs[i]);
41
void VP8LHistogramCreate(VP8LHistogram* const p,
42
const VP8LBackwardRefs* const refs,
43
int palette_code_bits) {
44
if (palette_code_bits >= 0) {
45
p->palette_code_bits_ = palette_code_bits;
48
VP8LHistogramStoreRefs(refs, p);
51
void VP8LHistogramInit(VP8LHistogram* const p, int palette_code_bits) {
52
p->palette_code_bits_ = palette_code_bits;
56
VP8LHistogramSet* VP8LAllocateHistogramSet(int size, int cache_bits) {
58
VP8LHistogramSet* set;
60
const uint64_t total_size = sizeof(*set)
61
+ (uint64_t)size * sizeof(*set->histograms)
62
+ (uint64_t)size * sizeof(**set->histograms);
63
uint8_t* memory = (uint8_t*)WebPSafeMalloc(total_size, sizeof(*memory));
64
if (memory == NULL) return NULL;
66
set = (VP8LHistogramSet*)memory;
67
memory += sizeof(*set);
68
set->histograms = (VP8LHistogram**)memory;
69
memory += size * sizeof(*set->histograms);
70
bulk = (VP8LHistogram*)memory;
73
for (i = 0; i < size; ++i) {
74
set->histograms[i] = bulk + i;
75
VP8LHistogramInit(set->histograms[i], cache_bits);
80
// -----------------------------------------------------------------------------
82
void VP8LHistogramAddSinglePixOrCopy(VP8LHistogram* const histo,
83
const PixOrCopy* const v) {
84
if (PixOrCopyIsLiteral(v)) {
85
++histo->alpha_[PixOrCopyLiteral(v, 3)];
86
++histo->red_[PixOrCopyLiteral(v, 2)];
87
++histo->literal_[PixOrCopyLiteral(v, 1)];
88
++histo->blue_[PixOrCopyLiteral(v, 0)];
89
} else if (PixOrCopyIsCacheIdx(v)) {
90
int literal_ix = 256 + NUM_LENGTH_CODES + PixOrCopyCacheIdx(v);
91
++histo->literal_[literal_ix];
93
int code, extra_bits_count, extra_bits_value;
94
PrefixEncode(PixOrCopyLength(v),
95
&code, &extra_bits_count, &extra_bits_value);
96
++histo->literal_[256 + code];
97
PrefixEncode(PixOrCopyDistance(v),
98
&code, &extra_bits_count, &extra_bits_value);
99
++histo->distance_[code];
103
static double BitsEntropy(const int* const array, int n) {
110
for (i = 0; i < n; ++i) {
114
retval -= VP8LFastSLog2(array[i]);
115
if (max_val < array[i]) {
120
retval += VP8LFastSLog2(sum);
126
// Two symbols, they will be 0 and 1 in a Huffman code.
127
// Let's mix in a bit of entropy to favor good clustering when
128
// distributions of these are combined.
130
return 0.99 * sum + 0.01 * retval;
132
// No matter what the entropy says, we cannot be better than min_limit
133
// with Huffman coding. I am mixing a bit of entropy into the
134
// min_limit since it produces much better (~0.5 %) compression results
135
// perhaps because of better entropy clustering.
139
mix = 0.7; // nonzeros == 4.
146
double min_limit = 2 * sum - max_val;
147
min_limit = mix * min_limit + (1.0 - mix) * retval;
148
return (retval < min_limit) ? min_limit : retval;
152
// Returns the cost encode the rle-encoded entropy code.
153
// The constants in this function are experimental.
154
static double HuffmanCost(const int* const population, int length) {
155
// Small bias because Huffman code length is typically not stored in
157
static const int kHuffmanCodeOfHuffmanCodeSize = CODE_LENGTH_CODES * 3;
158
static const double kSmallBias = 9.1;
159
double retval = kHuffmanCodeOfHuffmanCodeSize - kSmallBias;
162
for (; i < length - 1; ++i) {
164
if (population[i] == population[i + 1]) {
168
// population[i] points now to the symbol in the streak of same values.
170
if (population[i] == 0) {
171
retval += 1.5625 + 0.234375 * streak;
173
retval += 2.578125 + 0.703125 * streak;
176
if (population[i] == 0) {
177
retval += 1.796875 * streak;
179
retval += 3.28125 * streak;
184
if (i == length - 1) {
186
goto last_streak_hack;
191
static double PopulationCost(const int* const population, int length) {
192
return BitsEntropy(population, length) + HuffmanCost(population, length);
195
static double ExtraCost(const int* const population, int length) {
198
for (i = 2; i < length - 2; ++i) cost += (i >> 1) * population[i + 2];
202
// Estimates the Entropy + Huffman + other block overhead size cost.
203
double VP8LHistogramEstimateBits(const VP8LHistogram* const p) {
204
return PopulationCost(p->literal_, VP8LHistogramNumCodes(p))
205
+ PopulationCost(p->red_, 256)
206
+ PopulationCost(p->blue_, 256)
207
+ PopulationCost(p->alpha_, 256)
208
+ PopulationCost(p->distance_, NUM_DISTANCE_CODES)
209
+ ExtraCost(p->literal_ + 256, NUM_LENGTH_CODES)
210
+ ExtraCost(p->distance_, NUM_DISTANCE_CODES);
213
double VP8LHistogramEstimateBitsBulk(const VP8LHistogram* const p) {
214
return BitsEntropy(p->literal_, VP8LHistogramNumCodes(p))
215
+ BitsEntropy(p->red_, 256)
216
+ BitsEntropy(p->blue_, 256)
217
+ BitsEntropy(p->alpha_, 256)
218
+ BitsEntropy(p->distance_, NUM_DISTANCE_CODES)
219
+ ExtraCost(p->literal_ + 256, NUM_LENGTH_CODES)
220
+ ExtraCost(p->distance_, NUM_DISTANCE_CODES);
223
// -----------------------------------------------------------------------------
224
// Various histogram combine/cost-eval functions
226
// Adds 'in' histogram to 'out'
227
static void HistogramAdd(const VP8LHistogram* const in,
228
VP8LHistogram* const out) {
230
for (i = 0; i < PIX_OR_COPY_CODES_MAX; ++i) {
231
out->literal_[i] += in->literal_[i];
233
for (i = 0; i < NUM_DISTANCE_CODES; ++i) {
234
out->distance_[i] += in->distance_[i];
236
for (i = 0; i < 256; ++i) {
237
out->red_[i] += in->red_[i];
238
out->blue_[i] += in->blue_[i];
239
out->alpha_[i] += in->alpha_[i];
243
// Performs out = a + b, computing the cost C(a+b) - C(a) - C(b) while comparing
244
// to the threshold value 'cost_threshold'. The score returned is
245
// Score = C(a+b) - C(a) - C(b), where C(a) + C(b) is known and fixed.
246
// Since the previous score passed is 'cost_threshold', we only need to compare
247
// the partial cost against 'cost_threshold + C(a) + C(b)' to possibly bail-out
249
static double HistogramAddEval(const VP8LHistogram* const a,
250
const VP8LHistogram* const b,
251
VP8LHistogram* const out,
252
double cost_threshold) {
254
const double sum_cost = a->bit_cost_ + b->bit_cost_;
257
cost_threshold += sum_cost;
259
// palette_code_bits_ is part of the cost evaluation for literal_.
260
// TODO(skal): remove/simplify this palette_code_bits_?
261
out->palette_code_bits_ =
262
(a->palette_code_bits_ > b->palette_code_bits_) ? a->palette_code_bits_ :
263
b->palette_code_bits_;
264
for (i = 0; i < PIX_OR_COPY_CODES_MAX; ++i) {
265
out->literal_[i] = a->literal_[i] + b->literal_[i];
267
cost += PopulationCost(out->literal_, VP8LHistogramNumCodes(out));
268
cost += ExtraCost(out->literal_ + 256, NUM_LENGTH_CODES);
269
if (cost > cost_threshold) return cost;
271
for (i = 0; i < 256; ++i) out->red_[i] = a->red_[i] + b->red_[i];
272
cost += PopulationCost(out->red_, 256);
273
if (cost > cost_threshold) return cost;
275
for (i = 0; i < 256; ++i) out->blue_[i] = a->blue_[i] + b->blue_[i];
276
cost += PopulationCost(out->blue_, 256);
277
if (cost > cost_threshold) return cost;
279
for (i = 0; i < NUM_DISTANCE_CODES; ++i) {
280
out->distance_[i] = a->distance_[i] + b->distance_[i];
282
cost += PopulationCost(out->distance_, NUM_DISTANCE_CODES);
283
cost += ExtraCost(out->distance_, NUM_DISTANCE_CODES);
284
if (cost > cost_threshold) return cost;
286
for (i = 0; i < 256; ++i) out->alpha_[i] = a->alpha_[i] + b->alpha_[i];
287
cost += PopulationCost(out->alpha_, 256);
289
out->bit_cost_ = cost;
290
return cost - sum_cost;
293
// Same as HistogramAddEval(), except that the resulting histogram
294
// is not stored. Only the cost C(a+b) - C(a) is evaluated. We omit
295
// the term C(b) which is constant over all the evaluations.
296
static double HistogramAddThresh(const VP8LHistogram* const a,
297
const VP8LHistogram* const b,
298
double cost_threshold) {
299
int tmp[PIX_OR_COPY_CODES_MAX]; // <= max storage we'll need
301
double cost = -a->bit_cost_;
303
for (i = 0; i < PIX_OR_COPY_CODES_MAX; ++i) {
304
tmp[i] = a->literal_[i] + b->literal_[i];
306
// note that the tests are ordered so that the usually largest
307
// cost shares come first.
308
cost += PopulationCost(tmp, VP8LHistogramNumCodes(a));
309
cost += ExtraCost(tmp + 256, NUM_LENGTH_CODES);
310
if (cost > cost_threshold) return cost;
312
for (i = 0; i < 256; ++i) tmp[i] = a->red_[i] + b->red_[i];
313
cost += PopulationCost(tmp, 256);
314
if (cost > cost_threshold) return cost;
316
for (i = 0; i < 256; ++i) tmp[i] = a->blue_[i] + b->blue_[i];
317
cost += PopulationCost(tmp, 256);
318
if (cost > cost_threshold) return cost;
320
for (i = 0; i < NUM_DISTANCE_CODES; ++i) {
321
tmp[i] = a->distance_[i] + b->distance_[i];
323
cost += PopulationCost(tmp, NUM_DISTANCE_CODES);
324
cost += ExtraCost(tmp, NUM_DISTANCE_CODES);
325
if (cost > cost_threshold) return cost;
327
for (i = 0; i < 256; ++i) tmp[i] = a->alpha_[i] + b->alpha_[i];
328
cost += PopulationCost(tmp, 256);
333
// -----------------------------------------------------------------------------
335
static void HistogramBuildImage(int xsize, int histo_bits,
336
const VP8LBackwardRefs* const backward_refs,
337
VP8LHistogramSet* const image) {
340
const int histo_xsize = VP8LSubSampleSize(xsize, histo_bits);
341
VP8LHistogram** const histograms = image->histograms;
342
assert(histo_bits > 0);
343
for (i = 0; i < backward_refs->size; ++i) {
344
const PixOrCopy* const v = &backward_refs->refs[i];
345
const int ix = (y >> histo_bits) * histo_xsize + (x >> histo_bits);
346
VP8LHistogramAddSinglePixOrCopy(histograms[ix], v);
347
x += PixOrCopyLength(v);
355
static uint32_t MyRand(uint32_t *seed) {
363
static int HistogramCombine(const VP8LHistogramSet* const in,
364
VP8LHistogramSet* const out, int iter_mult,
365
int num_pairs, int num_tries_no_success) {
369
int tries_with_no_success = 0;
370
int out_size = in->size;
371
const int outer_iters = in->size * iter_mult;
372
const int min_cluster_size = 2;
373
VP8LHistogram* const histos = (VP8LHistogram*)malloc(2 * sizeof(*histos));
374
VP8LHistogram* cur_combo = histos + 0; // trial merged histogram
375
VP8LHistogram* best_combo = histos + 1; // best merged histogram so far
376
if (histos == NULL) goto End;
378
// Copy histograms from in[] to out[].
379
assert(in->size <= out->size);
380
for (i = 0; i < in->size; ++i) {
381
in->histograms[i]->bit_cost_ = VP8LHistogramEstimateBits(in->histograms[i]);
382
*out->histograms[i] = *in->histograms[i];
385
// Collapse similar histograms in 'out'.
386
for (iter = 0; iter < outer_iters && out_size >= min_cluster_size; ++iter) {
387
double best_cost_diff = 0.;
388
int best_idx1 = -1, best_idx2 = 1;
390
const int num_tries = (num_pairs < out_size) ? num_pairs : out_size;
392
for (j = 0; j < num_tries; ++j) {
393
double curr_cost_diff;
394
// Choose two histograms at random and try to combine them.
395
const uint32_t idx1 = MyRand(&seed) % out_size;
396
const uint32_t tmp = (j & 7) + 1;
397
const uint32_t diff = (tmp < 3) ? tmp : MyRand(&seed) % (out_size - 1);
398
const uint32_t idx2 = (idx1 + diff + 1) % out_size;
402
// Calculate cost reduction on combining.
403
curr_cost_diff = HistogramAddEval(out->histograms[idx1],
404
out->histograms[idx2],
405
cur_combo, best_cost_diff);
406
if (curr_cost_diff < best_cost_diff) { // found a better pair?
407
{ // swap cur/best combo histograms
408
VP8LHistogram* const tmp_histo = cur_combo;
409
cur_combo = best_combo;
410
best_combo = tmp_histo;
412
best_cost_diff = curr_cost_diff;
418
if (best_idx1 >= 0) {
419
*out->histograms[best_idx1] = *best_combo;
420
// swap best_idx2 slot with last one (which is now unused)
422
if (best_idx2 != out_size) {
423
out->histograms[best_idx2] = out->histograms[out_size];
424
out->histograms[out_size] = NULL; // just for sanity check.
426
tries_with_no_success = 0;
428
if (++tries_with_no_success >= num_tries_no_success) {
432
out->size = out_size;
440
// -----------------------------------------------------------------------------
441
// Histogram refinement
443
// What is the bit cost of moving square_histogram from cur_symbol to candidate.
444
static double HistogramDistance(const VP8LHistogram* const square_histogram,
445
const VP8LHistogram* const candidate,
446
double cost_threshold) {
447
return HistogramAddThresh(candidate, square_histogram, cost_threshold);
450
// Find the best 'out' histogram for each of the 'in' histograms.
451
// Note: we assume that out[]->bit_cost_ is already up-to-date.
452
static void HistogramRemap(const VP8LHistogramSet* const in,
453
const VP8LHistogramSet* const out,
454
uint16_t* const symbols) {
456
for (i = 0; i < in->size; ++i) {
459
HistogramDistance(in->histograms[i], out->histograms[0], 1.e38);
461
for (k = 1; k < out->size; ++k) {
462
const double cur_bits =
463
HistogramDistance(in->histograms[i], out->histograms[k], best_bits);
464
if (cur_bits < best_bits) {
465
best_bits = cur_bits;
469
symbols[i] = best_out;
472
// Recompute each out based on raw and symbols.
473
for (i = 0; i < out->size; ++i) {
474
HistogramClear(out->histograms[i]);
476
for (i = 0; i < in->size; ++i) {
477
HistogramAdd(in->histograms[i], out->histograms[symbols[i]]);
481
int VP8LGetHistoImageSymbols(int xsize, int ysize,
482
const VP8LBackwardRefs* const refs,
483
int quality, int histo_bits, int cache_bits,
484
VP8LHistogramSet* const image_in,
485
uint16_t* const histogram_symbols) {
487
const int histo_xsize = histo_bits ? VP8LSubSampleSize(xsize, histo_bits) : 1;
488
const int histo_ysize = histo_bits ? VP8LSubSampleSize(ysize, histo_bits) : 1;
489
const int histo_image_raw_size = histo_xsize * histo_ysize;
491
// Heuristic params for HistogramCombine().
492
const int num_tries_no_success = 8 + (quality >> 1);
493
const int iter_mult = (quality < 27) ? 1 : 1 + ((quality - 27) >> 4);
494
const int num_pairs = (quality < 25) ? 10 : (5 * quality) >> 3;
496
VP8LHistogramSet* const image_out =
497
VP8LAllocateHistogramSet(histo_image_raw_size, cache_bits);
498
if (image_out == NULL) return 0;
500
// Build histogram image.
501
HistogramBuildImage(xsize, histo_bits, refs, image_out);
502
// Collapse similar histograms.
503
if (!HistogramCombine(image_out, image_in, iter_mult, num_pairs,
504
num_tries_no_success)) {
507
// Find the optimal map from original histograms to the final ones.
508
HistogramRemap(image_out, image_in, histogram_symbols);