Coverage Report

Created: 2026-07-20 07:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libwebp/src/enc/backward_references_enc.c
Line
Count
Source
1
// Copyright 2012 Google Inc. All Rights Reserved.
2
//
3
// Use of this source code is governed by a BSD-style license
4
// that can be found in the COPYING file in the root of the source
5
// tree. An additional intellectual property rights grant can be found
6
// in the file PATENTS. All contributing project authors may
7
// be found in the AUTHORS file in the root of the source tree.
8
// -----------------------------------------------------------------------------
9
//
10
// Author: Jyrki Alakuijala (jyrki@google.com)
11
//
12
13
#include "src/enc/backward_references_enc.h"
14
15
#include <assert.h>
16
#include <string.h>
17
18
#include "src/dsp/cpu.h"
19
#include "src/dsp/lossless.h"
20
#include "src/dsp/lossless_common.h"
21
#include "src/enc/histogram_enc.h"
22
#include "src/enc/vp8i_enc.h"
23
#include "src/utils/color_cache_utils.h"
24
#include "src/utils/utils.h"
25
#include "src/webp/encode.h"
26
#include "src/webp/format_constants.h"
27
#include "src/webp/types.h"
28
29
13.7k
#define MIN_BLOCK_SIZE 256  // minimum block size for backward references
30
31
// 1M window (4M bytes) minus 120 special codes for short distances.
32
8.71k
#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
1.59G
#define MIN_LENGTH 4
37
38
// -----------------------------------------------------------------------------
39
40
static const uint8_t plane_to_code_lut[128] = {
41
    96,  73,  55,  39,  23, 13, 5,  1,  255, 255, 255, 255, 255, 255, 255, 255,
42
    101, 78,  58,  42,  26, 16, 8,  2,  0,   3,   9,   17,  27,  43,  59,  79,
43
    102, 86,  62,  46,  32, 20, 10, 6,  4,   7,   11,  21,  33,  47,  63,  87,
44
    105, 90,  70,  52,  37, 28, 18, 14, 12,  15,  19,  29,  38,  53,  71,  91,
45
    110, 99,  82,  66,  48, 35, 30, 24, 22,  25,  31,  36,  49,  67,  83,  100,
46
    115, 108, 94,  76,  64, 50, 44, 40, 34,  41,  45,  51,  65,  77,  95,  109,
47
    118, 113, 103, 92,  80, 68, 60, 56, 54,  57,  61,  69,  81,  93,  104, 114,
48
    119, 116, 111, 106, 97, 88, 84, 74, 72,  75,  85,  89,  98,  107, 112, 117};
49
50
extern int VP8LDistanceToPlaneCode(int xsize, int dist);
51
48.3M
int VP8LDistanceToPlaneCode(int xsize, int dist) {
52
48.3M
  const int yoffset = dist / xsize;
53
48.3M
  const int xoffset = dist - yoffset * xsize;
54
48.3M
  if (xoffset <= 8 && yoffset < 8) {
55
5.28M
    return plane_to_code_lut[yoffset * 16 + 8 - xoffset] + 1;
56
43.0M
  } else if (xoffset > xsize - 8 && yoffset < 7) {
57
1.25M
    return plane_to_code_lut[(yoffset + 1) * 16 + 8 + (xsize - xoffset)] + 1;
58
1.25M
  }
59
41.8M
  return dist + 120;
60
48.3M
}
61
62
// Returns the exact index where array1 and array2 are different. For an index
63
// inferior or equal to best_len_match, the return value just has to be strictly
64
// inferior to best_len_match. The current behavior is to return 0 if this index
65
// is best_len_match, and the index itself otherwise.
66
// If no two elements are the same, it returns max_limit.
67
static WEBP_INLINE int FindMatchLength(const uint32_t* const array1,
68
                                       const uint32_t* const array2,
69
576M
                                       int best_len_match, int max_limit) {
70
  // Before 'expensive' linear match, check if the two arrays match at the
71
  // current best length index.
72
576M
  if (array1[best_len_match] != array2[best_len_match]) return 0;
73
74
23.0M
  return VP8LVectorMismatch(array1, array2, max_limit);
75
576M
}
76
77
// -----------------------------------------------------------------------------
78
//  VP8LBackwardRefs
79
80
struct PixOrCopyBlock {
81
  PixOrCopyBlock* next;  // next block (or NULL)
82
  PixOrCopy* start;      // data start
83
  int size;              // currently used size
84
};
85
86
extern void VP8LClearBackwardRefs(VP8LBackwardRefs* const refs);
87
34.6k
void VP8LClearBackwardRefs(VP8LBackwardRefs* const refs) {
88
34.6k
  assert(refs != NULL);
89
34.6k
  if (refs->tail != NULL) {
90
34.6k
    *refs->tail = refs->free_blocks;  // recycle all blocks at once
91
34.6k
  }
92
34.6k
  refs->free_blocks = refs->refs;
93
34.6k
  refs->tail = &refs->refs;
94
34.6k
  refs->last_block = NULL;
95
34.6k
  refs->refs = NULL;
96
34.6k
}
97
98
16.6k
void VP8LBackwardRefsClear(VP8LBackwardRefs* const refs) {
99
16.6k
  assert(refs != NULL);
100
16.6k
  VP8LClearBackwardRefs(refs);
101
32.4k
  while (refs->free_blocks != NULL) {
102
15.8k
    PixOrCopyBlock* const next = refs->free_blocks->next;
103
15.8k
    WebPSafeFree(refs->free_blocks);
104
15.8k
    refs->free_blocks = next;
105
15.8k
  }
106
16.6k
}
107
108
// Swaps the content of two VP8LBackwardRefs.
109
static void BackwardRefsSwap(VP8LBackwardRefs* const refs1,
110
12.2k
                             VP8LBackwardRefs* const refs2) {
111
12.2k
  const int point_to_refs1 =
112
12.2k
      (refs1->tail != NULL && refs1->tail == &refs1->refs);
113
12.2k
  const int point_to_refs2 =
114
12.2k
      (refs2->tail != NULL && refs2->tail == &refs2->refs);
115
12.2k
  const VP8LBackwardRefs tmp = *refs1;
116
12.2k
  *refs1 = *refs2;
117
12.2k
  *refs2 = tmp;
118
12.2k
  if (point_to_refs2) refs1->tail = &refs1->refs;
119
12.2k
  if (point_to_refs1) refs2->tail = &refs2->refs;
120
12.2k
}
121
122
11.0k
void VP8LBackwardRefsInit(VP8LBackwardRefs* const refs, int block_size) {
123
11.0k
  assert(refs != NULL);
124
11.0k
  memset(refs, 0, sizeof(*refs));
125
11.0k
  refs->tail = &refs->refs;
126
11.0k
  refs->block_size =
127
11.0k
      (block_size < MIN_BLOCK_SIZE) ? MIN_BLOCK_SIZE : block_size;
128
11.0k
}
129
130
60.8k
VP8LRefsCursor VP8LRefsCursorInit(const VP8LBackwardRefs* const refs) {
131
60.8k
  VP8LRefsCursor c;
132
60.8k
  c.cur_block = refs->refs;
133
60.8k
  if (refs->refs != NULL) {
134
60.8k
    c.cur_pos = c.cur_block->start;
135
60.8k
    c.last_pos = c.cur_pos + c.cur_block->size;
136
60.8k
  } else {
137
0
    c.cur_pos = NULL;
138
0
    c.last_pos = NULL;
139
0
  }
140
60.8k
  return c;
141
60.8k
}
142
143
87.1k
void VP8LRefsCursorNextBlock(VP8LRefsCursor* const c) {
144
87.1k
  PixOrCopyBlock* const b = c->cur_block->next;
145
87.1k
  c->cur_pos = (b == NULL) ? NULL : b->start;
146
87.1k
  c->last_pos = (b == NULL) ? NULL : b->start + b->size;
147
87.1k
  c->cur_block = b;
148
87.1k
}
149
150
// Create a new block, either from the free list or allocated
151
28.7k
static PixOrCopyBlock* BackwardRefsNewBlock(VP8LBackwardRefs* const refs) {
152
28.7k
  PixOrCopyBlock* b = refs->free_blocks;
153
28.7k
  if (b == NULL) {  // allocate new memory chunk
154
15.8k
    const size_t total_size = sizeof(*b) + refs->block_size * sizeof(*b->start);
155
15.8k
    b = (PixOrCopyBlock*)WebPSafeMalloc(1ULL, total_size);
156
15.8k
    if (b == NULL) {
157
0
      refs->error |= 1;
158
0
      return NULL;
159
0
    }
160
15.8k
    b->start = (PixOrCopy*)((uint8_t*)b + sizeof(*b));  // not always aligned
161
15.8k
  } else {  // recycle from free-list
162
12.8k
    refs->free_blocks = b->next;
163
12.8k
  }
164
28.7k
  *refs->tail = b;
165
28.7k
  refs->tail = &b->next;
166
28.7k
  refs->last_block = b;
167
28.7k
  b->next = NULL;
168
28.7k
  b->size = 0;
169
28.7k
  return b;
170
28.7k
}
171
172
// Return 1 on success, 0 on error.
173
static int BackwardRefsClone(const VP8LBackwardRefs* const from,
174
0
                             VP8LBackwardRefs* const to) {
175
0
  const PixOrCopyBlock* block_from = from->refs;
176
0
  VP8LClearBackwardRefs(to);
177
0
  while (block_from != NULL) {
178
0
    PixOrCopyBlock* const block_to = BackwardRefsNewBlock(to);
179
0
    if (block_to == NULL) return 0;
180
0
    memcpy(block_to->start, block_from->start,
181
0
           block_from->size * sizeof(PixOrCopy));
182
0
    block_to->size = block_from->size;
183
0
    block_from = block_from->next;
184
0
  }
185
0
  return 1;
186
0
}
187
188
extern void VP8LBackwardRefsCursorAdd(VP8LBackwardRefs* const refs,
189
                                      const PixOrCopy v);
