Home | History | Annotate | Download | only in enc
      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 (at) google.com)
     11 //
     12 
     13 #include <assert.h>
     14 #include <math.h>
     15 
     16 #include "./backward_references_enc.h"
     17 #include "./histogram_enc.h"
     18 #include "../dsp/lossless.h"
     19 #include "../dsp/lossless_common.h"
     20 #include "../dsp/dsp.h"
     21 #include "../utils/color_cache_utils.h"
     22 #include "../utils/utils.h"
     23 
     24 #define VALUES_IN_BYTE 256
     25 
     26 #define MIN_BLOCK_SIZE 256  // minimum block size for backward references
     27 
     28 #define MAX_ENTROPY    (1e30f)
     29 
     30 // 1M window (4M bytes) minus 120 special codes for short distances.
     31 #define WINDOW_SIZE_BITS 20
     32 #define WINDOW_SIZE ((1 << WINDOW_SIZE_BITS) - 120)
     33 
     34 // Minimum number of pixels for which it is cheaper to encode a
     35 // distance + length instead of each pixel as a literal.
     36 #define MIN_LENGTH 4
     37 // If you change this, you need MAX_LENGTH_BITS + WINDOW_SIZE_BITS <= 32 as it
     38 // is used in VP8LHashChain.
     39 #define MAX_LENGTH_BITS 12
     40 // We want the max value to be attainable and stored in MAX_LENGTH_BITS bits.
     41 #define MAX_LENGTH ((1 << MAX_LENGTH_BITS) - 1)
     42 #if MAX_LENGTH_BITS + WINDOW_SIZE_BITS > 32
     43 #error "MAX_LENGTH_BITS + WINDOW_SIZE_BITS > 32"
     44 #endif
     45 
     46 // -----------------------------------------------------------------------------
     47 
     48 static const uint8_t plane_to_code_lut[128] = {
     49  96,   73,  55,  39,  23,  13,   5,  1,  255, 255, 255, 255, 255, 255, 255, 255,
     50  101,  78,  58,  42,  26,  16,   8,  2,    0,   3,  9,   17,  27,  43,  59,  79,
     51  102,  86,  62,  46,  32,  20,  10,  6,    4,   7,  11,  21,  33,  47,  63,  87,
     52  105,  90,  70,  52,  37,  28,  18,  14,  12,  15,  19,  29,  38,  53,  71,  91,
     53  110,  99,  82,  66,  48,  35,  30,  24,  22,  25,  31,  36,  49,  67,  83, 100,
     54  115, 108,  94,  76,  64,  50,  44,  40,  34,  41,  45,  51,  65,  77,  95, 109,
     55  118, 113, 103,  92,  80,  68,  60,  56,  54,  57,  61,  69,  81,  93, 104, 114,
     56  119, 116, 111, 106,  97,  88,  84,  74,  72,  75,  85,  89,  98, 107, 112, 117
     57 };
     58 
     59 static int DistanceToPlaneCode(int xsize, int dist) {
     60   const int yoffset = dist / xsize;
     61   const int xoffset = dist - yoffset * xsize;
     62   if (xoffset <= 8 && yoffset < 8) {
     63     return plane_to_code_lut[yoffset * 16 + 8 - xoffset] + 1;
     64   } else if (xoffset > xsize - 8 && yoffset < 7) {
     65     return plane_to_code_lut[(yoffset + 1) * 16 + 8 + (xsize - xoffset)] + 1;
     66   }
     67   return dist + 120;
     68 }
     69 
     70 // Returns the exact index where array1 and array2 are different. For an index
     71 // inferior or equal to best_len_match, the return value just has to be strictly
     72 // inferior to best_len_match. The current behavior is to return 0 if this index
     73 // is best_len_match, and the index itself otherwise.
     74 // If no two elements are the same, it returns max_limit.
     75 static WEBP_INLINE int FindMatchLength(const uint32_t* const array1,
     76                                        const uint32_t* const array2,
     77                                        int best_len_match, int max_limit) {
     78   // Before 'expensive' linear match, check if the two arrays match at the
     79   // current best length index.
     80   if (array1[best_len_match] != array2[best_len_match]) return 0;
     81 
     82   return VP8LVectorMismatch(array1, array2, max_limit);
     83 }
     84 
     85 // -----------------------------------------------------------------------------
     86 //  VP8LBackwardRefs
     87 
     88 struct PixOrCopyBlock {
     89   PixOrCopyBlock* next_;   // next block (or NULL)
     90   PixOrCopy* start_;       // data start
     91   int size_;               // currently used size
     92 };
     93 
     94 static void ClearBackwardRefs(VP8LBackwardRefs* const refs) {
     95   assert(refs != NULL);
     96   if (refs->tail_ != NULL) {
     97     *refs->tail_ = refs->free_blocks_;  // recycle all blocks at once
     98   }
     99   refs->free_blocks_ = refs->refs_;
    100   refs->tail_ = &refs->refs_;
    101   refs->last_block_ = NULL;
    102   refs->refs_ = NULL;
    103 }
    104 
    105 void VP8LBackwardRefsClear(VP8LBackwardRefs* const refs) {
    106   assert(refs != NULL);
    107   ClearBackwardRefs(refs);
    108   while (refs->free_blocks_ != NULL) {
    109     PixOrCopyBlock* const next = refs->free_blocks_->next_;
    110     WebPSafeFree(refs->free_blocks_);
    111     refs->free_blocks_ = next;
    112   }
    113 }
    114 
    115 void VP8LBackwardRefsInit(VP8LBackwardRefs* const refs, int block_size) {
    116   assert(refs != NULL);
    117   memset(refs, 0, sizeof(*refs));
    118   refs->tail_ = &refs->refs_;
    119   refs->block_size_ =
    120       (block_size < MIN_BLOCK_SIZE) ? MIN_BLOCK_SIZE : block_size;
    121 }
    122 
    123 VP8LRefsCursor VP8LRefsCursorInit(const VP8LBackwardRefs* const refs) {
    124   VP8LRefsCursor c;
    125   c.cur_block_ = refs->refs_;
    126   if (refs->refs_ != NULL) {
    127     c.cur_pos = c.cur_block_->start_;
    128     c.last_pos_ = c.cur_pos + c.cur_block_->size_;
    129   } else {
    130     c.cur_pos = NULL;
    131     c.last_pos_ = NULL;
    132   }
    133   return c;
    134 }
    135 
    136 void VP8LRefsCursorNextBlock(VP8LRefsCursor* const c) {
    137   PixOrCopyBlock* const b = c->cur_block_->next_;
    138   c->cur_pos = (b == NULL) ? NULL : b->start_;
    139   c->last_pos_ = (b == NULL) ? NULL : b->start_ + b->size_;
    140   c->cur_block_ = b;
    141 }
    142 
    143 // Create a new block, either from the free list or allocated
    144 static PixOrCopyBlock* BackwardRefsNewBlock(VP8LBackwardRefs* const refs) {
    145   PixOrCopyBlock* b = refs->free_blocks_;
    146   if (b == NULL) {   // allocate new memory chunk
    147     const size_t total_size =
    148         sizeof(*b) + refs->block_size_ * sizeof(*b->start_);
    149     b = (PixOrCopyBlock*)WebPSafeMalloc(1ULL, total_size);
    150     if (b == NULL) {
    151       refs->error_ |= 1;
    152       return NULL;
    153     }
    154     b->start_ = (PixOrCopy*)((uint8_t*)b + sizeof(*b));  // not always aligned
    155   } else {  // recycle from free-list
    156     refs->free_blocks_ = b->next_;
    157   }
    158   *refs->tail_ = b;
    159   refs->tail_ = &b->next_;
    160   refs->last_block_ = b;
    161   b->next_ = NULL;
    162   b->size_ = 0;
    163   return b;
    164 }
    165 
    166 static WEBP_INLINE void BackwardRefsCursorAdd(VP8LBackwardRefs* const refs,
    167                                               const PixOrCopy v) {
    168   PixOrCopyBlock* b = refs->last_block_;
    169   if (b == NULL || b->size_ == refs->block_size_) {
    170     b = BackwardRefsNewBlock(refs);
    171     if (b == NULL) return;   // refs->error_ is set
    172   }
    173   b->start_[b->size_++] = v;
    174 }
    175 
    176 int VP8LBackwardRefsCopy(const VP8LBackwardRefs* const src,
    177                          VP8LBackwardRefs* const dst) {
    178   const PixOrCopyBlock* b = src->refs_;
    179   ClearBackwardRefs(dst);
    180   assert(src->block_size_ == dst->block_size_);
    181   while (b != NULL) {
    182     PixOrCopyBlock* const new_b = BackwardRefsNewBlock(dst);
    183     if (new_b == NULL) return 0;   // dst->error_ is set
    184     memcpy(new_b->start_, b->start_, b->size_ * sizeof(*b->start_));
    185     new_b->size_ = b->size_;
    186     b = b->next_;
    187   }
    188   return 1;
    189 }
    190 
    191 // -----------------------------------------------------------------------------
    192 // Hash chains
    193 
    194 int VP8LHashChainInit(VP8LHashChain* const p, int size) {
    195   assert(p->size_ == 0);
    196   assert(p->offset_length_ == NULL);
    197   assert(size > 0);
    198   p->offset_length_ =
    199       (uint32_t*)WebPSafeMalloc(size, sizeof(*p->offset_length_));
    200   if (p->offset_length_ == NULL) return 0;
    201   p->size_ = size;
    202 
    203   return 1;
    204 }
    205 
    206 void VP8LHashChainClear(VP8LHashChain* const p) {
    207   assert(p != NULL);
    208   WebPSafeFree(p->offset_length_);
    209 
    210   p->size_ = 0;
    211   p->offset_length_ = NULL;
    212 }
    213 
    214 // -----------------------------------------------------------------------------
    215 
    216 #define HASH_MULTIPLIER_HI (0xc6a4a793ULL)
    217 #define HASH_MULTIPLIER_LO (0x5bd1e996ULL)
    218 
    219 static WEBP_INLINE uint32_t GetPixPairHash64(const uint32_t* const argb) {
    220   uint32_t key;
    221   key  = (argb[1] * HASH_MULTIPLIER_HI) & 0xffffffffu;
    222   key += (argb[0] * HASH_MULTIPLIER_LO) & 0xffffffffu;
    223   key = key >> (32 - HASH_BITS);
    224   return key;
    225 }
    226 
    227 // Returns the maximum number of hash chain lookups to do for a
    228 // given compression quality. Return value in range [8, 86].
    229 static int GetMaxItersForQuality(int quality) {
    230   return 8 + (quality * quality) / 128;
    231 }
    232 
    233 static int GetWindowSizeForHashChain(int quality, int xsize) {
    234   const int max_window_size = (quality > 75) ? WINDOW_SIZE
    235                             : (quality > 50) ? (xsize << 8)
    236                             : (quality > 25) ? (xsize << 6)
    237                             : (xsize << 4);
    238   assert(xsize > 0);
    239   return (max_window_size > WINDOW_SIZE) ? WINDOW_SIZE : max_window_size;
    240 }
    241 
    242 static WEBP_INLINE int MaxFindCopyLength(int len) {
    243   return (len < MAX_LENGTH) ? len : MAX_LENGTH;
    244 }
    245 
    246 int VP8LHashChainFill(VP8LHashChain* const p, int quality,
    247                       const uint32_t* const argb, int xsize, int ysize,
    248                       int low_effort) {
    249   const int size = xsize * ysize;
    250   const int iter_max = GetMaxItersForQuality(quality);
    251   const uint32_t window_size = GetWindowSizeForHashChain(quality, xsize);
    252   int pos;
    253   int argb_comp;
    254   uint32_t base_position;
    255   int32_t* hash_to_first_index;
    256   // Temporarily use the p->offset_length_ as a hash chain.
    257   int32_t* chain = (int32_t*)p->offset_length_;
    258   assert(size > 0);
    259   assert(p->size_ != 0);
    260   assert(p->offset_length_ != NULL);
    261 
    262   if (size <= 2) {
    263     p->offset_length_[0] = p->offset_length_[size - 1] = 0;
    264     return 1;
    265   }
    266 
    267   hash_to_first_index =
    268       (int32_t*)WebPSafeMalloc(HASH_SIZE, sizeof(*hash_to_first_index));
    269   if (hash_to_first_index == NULL) return 0;
    270 
    271   // Set the int32_t array to -1.
    272   memset(hash_to_first_index, 0xff, HASH_SIZE * sizeof(*hash_to_first_index));
    273   // Fill the chain linking pixels with the same hash.
    274   argb_comp = (argb[0] == argb[1]);
    275   for (pos = 0; pos < size - 2;) {
    276     uint32_t hash_code;
    277     const int argb_comp_next = (argb[pos + 1] == argb[pos + 2]);
    278     if (argb_comp && argb_comp_next) {
    279       // Consecutive pixels with the same color will share the same hash.
    280       // We therefore use a different hash: the color and its repetition
    281       // length.
    282       uint32_t tmp[2];
    283       uint32_t len = 1;
    284       tmp[0] = argb[pos];
    285       // Figure out how far the pixels are the same.
    286       // The last pixel has a different 64 bit hash, as its next pixel does
    287       // not have the same color, so we just need to get to the last pixel equal
    288       // to its follower.
    289       while (pos + (int)len + 2 < size && argb[pos + len + 2] == argb[pos]) {
    290         ++len;
    291       }
    292       if (len > MAX_LENGTH) {
    293         // Skip the pixels that match for distance=1 and length>MAX_LENGTH
    294         // because they are linked to their predecessor and we automatically
    295         // check that in the main for loop below. Skipping means setting no
    296         // predecessor in the chain, hence -1.
    297         memset(chain + pos, 0xff, (len - MAX_LENGTH) * sizeof(*chain));
    298         pos += len - MAX_LENGTH;
    299         len = MAX_LENGTH;
    300       }
    301       // Process the rest of the hash chain.
    302       while (len) {
    303         tmp[1] = len--;
    304         hash_code = GetPixPairHash64(tmp);
    305         chain[pos] = hash_to_first_index[hash_code];
    306         hash_to_first_index[hash_code] = pos++;
    307       }
    308       argb_comp = 0;
    309     } else {
    310       // Just move one pixel forward.
    311       hash_code = GetPixPairHash64(argb + pos);
    312       chain[pos] = hash_to_first_index[hash_code];
    313       hash_to_first_index[hash_code] = pos++;
    314       argb_comp = argb_comp_next;
    315     }
    316   }
    317   // Process the penultimate pixel.
    318   chain[pos] = hash_to_first_index[GetPixPairHash64(argb + pos)];
    319 
    320   WebPSafeFree(hash_to_first_index);
    321 
    322   // Find the best match interval at each pixel, defined by an offset to the
    323   // pixel and a length. The right-most pixel cannot match anything to the right
    324   // (hence a best length of 0) and the left-most pixel nothing to the left
    325   // (hence an offset of 0).
    326   assert(size > 2);
    327   p->offset_length_[0] = p->offset_length_[size - 1] = 0;
    328   for (base_position = size - 2; base_position > 0;) {
    329     const int max_len = MaxFindCopyLength(size - 1 - base_position);
    330     const uint32_t* const argb_start = argb + base_position;
    331     int iter = iter_max;
    332     int best_length = 0;
    333     uint32_t best_distance = 0;
    334     uint32_t best_argb;
    335     const int min_pos =
    336         (base_position > window_size) ? base_position - window_size : 0;
    337     const int length_max = (max_len < 256) ? max_len : 256;
    338     uint32_t max_base_position;
    339 
    340     pos = chain[base_position];
    341     if (!low_effort) {
    342       int curr_length;
    343       // Heuristic: use the comparison with the above line as an initialization.
    344       if (base_position >= (uint32_t)xsize) {
    345         curr_length = FindMatchLength(argb_start - xsize, argb_start,
    346                                       best_length, max_len);
    347         if (curr_length > best_length) {
    348           best_length = curr_length;
    349           best_distance = xsize;
    350         }
    351         --iter;
    352       }
    353       // Heuristic: compare to the previous pixel.
    354       curr_length =
    355           FindMatchLength(argb_start - 1, argb_start, best_length, max_len);
    356       if (curr_length > best_length) {
    357         best_length = curr_length;
    358         best_distance = 1;
    359       }
    360       --iter;
    361       // Skip the for loop if we already have the maximum.
    362       if (best_length == MAX_LENGTH) pos = min_pos - 1;
    363     }
    364     best_argb = argb_start[best_length];
    365 
    366     for (; pos >= min_pos && --iter; pos = chain[pos]) {
    367       int curr_length;
    368       assert(base_position > (uint32_t)pos);
    369 
    370       if (argb[pos + best_length] != best_argb) continue;
    371 
    372       curr_length = VP8LVectorMismatch(argb + pos, argb_start, max_len);
    373       if (best_length < curr_length) {
    374         best_length = curr_length;
    375         best_distance = base_position - pos;
    376         best_argb = argb_start[best_length];
    377         // Stop if we have reached a good enough length.
    378         if (best_length >= length_max) break;
    379       }
    380     }
    381     // We have the best match but in case the two intervals continue matching
    382     // to the left, we have the best matches for the left-extended pixels.
    383     max_base_position = base_position;
    384     while (1) {
    385       assert(best_length <= MAX_LENGTH);
    386       assert(best_distance <= WINDOW_SIZE);
    387       p->offset_length_[base_position] =
    388           (best_distance << MAX_LENGTH_BITS) | (uint32_t)best_length;
    389       --base_position;
    390       // Stop if we don't have a match or if we are out of bounds.
    391       if (best_distance == 0 || base_position == 0) break;
    392       // Stop if we cannot extend the matching intervals to the left.
    393       if (base_position < best_distance ||
    394           argb[base_position - best_distance] != argb[base_position]) {
    395         break;
    396       }
    397       // Stop if we are matching at its limit because there could be a closer
    398       // matching interval with the same maximum length. Then again, if the
    399       // matching interval is as close as possible (best_distance == 1), we will
    400       // never find anything better so let's continue.
    401       if (best_length == MAX_LENGTH && best_distance != 1 &&
    402           base_position + MAX_LENGTH < max_base_position) {
    403         break;
    404       }
    405       if (best_length < MAX_LENGTH) {
    406         ++best_length;
    407         max_base_position = base_position;
    408       }
    409     }
    410   }
    411   return 1;
    412 }
    413 
    414 static WEBP_INLINE int HashChainFindOffset(const VP8LHashChain* const p,
    415                                            const int base_position) {
    416   return p->offset_length_[base_position] >> MAX_LENGTH_BITS;
    417 }
    418 
    419 static WEBP_INLINE int HashChainFindLength(const VP8LHashChain* const p,
    420                                            const int base_position) {
    421   return p->offset_length_[base_position] & ((1U << MAX_LENGTH_BITS) - 1);
    422 }
    423 
    424 static WEBP_INLINE void HashChainFindCopy(const VP8LHashChain* const p,
    425                                           int base_position,
    426                                           int* const offset_ptr,
    427                                           int* const length_ptr) {
    428   *offset_ptr = HashChainFindOffset(p, base_position);
    429   *length_ptr = HashChainFindLength(p, base_position);
    430 }
    431 
    432 static WEBP_INLINE void AddSingleLiteral(uint32_t pixel, int use_color_cache,
    433                                          VP8LColorCache* const hashers,
    434                                          VP8LBackwardRefs* const refs) {
    435   PixOrCopy v;
    436   if (use_color_cache) {
    437     const uint32_t key = VP8LColorCacheGetIndex(hashers, pixel);
    438     if (VP8LColorCacheLookup(hashers, key) == pixel) {
    439       v = PixOrCopyCreateCacheIdx(key);
    440     } else {
    441       v = PixOrCopyCreateLiteral(pixel);
    442       VP8LColorCacheSet(hashers, key, pixel);
    443     }
    444   } else {
    445     v = PixOrCopyCreateLiteral(pixel);
    446   }
    447   BackwardRefsCursorAdd(refs, v);
    448 }
    449 
    450 static int BackwardReferencesRle(int xsize, int ysize,
    451                                  const uint32_t* const argb,
    452                                  int cache_bits, VP8LBackwardRefs* const refs) {
    453   const int pix_count = xsize * ysize;
    454   int i, k;
    455   const int use_color_cache = (cache_bits > 0);
    456   VP8LColorCache hashers;
    457 
    458   if (use_color_cache && !VP8LColorCacheInit(&hashers, cache_bits)) {
    459     return 0;
    460   }
    461   ClearBackwardRefs(refs);
    462   // Add first pixel as literal.
    463   AddSingleLiteral(argb[0], use_color_cache, &hashers, refs);
    464   i = 1;
    465   while (i < pix_count) {
    466     const int max_len = MaxFindCopyLength(pix_count - i);
    467     const int rle_len = FindMatchLength(argb + i, argb + i - 1, 0, max_len);
    468     const int prev_row_len = (i < xsize) ? 0 :
    469         FindMatchLength(argb + i, argb + i - xsize, 0, max_len);
    470     if (rle_len >= prev_row_len && rle_len >= MIN_LENGTH) {
    471       BackwardRefsCursorAdd(refs, PixOrCopyCreateCopy(1, rle_len));
    472       // We don't need to update the color cache here since it is always the
    473       // same pixel being copied, and that does not change the color cache
    474       // state.
    475       i += rle_len;
    476     } else if (prev_row_len >= MIN_LENGTH) {
    477       BackwardRefsCursorAdd(refs, PixOrCopyCreateCopy(xsize, prev_row_len));
    478       if (use_color_cache) {
    479         for (k = 0; k < prev_row_len; ++k) {
    480           VP8LColorCacheInsert(&hashers, argb[i + k]);
    481         }
    482       }
    483       i += prev_row_len;
    484     } else {
    485       AddSingleLiteral(argb[i], use_color_cache, &hashers, refs);
    486       i++;
    487     }
    488   }
    489   if (use_color_cache) VP8LColorCacheClear(&hashers);
    490   return !refs->error_;
    491 }
    492 
    493 static int BackwardReferencesLz77(int xsize, int ysize,
    494                                   const uint32_t* const argb, int cache_bits,
    495                                   const VP8LHashChain* const hash_chain,
    496                                   VP8LBackwardRefs* const refs) {
    497   int i;
    498   int i_last_check = -1;
    499   int ok = 0;
    500   int cc_init = 0;
    501   const int use_color_cache = (cache_bits > 0);
    502   const int pix_count = xsize * ysize;
    503   VP8LColorCache hashers;
    504 
    505   if (use_color_cache) {
    506     cc_init = VP8LColorCacheInit(&hashers, cache_bits);
    507     if (!cc_init) goto Error;
    508   }
    509   ClearBackwardRefs(refs);
    510   for (i = 0; i < pix_count;) {
    511     // Alternative#1: Code the pixels starting at 'i' using backward reference.
    512     int offset = 0;
    513     int len = 0;
    514     int j;
    515     HashChainFindCopy(hash_chain, i, &offset, &len);
    516     if (len >= MIN_LENGTH) {
    517       const int len_ini = len;
    518       int max_reach = 0;
    519       assert(i + len < pix_count);
    520       // Only start from what we have not checked already.
    521       i_last_check = (i > i_last_check) ? i : i_last_check;
    522       // We know the best match for the current pixel but we try to find the
    523       // best matches for the current pixel AND the next one combined.
    524       // The naive method would use the intervals:
    525       // [i,i+len) + [i+len, length of best match at i+len)
    526       // while we check if we can use:
    527       // [i,j) (where j<=i+len) + [j, length of best match at j)
    528       for (j = i_last_check + 1; j <= i + len_ini; ++j) {
    529         const int len_j = HashChainFindLength(hash_chain, j);
    530         const int reach =
    531             j + (len_j >= MIN_LENGTH ? len_j : 1);  // 1 for single literal.
    532         if (reach > max_reach) {
    533           len = j - i;
    534           max_reach = reach;
    535         }
    536       }
    537     } else {
    538       len = 1;
    539     }
    540     // Go with literal or backward reference.
    541     assert(len > 0);
    542     if (len == 1) {
    543       AddSingleLiteral(argb[i], use_color_cache, &hashers, refs);
    544     } else {
    545       BackwardRefsCursorAdd(refs, PixOrCopyCreateCopy(offset, len));
    546       if (use_color_cache) {
    547         for (j = i; j < i + len; ++j) VP8LColorCacheInsert(&hashers, argb[j]);
    548       }
    549     }
    550     i += len;
    551   }
    552 
    553   ok = !refs->error_;
    554  Error:
    555   if (cc_init) VP8LColorCacheClear(&hashers);
    556   return ok;
    557 }
    558 
    559 // -----------------------------------------------------------------------------
    560 
    561 typedef struct {
    562   double alpha_[VALUES_IN_BYTE];
    563   double red_[VALUES_IN_BYTE];
    564   double blue_[VALUES_IN_BYTE];
    565   double distance_[NUM_DISTANCE_CODES];
    566   double* literal_;
    567 } CostModel;
    568 
    569 static int BackwardReferencesTraceBackwards(
    570     int xsize, int ysize, const uint32_t* const argb, int quality,
    571     int cache_bits, const VP8LHashChain* const hash_chain,
    572     VP8LBackwardRefs* const refs);
    573 
    574 static void ConvertPopulationCountTableToBitEstimates(
    575     int num_symbols, const uint32_t population_counts[], double output[]) {
    576   uint32_t sum = 0;
    577   int nonzeros = 0;
    578   int i;
    579   for (i = 0; i < num_symbols; ++i) {
    580     sum += population_counts[i];
    581     if (population_counts[i] > 0) {
    582       ++nonzeros;
    583     }
    584   }
    585   if (nonzeros <= 1) {
    586     memset(output, 0, num_symbols * sizeof(*output));
    587   } else {
    588     const double logsum = VP8LFastLog2(sum);
    589     for (i = 0; i < num_symbols; ++i) {
    590       output[i] = logsum - VP8LFastLog2(population_counts[i]);
    591     }
    592   }
    593 }
    594 
    595 static int CostModelBuild(CostModel* const m, int cache_bits,
    596                           VP8LBackwardRefs* const refs) {
    597   int ok = 0;
    598   VP8LHistogram* const histo = VP8LAllocateHistogram(cache_bits);
    599   if (histo == NULL) goto Error;
    600 
    601   VP8LHistogramCreate(histo, refs, cache_bits);
    602 
    603   ConvertPopulationCountTableToBitEstimates(
    604       VP8LHistogramNumCodes(histo->palette_code_bits_),
    605       histo->literal_, m->literal_);
    606   ConvertPopulationCountTableToBitEstimates(
    607       VALUES_IN_BYTE, histo->red_, m->red_);
    608   ConvertPopulationCountTableToBitEstimates(
    609       VALUES_IN_BYTE, histo->blue_, m->blue_);
    610   ConvertPopulationCountTableToBitEstimates(
    611       VALUES_IN_BYTE, histo->alpha_, m->alpha_);
    612   ConvertPopulationCountTableToBitEstimates(
    613       NUM_DISTANCE_CODES, histo->distance_, m->distance_);
    614   ok = 1;
    615 
    616  Error:
    617   VP8LFreeHistogram(histo);
    618   return ok;
    619 }
    620 
    621 static WEBP_INLINE double GetLiteralCost(const CostModel* const m, uint32_t v) {
    622   return m->alpha_[v >> 24] +
    623          m->red_[(v >> 16) & 0xff] +
    624          m->literal_[(v >> 8) & 0xff] +
    625          m->blue_[v & 0xff];
    626 }
    627 
    628 static WEBP_INLINE double GetCacheCost(const CostModel* const m, uint32_t idx) {
    629   const int literal_idx = VALUES_IN_BYTE + NUM_LENGTH_CODES + idx;
    630   return m->literal_[literal_idx];
    631 }
    632 
    633 static WEBP_INLINE double GetLengthCost(const CostModel* const m,
    634                                         uint32_t length) {
    635   int code, extra_bits;
    636   VP8LPrefixEncodeBits(length, &code, &extra_bits);
    637   return m->literal_[VALUES_IN_BYTE + code] + extra_bits;
    638 }
    639 
    640 static WEBP_INLINE double GetDistanceCost(const CostModel* const m,
    641                                           uint32_t distance) {
    642   int code, extra_bits;
    643   VP8LPrefixEncodeBits(distance, &code, &extra_bits);
    644   return m->distance_[code] + extra_bits;
    645 }
    646 
    647 static void AddSingleLiteralWithCostModel(const uint32_t* const argb,
    648                                           VP8LColorCache* const hashers,
    649                                           const CostModel* const cost_model,
    650                                           int idx, int use_color_cache,
    651                                           double prev_cost, float* const cost,
    652                                           uint16_t* const dist_array) {
    653   double cost_val = prev_cost;
    654   const uint32_t color = argb[0];
    655   const int ix = use_color_cache ? VP8LColorCacheContains(hashers, color) : -1;
    656   if (ix >= 0) {
    657     // use_color_cache is true and hashers contains color
    658     const double mul0 = 0.68;
    659     cost_val += GetCacheCost(cost_model, ix) * mul0;
    660   } else {
    661     const double mul1 = 0.82;
    662     if (use_color_cache) VP8LColorCacheInsert(hashers, color);
    663     cost_val += GetLiteralCost(cost_model, color) * mul1;
    664   }
    665   if (cost[idx] > cost_val) {
    666     cost[idx] = (float)cost_val;
    667     dist_array[idx] = 1;  // only one is inserted.
    668   }
    669 }
    670 
    671 // -----------------------------------------------------------------------------
    672 // CostManager and interval handling
    673 
    674 // Empirical value to avoid high memory consumption but good for performance.
    675 #define COST_CACHE_INTERVAL_SIZE_MAX 100
    676 
    677 // To perform backward reference every pixel at index index_ is considered and
    678 // the cost for the MAX_LENGTH following pixels computed. Those following pixels
    679 // at index index_ + k (k from 0 to MAX_LENGTH) have a cost of:
    680 //     distance_cost_ at index_ + GetLengthCost(cost_model, k)
    681 //            (named cost)            (named cached cost)
    682 // and the minimum value is kept. GetLengthCost(cost_model, k) is cached in an
    683 // array of size MAX_LENGTH.
    684 // Instead of performing MAX_LENGTH comparisons per pixel, we keep track of the
    685 // minimal values using intervals, for which lower_ and upper_ bounds are kept.
    686 // An interval is defined by the index_ of the pixel that generated it and
    687 // is only useful in a range of indices from start_ to end_ (exclusive), i.e.
    688 // it contains the minimum value for pixels between start_ and end_.
    689 // Intervals are stored in a linked list and ordered by start_. When a new
    690 // interval has a better minimum, old intervals are split or removed.
    691 typedef struct CostInterval CostInterval;
    692 struct CostInterval {
    693   double lower_;
    694   double upper_;
    695   int start_;
    696   int end_;
    697   double distance_cost_;
    698   int index_;
    699   CostInterval* previous_;
    700   CostInterval* next_;
    701 };
    702 
    703 // The GetLengthCost(cost_model, k) part of the costs is also bounded for
    704 // efficiency in a set of intervals of a different type.
    705 // If those intervals are small enough, they are not used for comparison and
    706 // written into the costs right away.
    707 typedef struct {
    708   double lower_;  // Lower bound of the interval.
    709   double upper_;  // Upper bound of the interval.
    710   int start_;
    711   int end_;       // Exclusive.
    712   int do_write_;  // If !=0, the interval is saved to cost instead of being kept
    713                   // for comparison.
    714 } CostCacheInterval;
    715 
    716 // This structure is in charge of managing intervals and costs.
    717 // It caches the different CostCacheInterval, caches the different
    718 // GetLengthCost(cost_model, k) in cost_cache_ and the CostInterval's (whose
    719 // count_ is limited by COST_CACHE_INTERVAL_SIZE_MAX).
    720 #define COST_MANAGER_MAX_FREE_LIST 10
    721 typedef struct {
    722   CostInterval* head_;
    723   int count_;  // The number of stored intervals.
    724   CostCacheInterval* cache_intervals_;
    725   size_t cache_intervals_size_;
    726   double cost_cache_[MAX_LENGTH];  // Contains the GetLengthCost(cost_model, k).
    727   double min_cost_cache_;          // The minimum value in cost_cache_[1:].
    728   double max_cost_cache_;          // The maximum value in cost_cache_[1:].
    729   float* costs_;
    730   uint16_t* dist_array_;
    731   // Most of the time, we only need few intervals -> use a free-list, to avoid
    732   // fragmentation with small allocs in most common cases.
    733   CostInterval intervals_[COST_MANAGER_MAX_FREE_LIST];
    734   CostInterval* free_intervals_;
    735   // These are regularly malloc'd remains. This list can't grow larger than than
    736   // size COST_CACHE_INTERVAL_SIZE_MAX - COST_MANAGER_MAX_FREE_LIST, note.
    737   CostInterval* recycled_intervals_;
    738   // Buffer used in BackwardReferencesHashChainDistanceOnly to store the ends
    739   // of the intervals that can have impacted the cost at a pixel.
    740   int* interval_ends_;
    741   int interval_ends_size_;
    742 } CostManager;
    743 
    744 static int IsCostCacheIntervalWritable(int start, int end) {
    745   // 100 is the length for which we consider an interval for comparison, and not
    746   // for writing.
    747   // The first intervals are very small and go in increasing size. This constant
    748   // helps merging them into one big interval (up to index 150/200 usually from
    749   // which intervals start getting much bigger).
    750   // This value is empirical.
    751   return (end - start + 1 < 100);
    752 }
    753 
    754 static void CostIntervalAddToFreeList(CostManager* const manager,
    755                                       CostInterval* const interval) {
    756   interval->next_ = manager->free_intervals_;
    757   manager->free_intervals_ = interval;
    758 }
    759 
    760 static int CostIntervalIsInFreeList(const CostManager* const manager,
    761                                     const CostInterval* const interval) {
    762   return (interval >= &manager->intervals_[0] &&
    763           interval <= &manager->intervals_[COST_MANAGER_MAX_FREE_LIST - 1]);
    764 }
    765 
    766 static void CostManagerInitFreeList(CostManager* const manager) {
    767   int i;
    768   manager->free_intervals_ = NULL;
    769   for (i = 0; i < COST_MANAGER_MAX_FREE_LIST; ++i) {
    770     CostIntervalAddToFreeList(manager, &manager->intervals_[i]);
    771   }
    772 }
    773 
    774 static void DeleteIntervalList(CostManager* const manager,
    775                                const CostInterval* interval) {
    776   while (interval != NULL) {
    777     const CostInterval* const next = interval->next_;
    778     if (!CostIntervalIsInFreeList(manager, interval)) {
    779       WebPSafeFree((void*)interval);
    780     }  // else: do nothing
    781     interval = next;
    782   }
    783 }
    784 
    785 static void CostManagerClear(CostManager* const manager) {
    786   if (manager == NULL) return;
    787 
    788   WebPSafeFree(manager->costs_);
    789   WebPSafeFree(manager->cache_intervals_);
    790   WebPSafeFree(manager->interval_ends_);
    791 
    792   // Clear the interval lists.
    793   DeleteIntervalList(manager, manager->head_);
    794   manager->head_ = NULL;
    795   DeleteIntervalList(manager, manager->recycled_intervals_);
    796   manager->recycled_intervals_ = NULL;
    797 
    798   // Reset pointers, count_ and cache_intervals_size_.
    799   memset(manager, 0, sizeof(*manager));
    800   CostManagerInitFreeList(manager);
    801 }
    802 
    803 static int CostManagerInit(CostManager* const manager,
    804                            uint16_t* const dist_array, int pix_count,
    805                            const CostModel* const cost_model) {
    806   int i;
    807   const int cost_cache_size = (pix_count > MAX_LENGTH) ? MAX_LENGTH : pix_count;
    808   // This constant is tied to the cost_model we use.
    809   // Empirically, differences between intervals is usually of more than 1.
    810   const double min_cost_diff = 0.1;
    811 
    812   manager->costs_ = NULL;
    813   manager->cache_intervals_ = NULL;
    814   manager->interval_ends_ = NULL;
    815   manager->head_ = NULL;
    816   manager->recycled_intervals_ = NULL;
    817   manager->count_ = 0;
    818   manager->dist_array_ = dist_array;
    819   CostManagerInitFreeList(manager);
    820 
    821   // Fill in the cost_cache_.
    822   manager->cache_intervals_size_ = 1;
    823   manager->cost_cache_[0] = 0;
    824   for (i = 1; i < cost_cache_size; ++i) {
    825     manager->cost_cache_[i] = GetLengthCost(cost_model, i);
    826     // Get an approximation of the number of bound intervals.
    827     if (fabs(manager->cost_cache_[i] - manager->cost_cache_[i - 1]) >
    828         min_cost_diff) {
    829       ++manager->cache_intervals_size_;
    830     }
    831     // Compute the minimum of cost_cache_.
    832     if (i == 1) {
    833       manager->min_cost_cache_ = manager->cost_cache_[1];
    834       manager->max_cost_cache_ = manager->cost_cache_[1];
    835     } else if (manager->cost_cache_[i] < manager->min_cost_cache_) {
    836       manager->min_cost_cache_ = manager->cost_cache_[i];
    837     } else if (manager->cost_cache_[i] > manager->max_cost_cache_) {
    838       manager->max_cost_cache_ = manager->cost_cache_[i];
    839     }
    840   }
    841 
    842   // With the current cost models, we have 15 intervals, so we are safe by
    843   // setting a maximum of COST_CACHE_INTERVAL_SIZE_MAX.
    844   if (manager->cache_intervals_size_ > COST_CACHE_INTERVAL_SIZE_MAX) {
    845     manager->cache_intervals_size_ = COST_CACHE_INTERVAL_SIZE_MAX;
    846   }
    847   manager->cache_intervals_ = (CostCacheInterval*)WebPSafeMalloc(
    848       manager->cache_intervals_size_, sizeof(*manager->cache_intervals_));
    849   if (manager->cache_intervals_ == NULL) {
    850     CostManagerClear(manager);
    851     return 0;
    852   }
    853 
    854   // Fill in the cache_intervals_.
    855   {
    856     double cost_prev = -1e38f;  // unprobably low initial value
    857     CostCacheInterval* prev = NULL;
    858     CostCacheInterval* cur = manager->cache_intervals_;
    859     const CostCacheInterval* const end =
    860         manager->cache_intervals_ + manager->cache_intervals_size_;
    861 
    862     // Consecutive values in cost_cache_ are compared and if a big enough
    863     // difference is found, a new interval is created and bounded.
    864     for (i = 0; i < cost_cache_size; ++i) {
    865       const double cost_val = manager->cost_cache_[i];
    866       if (i == 0 ||
    867           (fabs(cost_val - cost_prev) > min_cost_diff && cur + 1 < end)) {
    868         if (i > 1) {
    869           const int is_writable =
    870               IsCostCacheIntervalWritable(cur->start_, cur->end_);
    871           // Merge with the previous interval if both are writable.
    872           if (is_writable && cur != manager->cache_intervals_ &&
    873               prev->do_write_) {
    874             // Update the previous interval.
    875             prev->end_ = cur->end_;
    876             if (cur->lower_ < prev->lower_) {
    877               prev->lower_ = cur->lower_;
    878             } else if (cur->upper_ > prev->upper_) {
    879               prev->upper_ = cur->upper_;
    880             }
    881           } else {
    882             cur->do_write_ = is_writable;
    883             prev = cur;
    884             ++cur;
    885           }
    886         }
    887         // Initialize an interval.
    888         cur->start_ = i;
    889         cur->do_write_ = 0;
    890         cur->lower_ = cost_val;
    891         cur->upper_ = cost_val;
    892       } else {
    893         // Update the current interval bounds.
    894         if (cost_val < cur->lower_) {
    895           cur->lower_ = cost_val;
    896         } else if (cost_val > cur->upper_) {
    897           cur->upper_ = cost_val;
    898         }
    899       }
    900       cur->end_ = i + 1;
    901       cost_prev = cost_val;
    902     }
    903     manager->cache_intervals_size_ = cur + 1 - manager->cache_intervals_;
    904   }
    905 
    906   manager->costs_ = (float*)WebPSafeMalloc(pix_count, sizeof(*manager->costs_));
    907   if (manager->costs_ == NULL) {
    908     CostManagerClear(manager);
    909     return 0;
    910   }
    911   // Set the initial costs_ high for every pixel as we will keep the minimum.
    912   for (i = 0; i < pix_count; ++i) manager->costs_[i] = 1e38f;
    913 
    914   // The cost at pixel is influenced by the cost intervals from previous pixels.
    915   // Let us take the specific case where the offset is the same (which actually
    916   // happens a lot in case of uniform regions).
    917   // pixel i contributes to j>i a cost of: offset cost + cost_cache_[j-i]
    918   // pixel i+1 contributes to j>i a cost of: 2*offset cost + cost_cache_[j-i-1]
    919   // pixel i+2 contributes to j>i a cost of: 3*offset cost + cost_cache_[j-i-2]
    920   // and so on.
    921   // A pixel i influences the following length(j) < MAX_LENGTH pixels. What is
    922   // the value of j such that pixel i + j cannot influence any of those pixels?
    923   // This value is such that:
    924   //               max of cost_cache_ < j*offset cost + min of cost_cache_
    925   // (pixel i + j 's cost cannot beat the worst cost given by pixel i).
    926   // This value will be used to optimize the cost computation in
    927   // BackwardReferencesHashChainDistanceOnly.
    928   {
    929     // The offset cost is computed in GetDistanceCost and has a minimum value of
    930     // the minimum in cost_model->distance_. The case where the offset cost is 0
    931     // will be dealt with differently later so we are only interested in the
    932     // minimum non-zero offset cost.
    933     double offset_cost_min = 0.;
    934     int size;
    935     for (i = 0; i < NUM_DISTANCE_CODES; ++i) {
    936       if (cost_model->distance_[i] != 0) {
    937         if (offset_cost_min == 0.) {
    938           offset_cost_min = cost_model->distance_[i];
    939         } else if (cost_model->distance_[i] < offset_cost_min) {
    940           offset_cost_min = cost_model->distance_[i];
    941         }
    942       }
    943     }
    944     // In case all the cost_model->distance_ is 0, the next non-zero cost we
    945     // can have is from the extra bit in GetDistanceCost, hence 1.
    946     if (offset_cost_min < 1.) offset_cost_min = 1.;
    947 
    948     size = 1 + (int)ceil((manager->max_cost_cache_ - manager->min_cost_cache_) /
    949                          offset_cost_min);
    950     // Empirically, we usually end up with a value below 100.
    951     if (size > MAX_LENGTH) size = MAX_LENGTH;
    952 
    953     manager->interval_ends_ =
    954         (int*)WebPSafeMalloc(size, sizeof(*manager->interval_ends_));
    955     if (manager->interval_ends_ == NULL) {
    956       CostManagerClear(manager);
    957       return 0;
    958     }
    959     manager->interval_ends_size_ = size;
    960   }
    961 
    962   return 1;
    963 }
    964 
    965 // Given the distance_cost for pixel 'index', update the cost at pixel 'i' if it
    966 // is smaller than the previously computed value.
    967 static WEBP_INLINE void UpdateCost(CostManager* const manager, int i, int index,
    968                                    double distance_cost) {
    969   int k = i - index;
    970   double cost_tmp;
    971   assert(k >= 0 && k < MAX_LENGTH);
    972   cost_tmp = distance_cost + manager->cost_cache_[k];
    973 
    974   if (manager->costs_[i] > cost_tmp) {
    975     manager->costs_[i] = (float)cost_tmp;
    976     manager->dist_array_[i] = k + 1;
    977   }
    978 }
    979 
    980 // Given the distance_cost for pixel 'index', update the cost for all the pixels
    981 // between 'start' and 'end' excluded.
    982 static WEBP_INLINE void UpdateCostPerInterval(CostManager* const manager,
    983                                               int start, int end, int index,
    984                                               double distance_cost) {
    985   int i;
    986   for (i = start; i < end; ++i) UpdateCost(manager, i, index, distance_cost);
    987 }
    988 
    989 // Given two intervals, make 'prev' be the previous one of 'next' in 'manager'.
    990 static WEBP_INLINE void ConnectIntervals(CostManager* const manager,
    991                                          CostInterval* const prev,
    992                                          CostInterval* const next) {
    993   if (prev != NULL) {
    994     prev->next_ = next;
    995   } else {
    996     manager->head_ = next;
    997   }
    998 
    999   if (next != NULL) next->previous_ = prev;
   1000 }
   1001 
   1002 // Pop an interval in the manager.
   1003 static WEBP_INLINE void PopInterval(CostManager* const manager,
   1004                                     CostInterval* const interval) {
   1005   CostInterval* const next = interval->next_;
   1006 
   1007   if (interval == NULL) return;
   1008 
   1009   ConnectIntervals(manager, interval->previous_, next);
   1010   if (CostIntervalIsInFreeList(manager, interval)) {
   1011     CostIntervalAddToFreeList(manager, interval);
   1012   } else {  // recycle regularly malloc'd intervals too
   1013     interval->next_ = manager->recycled_intervals_;
   1014     manager->recycled_intervals_ = interval;
   1015   }
   1016   --manager->count_;
   1017   assert(manager->count_ >= 0);
   1018 }
   1019 
   1020 // Update the cost at index i by going over all the stored intervals that
   1021 // overlap with i.
   1022 static WEBP_INLINE void UpdateCostPerIndex(CostManager* const manager, int i) {
   1023   CostInterval* current = manager->head_;
   1024 
   1025   while (current != NULL && current->start_ <= i) {
   1026     if (current->end_ <= i) {
   1027       // We have an outdated interval, remove it.
   1028       CostInterval* next = current->next_;
   1029       PopInterval(manager, current);
   1030       current = next;
   1031     } else {
   1032       UpdateCost(manager, i, current->index_, current->distance_cost_);
   1033       current = current->next_;
   1034     }
   1035   }
   1036 }
   1037 
   1038 // Given a current orphan interval and its previous interval, before
   1039 // it was orphaned (which can be NULL), set it at the right place in the list
   1040 // of intervals using the start_ ordering and the previous interval as a hint.
   1041 static WEBP_INLINE void PositionOrphanInterval(CostManager* const manager,
   1042                                                CostInterval* const current,
   1043                                                CostInterval* previous) {
   1044   assert(current != NULL);
   1045 
   1046   if (previous == NULL) previous = manager->head_;
   1047   while (previous != NULL && current->start_ < previous->start_) {
   1048     previous = previous->previous_;
   1049   }
   1050   while (previous != NULL && previous->next_ != NULL &&
   1051          previous->next_->start_ < current->start_) {
   1052     previous = previous->next_;
   1053   }
   1054 
   1055   if (previous != NULL) {
   1056     ConnectIntervals(manager, current, previous->next_);
   1057   } else {
   1058     ConnectIntervals(manager, current, manager->head_);
   1059   }
   1060   ConnectIntervals(manager, previous, current);
   1061 }
   1062 
   1063 // Insert an interval in the list contained in the manager by starting at
   1064 // interval_in as a hint. The intervals are sorted by start_ value.
   1065 static WEBP_INLINE void InsertInterval(CostManager* const manager,
   1066                                        CostInterval* const interval_in,
   1067                                        double distance_cost, double lower,
   1068                                        double upper, int index, int start,
   1069                                        int end) {
   1070   CostInterval* interval_new;
   1071 
   1072   if (IsCostCacheIntervalWritable(start, end) ||
   1073       manager->count_ >= COST_CACHE_INTERVAL_SIZE_MAX) {
   1074     // Write down the interval if it is too small.
   1075     UpdateCostPerInterval(manager, start, end, index, distance_cost);
   1076     return;
   1077   }
   1078   if (manager->free_intervals_ != NULL) {
   1079     interval_new = manager->free_intervals_;
   1080     manager->free_intervals_ = interval_new->next_;
   1081   } else if (manager->recycled_intervals_ != NULL) {
   1082     interval_new = manager->recycled_intervals_;
   1083     manager->recycled_intervals_ = interval_new->next_;
   1084   } else {   // malloc for good
   1085     interval_new = (CostInterval*)WebPSafeMalloc(1, sizeof(*interval_new));
   1086     if (interval_new == NULL) {
   1087       // Write down the interval if we cannot create it.
   1088       UpdateCostPerInterval(manager, start, end, index, distance_cost);
   1089       return;
   1090     }
   1091   }
   1092 
   1093   interval_new->distance_cost_ = distance_cost;
   1094   interval_new->lower_ = lower;
   1095   interval_new->upper_ = upper;
   1096   interval_new->index_ = index;
   1097   interval_new->start_ = start;
   1098   interval_new->end_ = end;
   1099   PositionOrphanInterval(manager, interval_new, interval_in);
   1100 
   1101   ++manager->count_;
   1102 }
   1103 
   1104 // When an interval has its start_ or end_ modified, it needs to be
   1105 // repositioned in the linked list.
   1106 static WEBP_INLINE void RepositionInterval(CostManager* const manager,
   1107                                            CostInterval* const interval) {
   1108   if (IsCostCacheIntervalWritable(interval->start_, interval->end_)) {
   1109     // Maybe interval has been resized and is small enough to be removed.
   1110     UpdateCostPerInterval(manager, interval->start_, interval->end_,
   1111                           interval->index_, interval->distance_cost_);
   1112     PopInterval(manager, interval);
   1113     return;
   1114   }
   1115 
   1116   // Early exit if interval is at the right spot.
   1117   if ((interval->previous_ == NULL ||
   1118        interval->previous_->start_ <= interval->start_) &&
   1119       (interval->next_ == NULL ||
   1120        interval->start_ <= interval->next_->start_)) {
   1121     return;
   1122   }
   1123 
   1124   ConnectIntervals(manager, interval->previous_, interval->next_);
   1125   PositionOrphanInterval(manager, interval, interval->previous_);
   1126 }
   1127 
   1128 // Given a new cost interval defined by its start at index, its last value and
   1129 // distance_cost, add its contributions to the previous intervals and costs.
   1130 // If handling the interval or one of its subintervals becomes to heavy, its
   1131 // contribution is added to the costs right away.
   1132 static WEBP_INLINE void PushInterval(CostManager* const manager,
   1133                                      double distance_cost, int index,
   1134                                      int last) {
   1135   size_t i;
   1136   CostInterval* interval = manager->head_;
   1137   CostInterval* interval_next;
   1138   const CostCacheInterval* const cost_cache_intervals =
   1139       manager->cache_intervals_;
   1140 
   1141   for (i = 0; i < manager->cache_intervals_size_ &&
   1142               cost_cache_intervals[i].start_ < last;
   1143        ++i) {
   1144     // Define the intersection of the ith interval with the new one.
   1145     int start = index + cost_cache_intervals[i].start_;
   1146     const int end = index + (cost_cache_intervals[i].end_ > last
   1147                                  ? last
   1148                                  : cost_cache_intervals[i].end_);
   1149     const double lower_in = cost_cache_intervals[i].lower_;
   1150     const double upper_in = cost_cache_intervals[i].upper_;
   1151     const double lower_full_in = distance_cost + lower_in;
   1152     const double upper_full_in = distance_cost + upper_in;
   1153 
   1154     if (cost_cache_intervals[i].do_write_) {
   1155       UpdateCostPerInterval(manager, start, end, index, distance_cost);
   1156       continue;
   1157     }
   1158 
   1159     for (; interval != NULL && interval->start_ < end && start < end;
   1160          interval = interval_next) {
   1161       const double lower_full_interval =
   1162           interval->distance_cost_ + interval->lower_;
   1163       const double upper_full_interval =
   1164           interval->distance_cost_ + interval->upper_;
   1165 
   1166       interval_next = interval->next_;
   1167 
   1168       // Make sure we have some overlap
   1169       if (start >= interval->end_) continue;
   1170 
   1171       if (lower_full_in >= upper_full_interval) {
   1172         // When intervals are represented, the lower, the better.
   1173         // [**********************************************************]
   1174         // start                                                    end
   1175         //                   [----------------------------------]
   1176         //                   interval->start_       interval->end_
   1177         // If we are worse than what we already have, add whatever we have so
   1178         // far up to interval.
   1179         const int start_new = interval->end_;
   1180         InsertInterval(manager, interval, distance_cost, lower_in, upper_in,
   1181                        index, start, interval->start_);
   1182         start = start_new;
   1183         continue;
   1184       }
   1185 
   1186       // We know the two intervals intersect.
   1187       if (upper_full_in >= lower_full_interval) {
   1188         // There is no clear cut on which is best, so let's keep both.
   1189         // [*********[*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*]***********]
   1190         // start     interval->start_     interval->end_         end
   1191         // OR
   1192         // [*********[*-*-*-*-*-*-*-*-*-*-*-]----------------------]
   1193         // start     interval->start_     end          interval->end_
   1194         const int end_new = (interval->end_ <= end) ? interval->end_ : end;
   1195         InsertInterval(manager, interval, distance_cost, lower_in, upper_in,
   1196                        index, start, end_new);
   1197         start = end_new;
   1198       } else if (start <= interval->start_ && interval->end_ <= end) {
   1199         //                   [----------------------------------]
   1200         //                   interval->start_       interval->end_
   1201         // [**************************************************************]
   1202         // start                                                        end
   1203         // We can safely remove the old interval as it is fully included.
   1204         PopInterval(manager, interval);
   1205       } else {
   1206         if (interval->start_ <= start && end <= interval->end_) {
   1207           // [--------------------------------------------------------------]
   1208           // interval->start_                                  interval->end_
   1209           //                     [*****************************]
   1210           //                     start                       end
   1211           // We have to split the old interval as it fully contains the new one.
   1212           const int end_original = interval->end_;
   1213           interval->end_ = start;
   1214           InsertInterval(manager, interval, interval->distance_cost_,
   1215                          interval->lower_, interval->upper_, interval->index_,
   1216                          end, end_original);
   1217         } else if (interval->start_ < start) {
   1218           // [------------------------------------]
   1219           // interval->start_        interval->end_
   1220           //                     [*****************************]
   1221           //                     start                       end
   1222           interval->end_ = start;
   1223         } else {
   1224           //              [------------------------------------]
   1225           //              interval->start_        interval->end_
   1226           // [*****************************]
   1227           // start                       end
   1228           interval->start_ = end;
   1229         }
   1230 
   1231         // The interval has been modified, we need to reposition it or write it.
   1232         RepositionInterval(manager, interval);
   1233       }
   1234     }
   1235     // Insert the remaining interval from start to end.
   1236     InsertInterval(manager, interval, distance_cost, lower_in, upper_in, index,
   1237                    start, end);
   1238   }
   1239 }
   1240 
   1241 static int BackwardReferencesHashChainDistanceOnly(
   1242     int xsize, int ysize, const uint32_t* const argb, int quality,
   1243     int cache_bits, const VP8LHashChain* const hash_chain,
   1244     VP8LBackwardRefs* const refs, uint16_t* const dist_array) {
   1245   int i;
   1246   int ok = 0;
   1247   int cc_init = 0;
   1248   const int pix_count = xsize * ysize;
   1249   const int use_color_cache = (cache_bits > 0);
   1250   const size_t literal_array_size = sizeof(double) *
   1251       (NUM_LITERAL_CODES + NUM_LENGTH_CODES +
   1252        ((cache_bits > 0) ? (1 << cache_bits) : 0));
   1253   const size_t cost_model_size = sizeof(CostModel) + literal_array_size;
   1254   CostModel* const cost_model =
   1255       (CostModel*)WebPSafeCalloc(1ULL, cost_model_size);
   1256   VP8LColorCache hashers;
   1257   const int skip_length = 32 + quality;
   1258   const int skip_min_distance_code = 2;
   1259   CostManager* cost_manager =
   1260       (CostManager*)WebPSafeMalloc(1ULL, sizeof(*cost_manager));
   1261 
   1262   if (cost_model == NULL || cost_manager == NULL) goto Error;
   1263 
   1264   cost_model->literal_ = (double*)(cost_model + 1);
   1265   if (use_color_cache) {
   1266     cc_init = VP8LColorCacheInit(&hashers, cache_bits);
   1267     if (!cc_init) goto Error;
   1268   }
   1269 
   1270   if (!CostModelBuild(cost_model, cache_bits, refs)) {
   1271     goto Error;
   1272   }
   1273 
   1274   if (!CostManagerInit(cost_manager, dist_array, pix_count, cost_model)) {
   1275     goto Error;
   1276   }
   1277 
   1278   // We loop one pixel at a time, but store all currently best points to
   1279   // non-processed locations from this point.
   1280   dist_array[0] = 0;
   1281   // Add first pixel as literal.
   1282   AddSingleLiteralWithCostModel(argb + 0, &hashers, cost_model, 0,
   1283                                 use_color_cache, 0.0, cost_manager->costs_,
   1284                                 dist_array);
   1285 
   1286   for (i = 1; i < pix_count - 1; ++i) {
   1287     int offset = 0, len = 0;
   1288     double prev_cost = cost_manager->costs_[i - 1];
   1289     HashChainFindCopy(hash_chain, i, &offset, &len);
   1290     if (len >= 2) {
   1291       // If we are dealing with a non-literal.
   1292       const int code = DistanceToPlaneCode(xsize, offset);
   1293       const double offset_cost = GetDistanceCost(cost_model, code);
   1294       const int first_i = i;
   1295       int j_max = 0, interval_ends_index = 0;
   1296       const int is_offset_zero = (offset_cost == 0.);
   1297 
   1298       if (!is_offset_zero) {
   1299         j_max = (int)ceil(
   1300             (cost_manager->max_cost_cache_ - cost_manager->min_cost_cache_) /
   1301             offset_cost);
   1302         if (j_max < 1) {
   1303           j_max = 1;
   1304         } else if (j_max > cost_manager->interval_ends_size_ - 1) {
   1305           // This could only happen in the case of MAX_LENGTH.
   1306           j_max = cost_manager->interval_ends_size_ - 1;
   1307         }
   1308       }  // else j_max is unused anyway.
   1309 
   1310       // Instead of considering all contributions from a pixel i by calling:
   1311       //         PushInterval(cost_manager, prev_cost + offset_cost, i, len);
   1312       // we optimize these contributions in case offset_cost stays the same for
   1313       // consecutive pixels. This describes a set of pixels similar to a
   1314       // previous set (e.g. constant color regions).
   1315       for (; i < pix_count - 1; ++i) {
   1316         int offset_next, len_next;
   1317         prev_cost = cost_manager->costs_[i - 1];
   1318 
   1319         if (is_offset_zero) {
   1320           // No optimization can be made so we just push all of the
   1321           // contributions from i.
   1322           PushInterval(cost_manager, prev_cost, i, len);
   1323         } else {
   1324           // j_max is chosen as the smallest j such that:
   1325           //       max of cost_cache_ < j*offset cost + min of cost_cache_
   1326           // Therefore, the pixel influenced by i-j_max, cannot be influenced
   1327           // by i. Only the costs after the end of what i contributed need to be
   1328           // updated. cost_manager->interval_ends_ is a circular buffer that
   1329           // stores those ends.
   1330           const double distance_cost = prev_cost + offset_cost;
   1331           int j = cost_manager->interval_ends_[interval_ends_index];
   1332           if (i - first_i <= j_max ||
   1333               !IsCostCacheIntervalWritable(j, i + len)) {
   1334             PushInterval(cost_manager, distance_cost, i, len);
   1335           } else {
   1336             for (; j < i + len; ++j) {
   1337               UpdateCost(cost_manager, j, i, distance_cost);
   1338             }
   1339           }
   1340           // Store the new end in the circular buffer.
   1341           assert(interval_ends_index < cost_manager->interval_ends_size_);
   1342           cost_manager->interval_ends_[interval_ends_index] = i + len;
   1343           if (++interval_ends_index > j_max) interval_ends_index = 0;
   1344         }
   1345 
   1346         // Check whether i is the last pixel to consider, as it is handled
   1347         // differently.
   1348         if (i + 1 >= pix_count - 1) break;
   1349         HashChainFindCopy(hash_chain, i + 1, &offset_next, &len_next);
   1350         if (offset_next != offset) break;
   1351         len = len_next;
   1352         UpdateCostPerIndex(cost_manager, i);
   1353         AddSingleLiteralWithCostModel(argb + i, &hashers, cost_model, i,
   1354                                       use_color_cache, prev_cost,
   1355                                       cost_manager->costs_, dist_array);
   1356       }
   1357       // Submit the last pixel.
   1358       UpdateCostPerIndex(cost_manager, i + 1);
   1359 
   1360       // This if is for speedup only. It roughly doubles the speed, and
   1361       // makes compression worse by .1 %.
   1362       if (len >= skip_length && code <= skip_min_distance_code) {
   1363         // Long copy for short distances, let's skip the middle
   1364         // lookups for better copies.
   1365         // 1) insert the hashes.
   1366         if (use_color_cache) {
   1367           int k;
   1368           for (k = 0; k < len; ++k) {
   1369             VP8LColorCacheInsert(&hashers, argb[i + k]);
   1370           }
   1371         }
   1372         // 2) jump.
   1373         {
   1374           const int i_next = i + len - 1;  // for loop does ++i, thus -1 here.
   1375           for (; i <= i_next; ++i) UpdateCostPerIndex(cost_manager, i + 1);
   1376           i = i_next;
   1377         }
   1378         goto next_symbol;
   1379       }
   1380       if (len > 2) {
   1381         // Also try the smallest interval possible (size 2).
   1382         double cost_total =
   1383             prev_cost + offset_cost + GetLengthCost(cost_model, 1);
   1384         if (cost_manager->costs_[i + 1] > cost_total) {
   1385           cost_manager->costs_[i + 1] = (float)cost_total;
   1386           dist_array[i + 1] = 2;
   1387         }
   1388       }
   1389     } else {
   1390       // The pixel is added as a single literal so just update the costs.
   1391       UpdateCostPerIndex(cost_manager, i + 1);
   1392     }
   1393 
   1394     AddSingleLiteralWithCostModel(argb + i, &hashers, cost_model, i,
   1395                                   use_color_cache, prev_cost,
   1396                                   cost_manager->costs_, dist_array);
   1397 
   1398  next_symbol: ;
   1399   }
   1400   // Handle the last pixel.
   1401   if (i == (pix_count - 1)) {
   1402     AddSingleLiteralWithCostModel(
   1403         argb + i, &hashers, cost_model, i, use_color_cache,
   1404         cost_manager->costs_[pix_count - 2], cost_manager->costs_, dist_array);
   1405   }
   1406 
   1407   ok = !refs->error_;
   1408  Error:
   1409   if (cc_init) VP8LColorCacheClear(&hashers);
   1410   CostManagerClear(cost_manager);
   1411   WebPSafeFree(cost_model);
   1412   WebPSafeFree(cost_manager);
   1413   return ok;
   1414 }
   1415 
   1416 // We pack the path at the end of *dist_array and return
   1417 // a pointer to this part of the array. Example:
   1418 // dist_array = [1x2xx3x2] => packed [1x2x1232], chosen_path = [1232]
   1419 static void TraceBackwards(uint16_t* const dist_array,
   1420                            int dist_array_size,
   1421                            uint16_t** const chosen_path,
   1422                            int* const chosen_path_size) {
   1423   uint16_t* path = dist_array + dist_array_size;
   1424   uint16_t* cur = dist_array + dist_array_size - 1;
   1425   while (cur >= dist_array) {
   1426     const int k = *cur;
   1427     --path;
   1428     *path = k;
   1429     cur -= k;
   1430   }
   1431   *chosen_path = path;
   1432   *chosen_path_size = (int)(dist_array + dist_array_size - path);
   1433 }
   1434 
   1435 static int BackwardReferencesHashChainFollowChosenPath(
   1436     const uint32_t* const argb, int cache_bits,
   1437     const uint16_t* const chosen_path, int chosen_path_size,
   1438     const VP8LHashChain* const hash_chain, VP8LBackwardRefs* const refs) {
   1439   const int use_color_cache = (cache_bits > 0);
   1440   int ix;
   1441   int i = 0;
   1442   int ok = 0;
   1443   int cc_init = 0;
   1444   VP8LColorCache hashers;
   1445 
   1446   if (use_color_cache) {
   1447     cc_init = VP8LColorCacheInit(&hashers, cache_bits);
   1448     if (!cc_init) goto Error;
   1449   }
   1450 
   1451   ClearBackwardRefs(refs);
   1452   for (ix = 0; ix < chosen_path_size; ++ix) {
   1453     const int len = chosen_path[ix];
   1454     if (len != 1) {
   1455       int k;
   1456       const int offset = HashChainFindOffset(hash_chain, i);
   1457       BackwardRefsCursorAdd(refs, PixOrCopyCreateCopy(offset, len));
   1458       if (use_color_cache) {
   1459         for (k = 0; k < len; ++k) {
   1460           VP8LColorCacheInsert(&hashers, argb[i + k]);
   1461         }
   1462       }
   1463       i += len;
   1464     } else {
   1465       PixOrCopy v;
   1466       const int idx =
   1467           use_color_cache ? VP8LColorCacheContains(&hashers, argb[i]) : -1;
   1468       if (idx >= 0) {
   1469         // use_color_cache is true and hashers contains argb[i]
   1470         // push pixel as a color cache index
   1471         v = PixOrCopyCreateCacheIdx(idx);
   1472       } else {
   1473         if (use_color_cache) VP8LColorCacheInsert(&hashers, argb[i]);
   1474         v = PixOrCopyCreateLiteral(argb[i]);
   1475       }
   1476       BackwardRefsCursorAdd(refs, v);
   1477       ++i;
   1478     }
   1479   }
   1480   ok = !refs->error_;
   1481  Error:
   1482   if (cc_init) VP8LColorCacheClear(&hashers);
   1483   return ok;
   1484 }
   1485 
   1486 // Returns 1 on success.
   1487 static int BackwardReferencesTraceBackwards(
   1488     int xsize, int ysize, const uint32_t* const argb, int quality,
   1489     int cache_bits, const VP8LHashChain* const hash_chain,
   1490     VP8LBackwardRefs* const refs) {
   1491   int ok = 0;
   1492   const int dist_array_size = xsize * ysize;
   1493   uint16_t* chosen_path = NULL;
   1494   int chosen_path_size = 0;
   1495   uint16_t* dist_array =
   1496       (uint16_t*)WebPSafeMalloc(dist_array_size, sizeof(*dist_array));
   1497 
   1498   if (dist_array == NULL) goto Error;
   1499 
   1500   if (!BackwardReferencesHashChainDistanceOnly(
   1501       xsize, ysize, argb, quality, cache_bits, hash_chain,
   1502       refs, dist_array)) {
   1503     goto Error;
   1504   }
   1505   TraceBackwards(dist_array, dist_array_size, &chosen_path, &chosen_path_size);
   1506   if (!BackwardReferencesHashChainFollowChosenPath(
   1507           argb, cache_bits, chosen_path, chosen_path_size, hash_chain, refs)) {
   1508     goto Error;
   1509   }
   1510   ok = 1;
   1511  Error:
   1512   WebPSafeFree(dist_array);
   1513   return ok;
   1514 }
   1515 
   1516 static void BackwardReferences2DLocality(int xsize,
   1517                                          const VP8LBackwardRefs* const refs) {
   1518   VP8LRefsCursor c = VP8LRefsCursorInit(refs);
   1519   while (VP8LRefsCursorOk(&c)) {
   1520     if (PixOrCopyIsCopy(c.cur_pos)) {
   1521       const int dist = c.cur_pos->argb_or_distance;
   1522       const int transformed_dist = DistanceToPlaneCode(xsize, dist);
   1523       c.cur_pos->argb_or_distance = transformed_dist;
   1524     }
   1525     VP8LRefsCursorNext(&c);
   1526   }
   1527 }
   1528 
   1529 // Computes the entropies for a color cache size (in bits) between 0 (unused)
   1530 // and cache_bits_max (inclusive).
   1531 // Returns 1 on success, 0 in case of allocation error.
   1532 static int ComputeCacheEntropies(const uint32_t* argb,
   1533                                  const VP8LBackwardRefs* const refs,
   1534                                  int cache_bits_max, double entropies[]) {
   1535   int cc_init[MAX_COLOR_CACHE_BITS + 1] = { 0 };
   1536   VP8LColorCache hashers[MAX_COLOR_CACHE_BITS + 1];
   1537   VP8LRefsCursor c = VP8LRefsCursorInit(refs);
   1538   VP8LHistogram* histos[MAX_COLOR_CACHE_BITS + 1] = { NULL };
   1539   int ok = 0;
   1540   int i;
   1541 
   1542   for (i = 0; i <= cache_bits_max; ++i) {
   1543     histos[i] = VP8LAllocateHistogram(i);
   1544     if (histos[i] == NULL) goto Error;
   1545     if (i == 0) continue;
   1546     cc_init[i] = VP8LColorCacheInit(&hashers[i], i);
   1547     if (!cc_init[i]) goto Error;
   1548   }
   1549 
   1550   assert(cache_bits_max >= 0);
   1551   // Do not use the color cache for cache_bits=0.
   1552   while (VP8LRefsCursorOk(&c)) {
   1553     VP8LHistogramAddSinglePixOrCopy(histos[0], c.cur_pos);
   1554     VP8LRefsCursorNext(&c);
   1555   }
   1556   if (cache_bits_max > 0) {
   1557     c = VP8LRefsCursorInit(refs);
   1558     while (VP8LRefsCursorOk(&c)) {
   1559       const PixOrCopy* const v = c.cur_pos;
   1560       if (PixOrCopyIsLiteral(v)) {
   1561         const uint32_t pix = *argb++;
   1562         // The keys of the caches can be derived from the longest one.
   1563         int key = HashPix(pix, 32 - cache_bits_max);
   1564         for (i = cache_bits_max; i >= 1; --i, key >>= 1) {
   1565           if (VP8LColorCacheLookup(&hashers[i], key) == pix) {
   1566             ++histos[i]->literal_[NUM_LITERAL_CODES + NUM_LENGTH_CODES + key];
   1567           } else {
   1568             VP8LColorCacheSet(&hashers[i], key, pix);
   1569             ++histos[i]->blue_[pix & 0xff];
   1570             ++histos[i]->literal_[(pix >> 8) & 0xff];
   1571             ++histos[i]->red_[(pix >> 16) & 0xff];
   1572             ++histos[i]->alpha_[pix >> 24];
   1573           }
   1574         }
   1575       } else {
   1576         // Update the histograms for distance/length.
   1577         int len = PixOrCopyLength(v);
   1578         int code_dist, code_len, extra_bits;
   1579         uint32_t argb_prev = *argb ^ 0xffffffffu;
   1580         VP8LPrefixEncodeBits(len, &code_len, &extra_bits);
   1581         VP8LPrefixEncodeBits(PixOrCopyDistance(v), &code_dist, &extra_bits);
   1582         for (i = 1; i <= cache_bits_max; ++i) {
   1583           ++histos[i]->literal_[NUM_LITERAL_CODES + code_len];
   1584           ++histos[i]->distance_[code_dist];
   1585         }
   1586         // Update the colors caches.
   1587         do {
   1588           if (*argb != argb_prev) {
   1589             // Efficiency: insert only if the color changes.
   1590             int key = HashPix(*argb, 32 - cache_bits_max);
   1591             for (i = cache_bits_max; i >= 1; --i, key >>= 1) {
   1592               hashers[i].colors_[key] = *argb;
   1593             }
   1594             argb_prev = *argb;
   1595           }
   1596           argb++;
   1597         } while (--len != 0);
   1598       }
   1599       VP8LRefsCursorNext(&c);
   1600     }
   1601   }
   1602   for (i = 0; i <= cache_bits_max; ++i) {
   1603     entropies[i] = VP8LHistogramEstimateBits(histos[i]);
   1604   }
   1605   ok = 1;
   1606 Error:
   1607   for (i = 0; i <= cache_bits_max; ++i) {
   1608     if (cc_init[i]) VP8LColorCacheClear(&hashers[i]);
   1609     VP8LFreeHistogram(histos[i]);
   1610   }
   1611   return ok;
   1612 }
   1613 
   1614 // Evaluate optimal cache bits for the local color cache.
   1615 // The input *best_cache_bits sets the maximum cache bits to use (passing 0
   1616 // implies disabling the local color cache). The local color cache is also
   1617 // disabled for the lower (<= 25) quality.
   1618 // Returns 0 in case of memory error.
   1619 static int CalculateBestCacheSize(const uint32_t* const argb,
   1620                                   int xsize, int ysize, int quality,
   1621                                   const VP8LHashChain* const hash_chain,
   1622                                   VP8LBackwardRefs* const refs,
   1623                                   int* const lz77_computed,
   1624                                   int* const best_cache_bits) {
   1625   int i;
   1626   int cache_bits_high = (quality <= 25) ? 0 : *best_cache_bits;
   1627   double entropy_min = MAX_ENTROPY;
   1628   double entropies[MAX_COLOR_CACHE_BITS + 1];
   1629 
   1630   assert(cache_bits_high <= MAX_COLOR_CACHE_BITS);
   1631 
   1632   *lz77_computed = 0;
   1633   if (cache_bits_high == 0) {
   1634     *best_cache_bits = 0;
   1635     // Local color cache is disabled.
   1636     return 1;
   1637   }
   1638   // Compute LZ77 with no cache (0 bits), as the ideal LZ77 with a color cache
   1639   // is not that different in practice.
   1640   if (!BackwardReferencesLz77(xsize, ysize, argb, 0, hash_chain, refs)) {
   1641     return 0;
   1642   }
   1643   // Find the cache_bits giving the lowest entropy. The search is done in a
   1644   // brute-force way as the function (entropy w.r.t cache_bits) can be
   1645   // anything in practice.
   1646   if (!ComputeCacheEntropies(argb, refs, cache_bits_high, entropies)) {
   1647     return 0;
   1648   }
   1649   for (i = 0; i <= cache_bits_high; ++i) {
   1650     if (i == 0 || entropies[i] < entropy_min) {
   1651       entropy_min = entropies[i];
   1652       *best_cache_bits = i;
   1653     }
   1654   }
   1655   return 1;
   1656 }
   1657 
   1658 // Update (in-place) backward references for specified cache_bits.
   1659 static int BackwardRefsWithLocalCache(const uint32_t* const argb,
   1660                                       int cache_bits,
   1661                                       VP8LBackwardRefs* const refs) {
   1662   int pixel_index = 0;
   1663   VP8LColorCache hashers;
   1664   VP8LRefsCursor c = VP8LRefsCursorInit(refs);
   1665   if (!VP8LColorCacheInit(&hashers, cache_bits)) return 0;
   1666 
   1667   while (VP8LRefsCursorOk(&c)) {
   1668     PixOrCopy* const v = c.cur_pos;
   1669     if (PixOrCopyIsLiteral(v)) {
   1670       const uint32_t argb_literal = v->argb_or_distance;
   1671       const int ix = VP8LColorCacheContains(&hashers, argb_literal);
   1672       if (ix >= 0) {
   1673         // hashers contains argb_literal
   1674         *v = PixOrCopyCreateCacheIdx(ix);
   1675       } else {
   1676         VP8LColorCacheInsert(&hashers, argb_literal);
   1677       }
   1678       ++pixel_index;
   1679     } else {
   1680       // refs was created without local cache, so it can not have cache indexes.
   1681       int k;
   1682       assert(PixOrCopyIsCopy(v));
   1683       for (k = 0; k < v->len; ++k) {
   1684         VP8LColorCacheInsert(&hashers, argb[pixel_index++]);
   1685       }
   1686     }
   1687     VP8LRefsCursorNext(&c);
   1688   }
   1689   VP8LColorCacheClear(&hashers);
   1690   return 1;
   1691 }
   1692 
   1693 static VP8LBackwardRefs* GetBackwardReferencesLowEffort(
   1694     int width, int height, const uint32_t* const argb,
   1695     int* const cache_bits, const VP8LHashChain* const hash_chain,
   1696     VP8LBackwardRefs refs_array[2]) {
   1697   VP8LBackwardRefs* refs_lz77 = &refs_array[0];
   1698   *cache_bits = 0;
   1699   if (!BackwardReferencesLz77(width, height, argb, 0, hash_chain, refs_lz77)) {
   1700     return NULL;
   1701   }
   1702   BackwardReferences2DLocality(width, refs_lz77);
   1703   return refs_lz77;
   1704 }
   1705 
   1706 static VP8LBackwardRefs* GetBackwardReferences(
   1707     int width, int height, const uint32_t* const argb, int quality,
   1708     int* const cache_bits, const VP8LHashChain* const hash_chain,
   1709     VP8LBackwardRefs refs_array[2]) {
   1710   int lz77_is_useful;
   1711   int lz77_computed;
   1712   double bit_cost_lz77, bit_cost_rle;
   1713   VP8LBackwardRefs* best = NULL;
   1714   VP8LBackwardRefs* refs_lz77 = &refs_array[0];
   1715   VP8LBackwardRefs* refs_rle = &refs_array[1];
   1716   VP8LHistogram* histo = NULL;
   1717 
   1718   if (!CalculateBestCacheSize(argb, width, height, quality, hash_chain,
   1719                               refs_lz77, &lz77_computed, cache_bits)) {
   1720     goto Error;
   1721   }
   1722 
   1723   if (lz77_computed) {
   1724     // Transform refs_lz77 for the optimized cache_bits.
   1725     if (*cache_bits > 0) {
   1726       if (!BackwardRefsWithLocalCache(argb, *cache_bits, refs_lz77)) {
   1727         goto Error;
   1728       }
   1729     }
   1730   } else {
   1731     if (!BackwardReferencesLz77(width, height, argb, *cache_bits, hash_chain,
   1732                                 refs_lz77)) {
   1733       goto Error;
   1734     }
   1735   }
   1736 
   1737   if (!BackwardReferencesRle(width, height, argb, *cache_bits, refs_rle)) {
   1738     goto Error;
   1739   }
   1740 
   1741   histo = VP8LAllocateHistogram(*cache_bits);
   1742   if (histo == NULL) goto Error;
   1743 
   1744   {
   1745     // Evaluate LZ77 coding.
   1746     VP8LHistogramCreate(histo, refs_lz77, *cache_bits);
   1747     bit_cost_lz77 = VP8LHistogramEstimateBits(histo);
   1748     // Evaluate RLE coding.
   1749     VP8LHistogramCreate(histo, refs_rle, *cache_bits);
   1750     bit_cost_rle = VP8LHistogramEstimateBits(histo);
   1751     // Decide if LZ77 is useful.
   1752     lz77_is_useful = (bit_cost_lz77 < bit_cost_rle);
   1753   }
   1754 
   1755   // Choose appropriate backward reference.
   1756   if (lz77_is_useful) {
   1757     // TraceBackwards is costly. Don't execute it at lower quality.
   1758     const int try_lz77_trace_backwards = (quality >= 25);
   1759     best = refs_lz77;   // default guess: lz77 is better
   1760     if (try_lz77_trace_backwards) {
   1761       VP8LBackwardRefs* const refs_trace = refs_rle;
   1762       if (!VP8LBackwardRefsCopy(refs_lz77, refs_trace)) {
   1763         best = NULL;
   1764         goto Error;
   1765       }
   1766       if (BackwardReferencesTraceBackwards(width, height, argb, quality,
   1767                                            *cache_bits, hash_chain,
   1768                                            refs_trace)) {
   1769         double bit_cost_trace;
   1770         // Evaluate LZ77 coding.
   1771         VP8LHistogramCreate(histo, refs_trace, *cache_bits);
   1772         bit_cost_trace = VP8LHistogramEstimateBits(histo);
   1773         if (bit_cost_trace < bit_cost_lz77) {
   1774           best = refs_trace;
   1775         }
   1776       }
   1777     }
   1778   } else {
   1779     best = refs_rle;
   1780   }
   1781 
   1782   BackwardReferences2DLocality(width, best);
   1783 
   1784  Error:
   1785   VP8LFreeHistogram(histo);
   1786   return best;
   1787 }
   1788 
   1789 VP8LBackwardRefs* VP8LGetBackwardReferences(
   1790     int width, int height, const uint32_t* const argb, int quality,
   1791     int low_effort, int* const cache_bits,
   1792     const VP8LHashChain* const hash_chain, VP8LBackwardRefs refs_array[2]) {
   1793   if (low_effort) {
   1794     return GetBackwardReferencesLowEffort(width, height, argb, cache_bits,
   1795                                           hash_chain, refs_array);
   1796   } else {
   1797     return GetBackwardReferences(width, height, argb, quality, cache_bits,
   1798                                  hash_chain, refs_array);
   1799   }
   1800 }
   1801