Coverage Report

Created: 2026-11-12 07:35

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