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