Coverage Report

Created: 2024-06-18 06:05

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