190
void VP8LBackwardRefsCursorAdd(VP8LBackwardRefs* const refs,
191
376M
                               const PixOrCopy v) {
192
376M
  PixOrCopyBlock* b = refs->last_block;
193
376M
  if (b == NULL || b->size == refs->block_size) {
194
28.7k
    b = BackwardRefsNewBlock(refs);
195
28.7k
    if (b == NULL) return;  // refs->error is set
196
28.7k
  }
197
376M
  b->start[b->size++] = v;
198
376M
}
199
200
// -----------------------------------------------------------------------------
201
// Hash chains
202
203
6.59k
int VP8LHashChainInit(VP8LHashChain* const p, int size) {
204
6.59k
  assert(p->size == 0);
205
6.59k
  assert(p->offset_length == NULL);
206
6.59k
  assert(size > 0);
207
6.59k
  p->offset_length = (uint32_t*)WebPSafeMalloc(size, sizeof(*p->offset_length));
208
6.59k
  if (p->offset_length == NULL) return 0;
209
6.59k
  p->size = size;
210
211
6.59k
  return 1;
212
6.59k
}
213
214
13.2k
void VP8LHashChainClear(VP8LHashChain* const p) {
215
13.2k
  assert(p != NULL);
216
13.2k
  WebPSafeFree(p->offset_length);
217
218
13.2k
  p->size = 0;
219
13.2k
  p->offset_length = NULL;
220
13.2k
}
221
222
// -----------------------------------------------------------------------------
223
224
static const uint32_t kHashMultiplierHi = 0xc6a4a793u;
225
static const uint32_t kHashMultiplierLo = 0x5bd1e996u;
226
227
static WEBP_UBSAN_IGNORE_UNSIGNED_OVERFLOW WEBP_INLINE uint32_t
228
689M
GetPixPairHash64(const uint32_t* const argb) {
229
689M
  uint32_t key;
230
689M
  key = argb[1] * kHashMultiplierHi;
231
689M
  key += argb[0] * kHashMultiplierLo;
232
689M
  key = key >> (32 - HASH_BITS);
233
689M
  return key;
234
689M
}
235
236
// Returns the maximum number of hash chain lookups to do for a
237
// given compression quality. Return value in range [8, 86].
238
6.60k
static int GetMaxItersForQuality(int quality) {
239
6.60k
  return 8 + (quality * quality) / 128;
240
6.60k
}
241
242
6.60k
static int GetWindowSizeForHashChain(int quality, int xsize) {
243
6.60k
  const int max_window_size = (quality > 75)   ? WINDOW_SIZE
244
6.60k
                              : (quality > 50) ? (xsize << 8)
245
4.49k
                              : (quality > 25) ? (xsize << 6)
246
4.49k
                                               : (xsize << 4);
247
6.60k
  assert(xsize > 0);
248
6.60k
  return (max_window_size > WINDOW_SIZE) ? WINDOW_SIZE : max_window_size;
249
6.60k
}
250
251
288M
static WEBP_INLINE int MaxFindCopyLength(int len) {
252
288M
  return (len < MAX_LENGTH) ? len : MAX_LENGTH;
253
288M
}
254
255
int VP8LHashChainFill(VP8LHashChain* const p, int quality,
256
                      const uint32_t* const argb, int xsize, int ysize,
257
                      int low_effort, const WebPPicture* const pic,
258
6.60k
                      int percent_range, int* const percent) {
259
6.60k
  const int size = xsize * ysize;
260
6.60k
  const int iter_max = GetMaxItersForQuality(quality);
261
6.60k
  const uint32_t window_size = GetWindowSizeForHashChain(quality, xsize);
262
6.60k
  int remaining_percent = percent_range;
263
6.60k
  int percent_start = *percent;
264
6.60k
  int pos;
265
6.60k
  int argb_comp;
266
6.60k
  uint32_t base_position;
267
6.60k
  int32_t* hash_to_first_index;
268
  // Temporarily use the p->offset_length as a hash chain.
269
6.60k
  int32_t* chain = (int32_t*)p->offset_length;
270
6.60k
  assert(size > 0);
271
6.60k
  assert(p->size != 0);
272
6.60k
  assert(p->offset_length != NULL);
273
274
6.60k
  if (size <= 2) {
275
1.24k
    p->offset_length[0] = p->offset_length[size - 1] = 0;
276
1.24k
    return 1;
277
1.24k
  }
278
279
5.36k
  hash_to_first_index =
280
5.36k
      (int32_t*)WebPSafeMalloc(HASH_SIZE, sizeof(*hash_to_first_index));
281
5.36k
  if (hash_to_first_index == NULL) {
282
0
    return WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
283
0
  }
284
285
5.36k
  percent_range = remaining_percent / 2;
286
5.36k
  remaining_percent -= percent_range;
287
288
  // Set the int32_t array to -1.
289
5.36k
  memset(hash_to_first_index, 0xff, HASH_SIZE * sizeof(*hash_to_first_index));
290
  // Fill the chain linking pixels with the same hash.
291
5.36k
  argb_comp = (argb[0] == argb[1]);
292
203M
  for (pos = 0; pos < size - 2;) {
293
203M
    uint32_t hash_code;
294
203M
    const int argb_comp_next = (argb[pos + 1] == argb[pos + 2]);
295
203M
    if (argb_comp && argb_comp_next) {
296
      // Consecutive pixels with the same color will share the same hash.
297
      // We therefore use a different hash: the color and its repetition
298
      // length.
299
4.02M
      uint32_t tmp[2];
300
4.02M
      uint32_t len = 1;
301
4.02M
      tmp[0] = argb[pos];
302
      // Figure out how far the pixels are the same.
303
      // The last pixel has a different 64 bit hash, as its next pixel does
304
      // not have the same color, so we just need to get to the last pixel equal
305
      // to its follower.
306
760M
      while (pos + (int)len + 2 < size && argb[pos + len + 2] == argb[pos]) {
307
756M
        ++len;
308
756M
      }
309
4.02M
      if (len > MAX_LENGTH) {
310
        // Skip the pixels that match for distance=1 and length>MAX_LENGTH
311
        // because they are linked to their predecessor and we automatically
312
        // check that in the main for loop below. Skipping means setting no
313
        // predecessor in the chain, hence -1.
314
1.46k
        memset(chain + pos, 0xff, (len - MAX_LENGTH) * sizeof(*chain));
315
1.46k
        pos += len - MAX_LENGTH;
316
1.46k
        len = MAX_LENGTH;
317
1.46k
      }
318
      // Process the rest of the hash chain.
319
493M
      while (len) {
320
489M
        tmp[1] = len--;
321
489M
        hash_code = GetPixPairHash64(tmp);
322
489M
        chain[pos] = hash_to_first_index[hash_code];
323
489M
        hash_to_first_index[hash_code] = pos++;
324
489M
      }
325
4.02M
      argb_comp = 0;
326
199M
    } else {
327
      // Just move one pixel forward.
328
199M
      hash_code = GetPixPairHash64(argb + pos);
329
199M
      chain[pos] = hash_to_first_index[hash_code];
330
199M
      hash_to_first_index[hash_code] = pos++;
331
199M
      argb_comp = argb_comp_next;
332
199M
    }
333
334
203M
    if (!WebPReportProgress(
335
203M
            pic, percent_start + percent_range * pos / (size - 2), percent)) {
336
0
      WebPSafeFree(hash_to_first_index);
337
0
      return 0;
338
0
    }
339
203M
  }
340
  // Process the penultimate pixel.
341
5.36k
  chain[pos] = hash_to_first_index[GetPixPairHash64(argb + pos)];
342
343
5.36k
  WebPSafeFree(hash_to_first_index);
344
345
5.36k
  percent_start += percent_range;
346
5.36k
  if (!WebPReportProgress(pic, percent_start, percent)) return 0;
347
5.36k
  percent_range = remaining_percent;
348
349
  // Find the best match interval at each pixel, defined by an offset to the
350
  // pixel and a length. The right-most pixel cannot match anything to the right
351
  // (hence a best length of 0) and the left-most pixel nothing to the left
352
  // (hence an offset of 0).
353
5.36k
  assert(size > 2);
354
5.36k
  p->offset_length[0] = p->offset_length[size - 1] = 0;
355
98.9M
  for (base_position = size - 2; base_position > 0;) {
356
98.9M
    const int max_len = MaxFindCopyLength(size - 1 - base_position);
357
98.9M
    const uint32_t* const argb_start = argb + base_position;
358
98.9M
    int iter = iter_max;
359
98.9M
    int best_length = 0;
360
98.9M
    uint32_t best_distance = 0;
361
98.9M
    uint32_t best_argb;
362
98.9M
    const int min_pos =
363
98.9M
        (base_position > window_size) ? base_position - window_size : 0;
364
98.9M
    const int length_max = (max_len < 256) ? max_len : 256;
365
98.9M
    uint32_t max_base_position;
366
367
98.9M
    pos = chain[base_position];
368
98.9M
    if (!low_effort) {
369
98.9M
      int curr_length;
370
      // Heuristic: use the comparison with the above line as an initialization.
371
98.9M
      if (base_position >= (uint32_t)xsize) {
372
98.8M
        curr_length = FindMatchLength(argb_start - xsize, argb_start,
373
98.8M
                                      best_length, max_len);
374
98.8M
        if (curr_length > best_length) {
375
5.26M
          best_length = curr_length;
376
5.26M
          best_distance = xsize;
377
5.26M
        }
378
98.8M
        --iter;
379
98.8M
      }
380
      // Heuristic: compare to the previous pixel.
381
98.9M
      curr_length =
382
98.9M
          FindMatchLength(argb_start - 1, argb_start, best_length, max_len);
383
98.9M
      if (curr_length > best_length) {
384
1.95M
        best_length = curr_length;
385
1.95M
        best_distance = 1;
386
1.95M
      }
387
98.9M
      --iter;
388
      // Skip the for loop if we already have the maximum.
389
98.9M
      if (best_length == MAX_LENGTH) pos = min_pos - 1;
390
98.9M
    }
391
98.9M
    best_argb = argb_start[best_length];
392
393
726M
    for (; pos >= min_pos && --iter; pos = chain[pos]) {
394
627M
      int curr_length;
395
627M
      assert(base_position > (uint32_t)pos);
396
397
627M
      if (argb[pos + best_length] != best_argb) continue;
398
399
98.3M
      curr_length = VP8LVectorMismatch(argb + pos, argb_start, max_len);
400
98.3M
      if (best_length < curr_length) {
401
52.2M
        best_length = curr_length;
402
52.2M
        best_distance = base_position - pos;
403
52.2M
        best_argb = argb_start[best_length];
404
        // Stop if we have reached a good enough length.
405
52.2M
        if (best_length >= length_max) break;
406
52.2M
      }
407
98.3M
    }
408
    // We have the best match but in case the two intervals continue matching
409
    // to the left, we have the best matches for the left-extended pixels.
410
98.9M
    max_base_position = base_position;
411
959M
    while (1) {
412
959M
      assert(best_length <= MAX_LENGTH);
413
959M
      assert(best_distance <= WINDOW_SIZE);
414
959M
      p->offset_length[base_position] =
415
959M
          (best_distance << MAX_LENGTH_BITS) | (uint32_t)best_length;
416
959M
      --base_position;
417
      // Stop if we don't have a match or if we are out of bounds.
418
959M
      if (best_distance == 0 || base_position == 0) break;
419
      // Stop if we cannot extend the matching intervals to the left.
420
901M
      if (base_position < best_distance ||
421
901M
          argb[base_position - best_distance] != argb[base_position]) {
422
40.4M
        break;
423
40.4M
      }
424
      // Stop if we are matching at its limit because there could be a closer
425
      // matching interval with the same maximum length. Then again, if the
426
      // matching interval is as close as possible (best_distance == 1), we will
427
      // never find anything better so let's continue.
428
861M
      if (best_length == MAX_LENGTH && best_distance != 1 &&
429
438M
          base_position + MAX_LENGTH < max_base_position) {
430
105k
        break;
431
105k
      }
432
860M
      if (best_length < MAX_LENGTH) {
433
422M
        ++best_length;
434
422M
        max_base_position = base_position;
435
422M
      }
436
860M
    }
437
438
98.9M
    if (!WebPReportProgress(pic,
439
98.9M
                            percent_start + percent_range *
440
98.9M
                                                (size - 2 - base_position) /
441
98.9M
                                                (size - 2),
442
98.9M
                            percent)) {
443
0
      return 0;
444
0
    }
445
98.9M
  }
446
447
5.36k
  return WebPReportProgress(pic, percent_start + percent_range, percent);
448
5.36k
}
449
450
static WEBP_INLINE void AddSingleLiteral(uint32_t pixel, int use_color_cache,
451
                                         VP8LColorCache* const hashers,
452
274M
                                         VP8LBackwardRefs* const refs) {
453
274M
  PixOrCopy v;
454
274M
  if (use_color_cache) {
455
0
    const uint32_t key = VP8LColorCacheGetIndex(hashers, pixel);
456
0
    if (VP8LColorCacheLookup(hashers, key) == pixel) {
457
0
      v = PixOrCopyCreateCacheIdx(key);
458
0
    } else {
459
0
      v = PixOrCopyCreateLiteral(pixel);
460
0
      VP8LColorCacheSet(hashers, key, pixel);
461
0
    }
462
274M
  } else {
463
274M
    v = PixOrCopyCreateLiteral(pixel);
464
274M
  }
465
274M
  VP8LBackwardRefsCursorAdd(refs, v);
466
274M
}
467
468
static int BackwardReferencesRle(int xsize, int ysize,
469
                                 const uint32_t* const argb, int cache_bits,
470
6.60k
                                 VP8LBackwardRefs* const refs) {
471
6.60k
  const int pix_count = xsize * ysize;
472
6.60k
  int i, k;
473
6.60k
  const int use_color_cache = (cache_bits > 0);
474
6.60k
  VP8LColorCache hashers;
475
476
6.60k
  if (use_color_cache && !VP8LColorCacheInit(&hashers, cache_bits)) {
477
0
    return 0;
478
0
  }
479
6.60k
  VP8LClearBackwardRefs(refs);
480
  // Add first pixel as literal.
481
6.60k
  AddSingleLiteral(argb[0], use_color_cache, &hashers, refs);
482
6.60k
  i = 1;
483
189M
  while (i < pix_count) {
484
189M
    const int max_len = MaxFindCopyLength(pix_count - i);
485
189M
    const int rle_len = FindMatchLength(argb + i, argb + i - 1, 0, max_len);
486
189M
    const int prev_row_len =
487
189M
        (i < xsize) ? 0
488
189M
                    : FindMatchLength(argb + i, argb + i - xsize, 0, max_len);
489
189M
    if (rle_len >= prev_row_len && rle_len >= MIN_LENGTH) {
490
1.12M
      VP8LBackwardRefsCursorAdd(refs, PixOrCopyCreateCopy(1, rle_len));
491
      // We don't need to update the color cache here since it is always the
492
      // same pixel being copied, and that does not change the color cache
493
      // state.
494
1.12M
      i += rle_len;
495
188M
    } else if (prev_row_len >= MIN_LENGTH) {
496
1.54M
      VP8LBackwardRefsCursorAdd(refs, PixOrCopyCreateCopy(xsize, prev_row_len));
497
1.54M
      if (use_color_cache) {
498
0
        for (k = 0; k < prev_row_len; ++k) {
499
0
          VP8LColorCacheInsert(&hashers, argb[i + k]);
500
0
        }
501
0
      }
502
1.54M
      i += prev_row_len;
503
186M
    } else {
504
186M
      AddSingleLiteral(argb[i], use_color_cache, &hashers, refs);
505
186M
      i++;
506
186M
    }
507
189M
  }
508
6.60k
  if (use_color_cache) VP8LColorCacheClear(&hashers);
509
6.60k
  return !refs->error;
510
6.60k
}
511
512
static int BackwardReferencesLz77(int xsize, int ysize,
513
                                  const uint32_t* const argb, int cache_bits,
514
                                  const VP8LHashChain* const hash_chain,
515
7.65k
                                  VP8LBackwardRefs* const refs) {
516
7.65k
  int i;
517
7.65k
  int i_last_check = -1;
518
7.65k
  int ok = 0;
519
7.65k
  int cc_init = 0;
520
7.65k
  const int use_color_cache = (cache_bits > 0);
521
7.65k
  const int pix_count = xsize * ysize;
522
7.65k
  VP8LColorCache hashers;
523
524
7.65k
  if (use_color_cache) {
525
0
    cc_init = VP8LColorCacheInit(&hashers, cache_bits);
526
0
    if (!cc_init) goto Error;
527
0
  }
528
7.65k
  VP8LClearBackwardRefs(refs);
529
94.0M
  for (i = 0; i < pix_count;) {
530
    // Alternative#1: Code the pixels starting at 'i' using backward reference.
531
94.0M
    int offset = 0;
532
94.0M
    int len = 0;
533
94.0M
    int j;
534
94.0M
    VP8LHashChainFindCopy(hash_chain, i, &offset, &len);
535
94.0M
    if (len >= MIN_LENGTH) {
536
8.95M
      const int len_ini = len;
537
8.95M
      int max_reach = 0;
538
8.95M
      const int j_max =
539
8.95M
          (i + len_ini >= pix_count) ? pix_count - 1 : i + len_ini;
540
      // Only start from what we have not checked already.
541
8.95M
      i_last_check = (i > i_last_check) ? i : i_last_check;
542
      // We know the best match for the current pixel but we try to find the
543
      // best matches for the current pixel AND the next one combined.
544
      // The naive method would use the intervals:
545
      // [i,i+len) + [i+len, length of best match at i+len)
546
      // while we check if we can use:
547
      // [i,j) (where j<=i+len) + [j, length of best match at j)
548
1.05G
      for (j = i_last_check + 1; j <= j_max; ++j) {
549
1.04G
        const int len_j = VP8LHashChainFindLength(hash_chain, j);
550
1.04G
        const int reach =
551
1.04G
            j + (len_j >= MIN_LENGTH ? len_j : 1);  // 1 for single literal.
552
1.04G
        if (reach > max_reach) {
553
527M
          len = j - i;
554
527M
          max_reach = reach;
555
527M
          if (max_reach >= pix_count) break;
556
527M
        }
557
1.04G
      }
558
85.0M
    } else {
559
85.0M
      len = 1;
560
85.0M
    }
561
    // Go with literal or backward reference.
562
94.0M
    assert(len > 0);
563
94.0M
    if (len == 1) {
564
87.4M
      AddSingleLiteral(argb[i], use_color_cache, &hashers, refs);
565
87.4M
    } else {
566
6.55M
      VP8LBackwardRefsCursorAdd(refs, PixOrCopyCreateCopy(offset, len));
567
6.55M
      if (use_color_cache) {
568
0
        for (j = i; j < i + len; ++j) VP8LColorCacheInsert(&hashers, argb[j]);
569
0
      }
570
6.55M
    }
571
94.0M
    i += len;
572
94.0M
  }
573
574
7.65k
  ok = !refs->error;
575
7.65k
Error:
576
7.65k
  if (cc_init) VP8LColorCacheClear(&hashers);
577
7.65k
  return ok;
578
7.65k
}
579
580
// Compute an LZ77 by forcing matches to happen within a given distance cost.
581
// We therefore limit the algorithm to the lowest 32 values in the PlaneCode
582
// definition.
583
116k
#define WINDOW_OFFSETS_SIZE_MAX 32
584
static int BackwardReferencesLz77Box(int xsize, int ysize,
585
                                     const uint32_t* const argb, int cache_bits,
586
                                     const VP8LHashChain* const hash_chain_best,
587
                                     VP8LHashChain* hash_chain,
588
1.04k
                                     VP8LBackwardRefs* const refs) {
589
1.04k
  int i;
590
1.04k
  const int pix_count = xsize * ysize;
591
1.04k
  uint16_t* counts;
592
1.04k
  int window_offsets[WINDOW_OFFSETS_SIZE_MAX] = {0};
593
1.04k
  int window_offsets_new[WINDOW_OFFSETS_SIZE_MAX] = {0};
594
1.04k
  int window_offsets_size = 0;
595
1.04k
  int window_offsets_new_size = 0;
596
1.04k
  uint16_t* const counts_ini =
597
1.04k
      (uint16_t*)WebPSafeMalloc(xsize * ysize, sizeof(*counts_ini));
598
1.04k
  int best_offset_prev = -1, best_length_prev = -1;
599
1.04k
  if (counts_ini == NULL) return 0;
600
601
  // counts[i] counts how many times a pixel is repeated starting at position i.
602
1.04k
  i = pix_count - 2;
603
1.04k
  counts = counts_ini + i;
604
1.04k
  counts[1] = 1;
605
86.1M
  for (; i >= 0; --i, --counts) {
606
86.1M
    if (argb[i] == argb[i + 1]) {
607
      // Max out the counts to MAX_LENGTH.
608
81.3M
      counts[0] = counts[1] + (counts[1] != MAX_LENGTH);
609
81.3M
    } else {
610
4.74M
      counts[0] = 1;
611
4.74M
    }
612
86.1M
  }
613
614
  // Figure out the window offsets around a pixel. They are stored in a
615
  // spiraling order around the pixel as defined by VP8LDistanceToPlaneCode.
616
1.04k
  {
617
1.04k
    int x, y;
618
8.39k
    for (y = 0; y <= 6; ++y) {
619
102k
      for (x = -6; x <= 6; ++x) {
620
95.4k
        const int offset = y * xsize + x;
621
95.4k
        int plane_code;
622
        // Ignore offsets that bring us after the pixel.
623
95.4k
        if (offset <= 0) continue;
624
81.9k
        plane_code = VP8LDistanceToPlaneCode(xsize, offset) - 1;
625
81.9k
        if (plane_code >= WINDOW_OFFSETS_SIZE_MAX) continue;
626
35.5k
        window_offsets[plane_code] = offset;
627
35.5k
      }
628
7.34k
    }
629
    // For narrow images, not all plane codes are reached, so remove those.
630
34.6k
    for (i = 0; i < WINDOW_OFFSETS_SIZE_MAX; ++i) {
631
33.5k
      if (window_offsets[i] == 0) continue;
632
23.2k
      window_offsets[window_offsets_size++] = window_offsets[i];
633
23.2k
    }
634
    // Given a pixel P, find the offsets that reach pixels unreachable from P-1
635
    // with any of the offsets in window_offsets[].
636
24.3k
    for (i = 0; i < window_offsets_size; ++i) {
637
23.2k
      int j;
638
23.2k
      int is_reachable = 0;
639
389k
      for (j = 0; j < window_offsets_size && !is_reachable; ++j) {
640
366k
        is_reachable |= (window_offsets[i] == window_offsets[j] + 1);
641
366k
      }
642
23.2k
      if (!is_reachable) {
643
3.72k
        window_offsets_new[window_offsets_new_size] = window_offsets[i];
644
3.72k
        ++window_offsets_new_size;
645
3.72k
      }
646
23.2k
    }
647
1.04k
  }
648
649
1.04k
  hash_chain->offset_length[0] = 0;
650
86.1M
  for (i = 1; i < pix_count; ++i) {
651
86.1M
    int ind;
652
86.1M
    int best_length = VP8LHashChainFindLength(hash_chain_best, i);
653
86.1M
    int best_offset;
654
86.1M
    int do_compute = 1;
655
656
86.1M
    if (best_length >= MAX_LENGTH) {
657
      // Do not recompute the best match if we already have a maximal one in the
658
      // window.
659
70.3M
      best_offset = VP8LHashChainFindOffset(hash_chain_best, i);
660
104M
      for (ind = 0; ind < window_offsets_size; ++ind) {
661
103M
        if (best_offset == window_offsets[ind]) {
662
69.3M
          do_compute = 0;
663
69.3M
          break;
664
69.3M
        }
665
103M
      }
666
70.3M
    }
667
86.1M
    if (do_compute) {
668
      // Figure out if we should use the offset/length from the previous pixel
669
      // as an initial guess and therefore only inspect the offsets in
670
      // window_offsets_new[].
671
16.7M
      const int use_prev =
672
16.7M
          (best_length_prev > 1) && (best_length_prev < MAX_LENGTH);
673
16.7M
      const int num_ind =
674
16.7M
          use_prev ? window_offsets_new_size : window_offsets_size;
675
16.7M
      best_length = use_prev ? best_length_prev - 1 : 0;
676
16.7M
      best_offset = use_prev ? best_offset_prev : 0;
677
      // Find the longest match in a window around the pixel.
678
138M
      for (ind = 0; ind < num_ind; ++ind) {
679
121M
        int curr_length = 0;
680
121M
        int j = i;
681
121M
        int j_offset =
682
121M
            use_prev ? i - window_offsets_new[ind] : i - window_offsets[ind];
683
121M
        if (j_offset < 0 || argb[j_offset] != argb[i]) continue;
684
        // The longest match is the sum of how many times each pixel is
685
        // repeated.
686
356M
        do {
687
356M
          const int counts_j_offset = counts_ini[j_offset];
688
356M
          const int counts_j = counts_ini[j];
689
356M
          if (counts_j_offset != counts_j) {
690
58.7M
            curr_length +=
691
58.7M
                (counts_j_offset < counts_j) ? counts_j_offset : counts_j;
692
58.7M
            break;
693
58.7M
          }
694
          // The same color is repeated counts_pos times at j_offset and j.
695
297M
          curr_length += counts_j_offset;
696
297M
          j_offset += counts_j_offset;
697
297M
          j += counts_j_offset;
698
297M
        } while (curr_length <= MAX_LENGTH && j < pix_count &&
699
297M
                 argb[j_offset] == argb[j]);
700
62.7M
        if (best_length < curr_length) {
701
1.13M
          best_offset =
702
1.13M
              use_prev ? window_offsets_new[ind] : window_offsets[ind];
703
1.13M
          if (curr_length >= MAX_LENGTH) {
704
12.3k
            best_length = MAX_LENGTH;
705
12.3k
            break;
706
1.12M
          } else {
707
1.12M
            best_length = curr_length;
708
1.12M
          }
709
1.13M
        }
710
62.7M
      }
711
16.7M
    }
712
713
86.1M
    assert(i + best_length <= pix_count);
714
86.1M
    assert(best_length <= MAX_LENGTH);
715
86.1M
    if (best_length <= MIN_LENGTH) {
716
1.44M
      hash_chain->offset_length[i] = 0;
717
1.44M
      best_offset_prev = 0;
718
1.44M
      best_length_prev = 0;
719
84.6M
    } else {
720
84.6M
      hash_chain->offset_length[i] =
721
84.6M
          (best_offset << MAX_LENGTH_BITS) | (uint32_t)best_length;
722
84.6M
      best_offset_prev = best_offset;
723
84.6M
      best_length_prev = best_length;
724
84.6M
    }
725
86.1M
  }
726
1.04k
  hash_chain->offset_length[0] = 0;
727
1.04k
  WebPSafeFree(counts_ini);
728
729
1.04k
  return BackwardReferencesLz77(xsize, ysize, argb, cache_bits, hash_chain,
730
1.04k
                                refs);
731
1.04k
}
732
733
// -----------------------------------------------------------------------------
734
735
static void BackwardReferences2DLocality(int xsize,
736
7.65k
                                         const VP8LBackwardRefs* const refs) {
737
7.65k
  VP8LRefsCursor c = VP8LRefsCursorInit(refs);
738
95.1M
  while (VP8LRefsCursorOk(&c)) {
739
95.1M
    if (PixOrCopyIsCopy(c.cur_pos)) {
740
5.24M
      const int dist = c.cur_pos->argb_or_distance;
741
5.24M
      const int transformed_dist = VP8LDistanceToPlaneCode(xsize, dist);
742
5.24M
      c.cur_pos->argb_or_distance = transformed_dist;
743
5.24M
    }
744
95.1M
    VP8LRefsCursorNext(&c);
745
95.1M
  }
746
7.65k
}
747
748
// Evaluate optimal cache bits for the local color cache.
749
// The input *best_cache_bits sets the maximum cache bits to use (passing 0
750
// implies disabling the local color cache). The local color cache is also
751
// disabled for the lower (<= 25) quality.
752
// Returns 0 in case of memory error.
753
static int CalculateBestCacheSize(const uint32_t* argb, int quality,
754
                                  const VP8LBackwardRefs* const refs,
755
14.2k
                                  int* const best_cache_bits) {
756
14.2k
  int i;
757
14.2k
  const int cache_bits_max = (quality <= 25) ? 0 : *best_cache_bits;
758
14.2k
  uint64_t entropy_min = WEBP_UINT64_MAX;
759
14.2k
  int cc_init[MAX_COLOR_CACHE_BITS + 1] = {0};
760
14.2k
  VP8LColorCache hashers[MAX_COLOR_CACHE_BITS + 1];
761
14.2k
  VP8LRefsCursor c = VP8LRefsCursorInit(refs);
762
14.2k
  VP8LHistogram* histos[MAX_COLOR_CACHE_BITS + 1] = {NULL};
763
14.2k
  int ok = 0;
764
765
14.2k
  assert(cache_bits_max >= 0 && cache_bits_max <= MAX_COLOR_CACHE_BITS);
766
767
14.2k
  if (cache_bits_max == 0) {
768
7.67k
    *best_cache_bits = 0;
769
    // Local color cache is disabled.
770
7.67k
    return 1;
771
7.67k
  }
772
773
  // Allocate data.
774
52.8k
  for (i = 0; i <= cache_bits_max; ++i) {
775
46.2k
    histos[i] = VP8LAllocateHistogram(i);
776
46.2k
    if (histos[i] == NULL) goto Error;
777
46.2k
    VP8LHistogramInit(histos[i], i, /*init_arrays=*/1);
778
46.2k
    if (i == 0) continue;
779
39.6k
    cc_init[i] = VP8LColorCacheInit(&hashers[i], i);
780
39.6k
    if (!cc_init[i]) goto Error;
781
39.6k
  }
782
783
  // Find the cache_bits giving the lowest entropy. The search is done in a
784
  // brute-force way as the function (entropy w.r.t cache_bits) can be
785
  // anything in practice.
786
283M
  while (VP8LRefsCursorOk(&c)) {
787
283M
    const PixOrCopy* const v = c.cur_pos;
788
283M
    if (PixOrCopyIsLiteral(v)) {
789
273M
      const uint32_t pix = *argb++;
790
273M
      const uint32_t a = (pix >> 24) & 0xff;
791
273M
      const uint32_t r = (pix >> 16) & 0xff;
792
273M
      const uint32_t g = (pix >> 8) & 0xff;
793
273M
      const uint32_t b = (pix >> 0) & 0xff;
794
      // The keys of the caches can be derived from the longest one.
795
273M
      int key = VP8LHashPix(pix, 32 - cache_bits_max);
796
      // Do not use the color cache for cache_bits = 0.
797
273M
      ++histos[0]->blue[b];
798
273M
      ++histos[0]->literal[g];
799
273M
      ++histos[0]->red[r];
800
273M
      ++histos[0]->alpha[a];
801
      // Deal with cache_bits > 0.
802
2.82G
      for (i = cache_bits_max; i >= 1; --i, key >>= 1) {
803
2.55G
        if (VP8LColorCacheLookup(&hashers[i], key) == pix) {
804
690M
          ++histos[i]->literal[NUM_LITERAL_CODES + NUM_LENGTH_CODES + key];
805
1.86G
        } else {
806
1.86G
          VP8LColorCacheSet(&hashers[i], key, pix);
807
1.86G
          ++histos[i]->blue[b];
808
1.86G
          ++histos[i]->literal[g];
809
1.86G
          ++histos[i]->red[r];
810
1.86G
          ++histos[i]->alpha[a];
811
1.86G
        }
812
2.55G
      }
813
273M
    } else {
814
9.13M
      int code, extra_bits, extra_bits_value;
815
      // We should compute the contribution of the (distance,length)
816
      // histograms but those are the same independently from the cache size.
817
      // As those constant contributions are in the end added to the other
818
      // histogram contributions, we can ignore them, except for the length
819
      // prefix that is part of the 'literal' histogram.
820
9.13M
      int len = PixOrCopyLength(v);
821
9.13M
      uint32_t argb_prev = *argb ^ 0xffffffffu;
822
9.13M
      VP8LPrefixEncode(len, &code, &extra_bits, &extra_bits_value);
823
102M
      for (i = 0; i <= cache_bits_max; ++i) {
824
93.6M
        ++histos[i]->literal[NUM_LITERAL_CODES + code];
825
93.6M
      }
826
      // Update the color caches.
827
1.72G
      do {
828
1.72G
        if (*argb != argb_prev) {
829
          // Efficiency: insert only if the color changes.
830
125M
          int key = VP8LHashPix(*argb, 32 - cache_bits_max);
831
1.25G
          for (i = cache_bits_max; i >= 1; --i, key >>= 1) {
832
1.13G
            hashers[i].colors[key] = *argb;
833
1.13G
          }
834
125M
          argb_prev = *argb;
835
125M
        }
836
1.72G
        argb++;
837
1.72G
      } while (--len != 0);
838
9.13M
    }
839
283M
    VP8LRefsCursorNext(&c);
840
283M
  }
841
842
52.8k
  for (i = 0; i <= cache_bits_max; ++i) {
843
46.2k
    const uint64_t entropy = VP8LHistogramEstimateBits(histos[i]);
844
46.2k
    if (i == 0 || entropy < entropy_min) {
845
11.7k
      entropy_min = entropy;
846
11.7k
      *best_cache_bits = i;
847
11.7k
    }
848
46.2k
  }
849
6.59k
  ok = 1;
850
6.59k
Error:
851
52.8k
  for (i = 0; i <= cache_bits_max; ++i) {
852
46.2k
    if (cc_init[i]) VP8LColorCacheClear(&hashers[i]);
853
46.2k
    VP8LFreeHistogram(histos[i]);
854
46.2k
  }
855
6.59k
  return ok;
856
6.59k
}
857
858
// Update (in-place) backward references for specified cache_bits.
859
static int BackwardRefsWithLocalCache(const uint32_t* const argb,
860
                                      int cache_bits,
861
1.88k
                                      VP8LBackwardRefs* const refs) {
862
1.88k
  int pixel_index = 0;
863
1.88k
  VP8LColorCache hashers;
864
1.88k
  VP8LRefsCursor c = VP8LRefsCursorInit(refs);
865
1.88k
  if (!VP8LColorCacheInit(&hashers, cache_bits)) return 0;
866
867
176M
  while (VP8LRefsCursorOk(&c)) {
868
176M
    PixOrCopy* const v = c.cur_pos;
869
176M
    if (PixOrCopyIsLiteral(v)) {
870
171M
      const uint32_t argb_literal = v->argb_or_distance;
871
171M
      const int ix = VP8LColorCacheContains(&hashers, argb_literal);
872
171M
      if (ix >= 0) {
873
        // hashers contains argb_literal
874
47.2M
        *v = PixOrCopyCreateCacheIdx(ix);
875
123M
      } else {
876
123M
        VP8LColorCacheInsert(&hashers, argb_literal);
877
123M
      }
878
171M
      ++pixel_index;
879
171M
    } else {
880
      // refs was created without local cache, so it can not have cache indexes.
881
5.20M
      int k;
882
5.20M
      assert(PixOrCopyIsCopy(v));
883
767M
      for (k = 0; k < v->len; ++k) {
884
762M
        VP8LColorCacheInsert(&hashers, argb[pixel_index++]);
885
762M
      }
886
5.20M
    }
887
176M
    VP8LRefsCursorNext(&c);
888
176M
  }
889
1.88k
  VP8LColorCacheClear(&hashers);
890
1.88k
  return 1;
891
1.88k
}
892
893
static VP8LBackwardRefs* GetBackwardReferencesLowEffort(
894
    int width, int height, const uint32_t* const argb, int* const cache_bits,
895
0
    const VP8LHashChain* const hash_chain, VP8LBackwardRefs* const refs_lz77) {
896
0
  *cache_bits = 0;
897
0
  if (!BackwardReferencesLz77(width, height, argb, 0, hash_chain, refs_lz77)) {
898
0
    return NULL;
899
0
  }
900
0
  BackwardReferences2DLocality(width, refs_lz77);
901
0
  return refs_lz77;
902
0
}
903
904
extern int VP8LBackwardReferencesTraceBackwards(
905
    int xsize, int ysize, const uint32_t* const argb, int cache_bits,
906
    const VP8LHashChain* const hash_chain,
907
    const VP8LBackwardRefs* const refs_src, VP8LBackwardRefs* const refs_dst);
908
static int GetBackwardReferences(int width, int height,
909
                                 const uint32_t* const argb, int quality,
910
                                 int lz77_types_to_try, int cache_bits_max,
911
                                 int do_no_cache,
912
                                 const VP8LHashChain* const hash_chain,
913
                                 VP8LBackwardRefs* const refs,
914
7.65k
                                 int* const cache_bits_best) {
915
7.65k
  VP8LHistogram* histo = NULL;
916
7.65k
  int i, lz77_type;
917
  // Index 0 is for a color cache, index 1 for no cache (if needed).
918
7.65k
  int lz77_types_best[2] = {0, 0};
919
7.65k
  uint64_t bit_costs_best[2] = {WEBP_UINT64_MAX, WEBP_UINT64_MAX};
920
7.65k
  VP8LHashChain hash_chain_box;
921
7.65k
  VP8LBackwardRefs* const refs_tmp = &refs[do_no_cache ? 2 : 1];
922
7.65k
  int status = 0;
923
7.65k
  memset(&hash_chain_box, 0, sizeof(hash_chain_box));
924
925
7.65k
  histo = VP8LAllocateHistogram(MAX_COLOR_CACHE_BITS);
926
7.65k
  if (histo == NULL) goto Error;
927
928
24.0k
  for (lz77_type = 1; lz77_types_to_try;
929
16.3k
       lz77_types_to_try &= ~lz77_type, lz77_type <<= 1) {
930
16.3k
    int res = 0;
931
16.3k
    uint64_t bit_cost = 0u;
932
16.3k
    if ((lz77_types_to_try & lz77_type) == 0) continue;
933
14.2k
    switch (lz77_type) {
934
6.60k
      case kLZ77RLE:
935
6.60k
        res = BackwardReferencesRle(width, height, argb, 0, refs_tmp);
936
6.60k
        break;
937
6.60k
      case kLZ77Standard:
938
        // Compute LZ77 with no cache (0 bits), as the ideal LZ77 with a color
939
        // cache is not that different in practice.
940
6.60k
        res = BackwardReferencesLz77(width, height, argb, 0, hash_chain,
941
6.60k
                                     refs_tmp);
942
6.60k
        break;
943
1.04k
      case kLZ77Box:
944
1.04k
        if (!VP8LHashChainInit(&hash_chain_box, width * height)) goto Error;
945
1.04k
        res = BackwardReferencesLz77Box(width, height, argb, 0, hash_chain,
946
1.04k
                                        &hash_chain_box, refs_tmp);
947
1.04k
        break;
948
0
      default:
949
0
        assert(0);
950
14.2k
    }
951
14.2k
    if (!res) goto Error;
952
953
    // Start with the no color cache case.
954
42.8k
    for (i = 1; i >= 0; --i) {
955
28.5k
      int cache_bits = (i == 1) ? 0 : cache_bits_max;
956
957
28.5k
      if (i == 1 && !do_no_cache) continue;
958
959
14.2k
      if (i == 0) {
960
        // Try with a color cache.
961
14.2k
        if (!CalculateBestCacheSize(argb, quality, refs_tmp, &cache_bits)) {
962
0
          goto Error;
963
0
        }
964
14.2k
        if (cache_bits > 0) {
965
1.88k
          if (!BackwardRefsWithLocalCache(argb, cache_bits, refs_tmp)) {
966
0
            goto Error;
967
0
          }
968
1.88k
        }
969
14.2k
      }
970
971
14.2k
      if (i == 0 && do_no_cache && cache_bits == 0) {
972
        // No need to re-compute bit_cost as it was computed at i == 1.
973
14.2k
      } else {
974
14.2k
        VP8LHistogramCreate(histo, refs_tmp, cache_bits);
975
14.2k
        bit_cost = VP8LHistogramEstimateBits(histo);
976
14.2k
      }
977
978
14.2k
      if (bit_cost < bit_costs_best[i]) {
979
10.5k
        if (i == 1) {
980
          // Do not swap as the full cache analysis would have the wrong
981
          // VP8LBackwardRefs to start with.
982
0
          if (!BackwardRefsClone(refs_tmp, &refs[1])) goto Error;
983
10.5k
        } else {
984
10.5k
          BackwardRefsSwap(refs_tmp, &refs[0]);
985
10.5k
        }
986
10.5k
        bit_costs_best[i] = bit_cost;
987
10.5k
        lz77_types_best[i] = lz77_type;
988
10.5k
        if (i == 0) *cache_bits_best = cache_bits;
989
10.5k
      }
990
14.2k
    }
991
14.2k
  }
992
7.65k
  assert(lz77_types_best[0] > 0);
993
7.65k
  assert(!do_no_cache || lz77_types_best[1] > 0);
994
995
  // Improve on simple LZ77 but only for high quality (TraceBackwards is
996
  // costly).
997
22.9k
  for (i = 1; i >= 0; --i) {
998
15.3k
    if (i == 1 && !do_no_cache) continue;
999
7.65k
    if ((lz77_types_best[i] == kLZ77Standard ||
1000
3.94k
         lz77_types_best[i] == kLZ77Box) &&
1001
4.76k
        quality >= 25) {
1002
3.71k
      const VP8LHashChain* const hash_chain_tmp =
1003
3.71k
          (lz77_types_best[i] == kLZ77Standard) ? hash_chain : &hash_chain_box;
1004
3.71k
      const int cache_bits = (i == 1) ? 0 : *cache_bits_best;
1005
3.71k
      uint64_t bit_cost_trace;
1006
3.71k
      if (!VP8LBackwardReferencesTraceBackwards(width, height, argb, cache_bits,
1007
3.71k
                                                hash_chain_tmp, &refs[i],
1008
3.71k
                                                refs_tmp)) {
1009
0
        goto Error;
1010
0
      }
1011
3.71k
      VP8LHistogramCreate(histo, refs_tmp, cache_bits);
1012
3.71k
      bit_cost_trace = VP8LHistogramEstimateBits(histo);
1013
3.71k
      if (bit_cost_trace < bit_costs_best[i]) {
1014
1.71k
        BackwardRefsSwap(refs_tmp, &refs[i]);
1015
1.71k
      }
1016
3.71k
    }
1017
1018
7.65k
    BackwardReferences2DLocality(width, &refs[i]);
1019
1020
7.65k
    if (i == 1 && lz77_types_best[0] == lz77_types_best[1] &&
1021
0
        *cache_bits_best == 0) {
1022
      // If the best cache size is 0 and we have the same best LZ77, just copy
1023
      // the data over and stop here.
1024
0
      if (!BackwardRefsClone(&refs[1], &refs[0])) goto Error;
1025
0
      break;
1026
0
    }
1027
7.65k
  }
1028
7.65k
  status = 1;
1029
1030
7.65k
Error:
1031
7.65k
  VP8LHashChainClear(&hash_chain_box);
1032
7.65k
  VP8LFreeHistogram(histo);
1033
7.65k
  return status;
1034
7.65k
}
1035
1036
int VP8LGetBackwardReferences(
1037
    int width, int height, const uint32_t* const argb, int quality,
1038
    int low_effort, int lz77_types_to_try, int cache_bits_max, int do_no_cache,
1039
    const VP8LHashChain* const hash_chain, VP8LBackwardRefs* const refs,
1040
    int* const cache_bits_best, const WebPPicture* const pic, int percent_range,
1041
7.65k
    int* const percent) {
1042
7.65k
  if (low_effort) {
1043
0
    VP8LBackwardRefs* refs_best;
1044
0
    *cache_bits_best = cache_bits_max;
1045
0
    refs_best = GetBackwardReferencesLowEffort(
1046
0
        width, height, argb, cache_bits_best, hash_chain, refs);
1047
0
    if (refs_best == NULL) {
1048
0
      return WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
1049
0
    }
1050
    // Set it in first position.
1051
0
    BackwardRefsSwap(refs_best, &refs[0]);
1052
7.65k
  } else {
1053
7.65k
    if (!GetBackwardReferences(width, height, argb, quality, lz77_types_to_try,
1054
7.65k
                               cache_bits_max, do_no_cache, hash_chain, refs,
1055
7.65k
                               cache_bits_best)) {
1056
0
      return WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
1057
0
    }
1058
7.65k
  }
1059
1060
7.65k
  return WebPReportProgress(pic, *percent + percent_range, percent);
1061
7.65k
}