Coverage Report

Created: 2025-10-12 07:48

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.3k
#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.36k
#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.63G
#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
56.8M
int VP8LDistanceToPlaneCode(int xsize, int dist) {
52
56.8M
  const int yoffset = dist / xsize;
53
56.8M
  const int xoffset = dist - yoffset * xsize;
54
56.8M
  if (xoffset <= 8 && yoffset < 8) {
55
4.94M
    return plane_to_code_lut[yoffset * 16 + 8 - xoffset] + 1;
56
51.8M
  } 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
50.6M
  return dist + 120;
60
56.8M
}
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
633M
                                       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
633M
  if (array1[best_len_match] != array2[best_len_match]) return 0;
73
74
21.8M
  return VP8LVectorMismatch(array1, array2, max_limit);
75
633M
}
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
33.4k
void VP8LClearBackwardRefs(VP8LBackwardRefs* const refs) {
88
33.4k
  assert(refs != NULL);
89
33.4k
  if (refs->tail != NULL) {
90
33.4k
    *refs->tail = refs->free_blocks;  // recycle all blocks at once
91
33.4k
  }
92
33.4k
  refs->free_blocks = refs->refs;
93
33.4k
  refs->tail = &refs->refs;
94
33.4k
  refs->last_block = NULL;
95
33.4k
  refs->refs = NULL;
96
33.4k
}
97
98
16.0k
void VP8LBackwardRefsClear(VP8LBackwardRefs* const refs) {
99
16.0k
  assert(refs != NULL);
100
16.0k
  VP8LClearBackwardRefs(refs);
101
31.4k
  while (refs->free_blocks != NULL) {
102
15.3k
    PixOrCopyBlock* const next = refs->free_blocks->next;
103
15.3k
    WebPSafeFree(refs->free_blocks);
104
15.3k
    refs->free_blocks = next;
105
15.3k
  }
106
16.0k
}
107
108
// Swaps the content of two VP8LBackwardRefs.
109
static void BackwardRefsSwap(VP8LBackwardRefs* const refs1,
110
11.8k
                             VP8LBackwardRefs* const refs2) {
111
11.8k
  const int point_to_refs1 =
112
11.8k
      (refs1->tail != NULL && refs1->tail == &refs1->refs);
113
11.8k
  const int point_to_refs2 =
114
11.8k
      (refs2->tail != NULL && refs2->tail == &refs2->refs);
115
11.8k
  const VP8LBackwardRefs tmp = *refs1;
116
11.8k
  *refs1 = *refs2;
117
11.8k
  *refs2 = tmp;
118
11.8k
  if (point_to_refs2) refs1->tail = &refs1->refs;
119
11.8k
  if (point_to_refs1) refs2->tail = &refs2->refs;
120
11.8k
}
121
122
10.7k
void VP8LBackwardRefsInit(VP8LBackwardRefs* const refs, int block_size) {
123
10.7k
  assert(refs != NULL);
124
10.7k
  memset(refs, 0, sizeof(*refs));
125
10.7k
  refs->tail = &refs->refs;
126
10.7k
  refs->block_size =
127
10.7k
      (block_size < MIN_BLOCK_SIZE) ? MIN_BLOCK_SIZE : block_size;
128
10.7k
}
129
130
58.9k
VP8LRefsCursor VP8LRefsCursorInit(const VP8LBackwardRefs* const refs) {
131
58.9k
  VP8LRefsCursor c;
132
58.9k
  c.cur_block = refs->refs;
133
58.9k
  if (refs->refs != NULL) {
134
58.9k
    c.cur_pos = c.cur_block->start;
135
58.9k
    c.last_pos = c.cur_pos + c.cur_block->size;
136
58.9k
  } else {
137
0
    c.cur_pos = NULL;
138
0
    c.last_pos = NULL;
139
0
  }
140
58.9k
  return c;
141
58.9k
}
142
143
84.8k
void VP8LRefsCursorNextBlock(VP8LRefsCursor* const c) {
144
84.8k
  PixOrCopyBlock* const b = c->cur_block->next;
145
84.8k
  c->cur_pos = (b == NULL) ? NULL : b->start;
146
84.8k
  c->last_pos = (b == NULL) ? NULL : b->start + b->size;
147
84.8k
  c->cur_block = b;
148
84.8k
}
149
150
// Create a new block, either from the free list or allocated
151
27.9k
static PixOrCopyBlock* BackwardRefsNewBlock(VP8LBackwardRefs* const refs) {
152
27.9k
  PixOrCopyBlock* b = refs->free_blocks;
153
27.9k
  if (b == NULL) {  // allocate new memory chunk
154
15.3k
    const size_t total_size = sizeof(*b) + refs->block_size * sizeof(*b->start);
155
15.3k
    b = (PixOrCopyBlock*)WebPSafeMalloc(1ULL, total_size);
156
15.3k
    if (b == NULL) {
157
0
      refs->error |= 1;
158
0
      return NULL;
159
0
    }
160
15.3k
    b->start = (PixOrCopy*)((uint8_t*)b + sizeof(*b));  // not always aligned
161
15.3k
  } else {  // recycle from free-list
162
12.5k
    refs->free_blocks = b->next;
163
12.5k
  }
164
27.9k
  *refs->tail = b;
165
27.9k
  refs->tail = &b->next;
166
27.9k
  refs->last_block = b;
167
27.9k
  b->next = NULL;
168
27.9k
  b->size = 0;
169
27.9k
  return b;
170
27.9k
}
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
409M
                               const PixOrCopy v) {
192
409M
  PixOrCopyBlock* b = refs->last_block;
193
409M
  if (b == NULL || b->size == refs->block_size) {
194
27.9k
    b = BackwardRefsNewBlock(refs);
195
27.9k
    if (b == NULL) return;  // refs->error is set
196
27.9k
  }
197
409M
  b->start[b->size++] = v;
198
409M
}
199
200
// -----------------------------------------------------------------------------
201
// Hash chains
202
203
6.40k
int VP8LHashChainInit(VP8LHashChain* const p, int size) {
204
6.40k
  assert(p->size == 0);
205
6.40k
  assert(p->offset_length == NULL);
206
6.40k
  assert(size > 0);
207
6.40k
  p->offset_length = (uint32_t*)WebPSafeMalloc(size, sizeof(*p->offset_length));
208
6.40k
  if (p->offset_length == NULL) return 0;
209
6.40k
  p->size = size;
210
211
6.40k
  return 1;
212
6.40k
}
213
214
12.7k
void VP8LHashChainClear(VP8LHashChain* const p) {
215
12.7k
  assert(p != NULL);
216
12.7k
  WebPSafeFree(p->offset_length);
217
218
12.7k
  p->size = 0;
219
12.7k
  p->offset_length = NULL;
220
12.7k
}
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
665M
GetPixPairHash64(const uint32_t* const argb) {
229
665M
  uint32_t key;
230
665M
  key = argb[1] * kHashMultiplierHi;
231
665M
  key += argb[0] * kHashMultiplierLo;
232
665M
  key = key >> (32 - HASH_BITS);
233
665M
  return key;
234
665M
}
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.39k
static int GetMaxItersForQuality(int quality) {
239
6.39k
  return 8 + (quality * quality) / 128;
240
6.39k
}
241
242
6.39k
static int GetWindowSizeForHashChain(int quality, int xsize) {
243
6.39k
  const int max_window_size = (quality > 75)   ? WINDOW_SIZE
244
6.39k
                              : (quality > 50) ? (xsize << 8)
245
4.41k
                              : (quality > 25) ? (xsize << 6)
246
4.41k
                                               : (xsize << 4);
247
6.39k
  assert(xsize > 0);
248
6.39k
  return (max_window_size > WINDOW_SIZE) ? WINDOW_SIZE : max_window_size;
249
6.39k
}
250
251
316M
static WEBP_INLINE int MaxFindCopyLength(int len) {
252
316M
  return (len < MAX_LENGTH) ? len : MAX_LENGTH;
253
316M
}
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.39k
                      int percent_range, int* const percent) {
259
6.39k
  const int size = xsize * ysize;
260
6.39k
  const int iter_max = GetMaxItersForQuality(quality);
261
6.39k
  const uint32_t window_size = GetWindowSizeForHashChain(quality, xsize);
262
6.39k
  int remaining_percent = percent_range;
263
6.39k
  int percent_start = *percent;
264
6.39k
  int pos;
265
6.39k
  int argb_comp;
266
6.39k
  uint32_t base_position;
267
6.39k
  int32_t* hash_to_first_index;
268
  // Temporarily use the p->offset_length as a hash chain.
269
6.39k
  int32_t* chain = (int32_t*)p->offset_length;
270
6.39k
  assert(size > 0);
271
6.39k
  assert(p->size != 0);
272
6.39k
  assert(p->offset_length != NULL);
273
274
6.39k
  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.14k
  hash_to_first_index =
280
5.14k
      (int32_t*)WebPSafeMalloc(HASH_SIZE, sizeof(*hash_to_first_index));
281
5.14k
  if (hash_to_first_index == NULL) {
282
0
    return WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
283
0
  }
284
285
5.14k
  percent_range = remaining_percent / 2;
286
5.14k
  remaining_percent -= percent_range;
287
288
  // Set the int32_t array to -1.
289
5.14k
  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.14k
  argb_comp = (argb[0] == argb[1]);
292
222M
  for (pos = 0; pos < size - 2;) {
293
222M
    uint32_t hash_code;
294
222M
    const int argb_comp_next = (argb[pos + 1] == argb[pos + 2]);
295
222M
    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
3.88M
      uint32_t tmp[2];
300
3.88M
      uint32_t len = 1;
301
3.88M
      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
744M
      while (pos + (int)len + 2 < size && argb[pos + len + 2] == argb[pos]) {
307
740M
        ++len;
308
740M
      }
309
3.88M
      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.73k
        memset(chain + pos, 0xff, (len - MAX_LENGTH) * sizeof(*chain));
315
1.73k
        pos += len - MAX_LENGTH;
316
1.73k
        len = MAX_LENGTH;
317
1.73k
      }
318
      // Process the rest of the hash chain.
319
450M
      while (len) {
320
447M
        tmp[1] = len--;
321
447M
        hash_code = GetPixPairHash64(tmp);
322
447M
        chain[pos] = hash_to_first_index[hash_code];
323
447M
        hash_to_first_index[hash_code] = pos++;
324
447M
      }
325
3.88M
      argb_comp = 0;
326
218M
    } else {
327
      // Just move one pixel forward.
328
218M
      hash_code = GetPixPairHash64(argb + pos);
329
218M
      chain[pos] = hash_to_first_index[hash_code];
330
218M
      hash_to_first_index[hash_code] = pos++;
331
218M
      argb_comp = argb_comp_next;
332
218M
    }
333
334
222M
    if (!WebPReportProgress(
335
222M
            pic, percent_start + percent_range * pos / (size - 2), percent)) {
336
0
      WebPSafeFree(hash_to_first_index);
337
0
      return 0;
338
0
    }
339
222M
  }
340
  // Process the penultimate pixel.
341
5.14k
  chain[pos] = hash_to_first_index[GetPixPairHash64(argb + pos)];
342
343
5.14k
  WebPSafeFree(hash_to_first_index);
344
345
5.14k
  percent_start += percent_range;
346
5.14k
  if (!WebPReportProgress(pic, percent_start, percent)) return 0;
347
5.14k
  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.14k
  assert(size > 2);
354
5.14k
  p->offset_length[0] = p->offset_length[size - 1] = 0;
355
108M
  for (base_position = size - 2; base_position > 0;) {
356
108M
    const int max_len = MaxFindCopyLength(size - 1 - base_position);
357
108M
    const uint32_t* const argb_start = argb + base_position;
358
108M
    int iter = iter_max;
359
108M
    int best_length = 0;
360
108M
    uint32_t best_distance = 0;
361
108M
    uint32_t best_argb;
362
108M
    const int min_pos =
363
108M
        (base_position > window_size) ? base_position - window_size : 0;
364
108M
    const int length_max = (max_len < 256) ? max_len : 256;
365
108M
    uint32_t max_base_position;
366
367
108M
    pos = chain[base_position];
368
108M
    if (!low_effort) {
369
108M
      int curr_length;
370
      // Heuristic: use the comparison with the above line as an initialization.
371
108M
      if (base_position >= (uint32_t)xsize) {
372
108M
        curr_length = FindMatchLength(argb_start - xsize, argb_start,
373
108M
                                      best_length, max_len);
374
108M
        if (curr_length > best_length) {
375
4.82M
          best_length = curr_length;
376
4.82M
          best_distance = xsize;
377
4.82M
        }
378
108M
        --iter;
379
108M
      }
380
      // Heuristic: compare to the previous pixel.
381
108M
      curr_length =
382
108M
          FindMatchLength(argb_start - 1, argb_start, best_length, max_len);
383
108M
      if (curr_length > best_length) {
384
2.76M
        best_length = curr_length;
385
2.76M
        best_distance = 1;
386
2.76M
      }
387
108M
      --iter;
388
      // Skip the for loop if we already have the maximum.
389
108M
      if (best_length == MAX_LENGTH) pos = min_pos - 1;
390
108M
    }
391
108M
    best_argb = argb_start[best_length];
392
393
1.14G
    for (; pos >= min_pos && --iter; pos = chain[pos]) {
394
1.03G
      int curr_length;
395
1.03G
      assert(base_position > (uint32_t)pos);
396
397
1.03G
      if (argb[pos + best_length] != best_argb) continue;
398
399
103M
      curr_length = VP8LVectorMismatch(argb + pos, argb_start, max_len);
400
103M
      if (best_length < curr_length) {
401
64.7M
        best_length = curr_length;
402
64.7M
        best_distance = base_position - pos;
403
64.7M
        best_argb = argb_start[best_length];
404
        // Stop if we have reached a good enough length.
405
64.7M
        if (best_length >= length_max) break;
406
64.7M
      }
407
103M
    }
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
108M
    max_base_position = base_position;
411
963M
    while (1) {
412
963M
      assert(best_length <= MAX_LENGTH);
413
963M
      assert(best_distance <= WINDOW_SIZE);
414
963M
      p->offset_length[base_position] =
415
963M
          (best_distance << MAX_LENGTH_BITS) | (uint32_t)best_length;
416
963M
      --base_position;
417
      // Stop if we don't have a match or if we are out of bounds.
418
963M
      if (best_distance == 0 || base_position == 0) break;
419
      // Stop if we cannot extend the matching intervals to the left.
420
902M
      if (base_position < best_distance ||
421
902M
          argb[base_position - best_distance] != argb[base_position]) {
422
47.8M
        break;
423
47.8M
      }
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
854M
      if (best_length == MAX_LENGTH && best_distance != 1 &&
429
446M
          base_position + MAX_LENGTH < max_base_position) {
430
107k
        break;
431
107k
      }
432
854M
      if (best_length < MAX_LENGTH) {
433
407M
        ++best_length;
434
407M
        max_base_position = base_position;
435
407M
      }
436
854M
    }
437
438
108M
    if (!WebPReportProgress(pic,
439
108M
                            percent_start + percent_range *
440
108M
                                                (size - 2 - base_position) /
441
108M
                                                (size - 2),
442
108M
                            percent)) {
443
0
      return 0;
444
0
    }
445
108M
  }
446
447
5.14k
  return WebPReportProgress(pic, percent_start + percent_range, percent);
448
5.14k
}
449
450
static WEBP_INLINE void AddSingleLiteral(uint32_t pixel, int use_color_cache,
451
                                         VP8LColorCache* const hashers,
452
299M
                                         VP8LBackwardRefs* const refs) {
453
299M
  PixOrCopy v;
454
299M
  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
299M
  } else {
463
299M
    v = PixOrCopyCreateLiteral(pixel);
464
299M
  }
465
299M
  VP8LBackwardRefsCursorAdd(refs, v);
466
299M
}
467
468
static int BackwardReferencesRle(int xsize, int ysize,
469
                                 const uint32_t* const argb, int cache_bits,
470
6.39k
                                 VP8LBackwardRefs* const refs) {
471
6.39k
  const int pix_count = xsize * ysize;
472
6.39k
  int i, k;
473
6.39k
  const int use_color_cache = (cache_bits > 0);
474
6.39k
  VP8LColorCache hashers;
475
476
6.39k
  if (use_color_cache && !VP8LColorCacheInit(&hashers, cache_bits)) {
477
0
    return 0;
478
0
  }
479
6.39k
  VP8LClearBackwardRefs(refs);
480
  // Add first pixel as literal.
481
6.39k
  AddSingleLiteral(argb[0], use_color_cache, &hashers, refs);
482
6.39k
  i = 1;
483
207M
  while (i < pix_count) {
484
207M
    const int max_len = MaxFindCopyLength(pix_count - i);
485
207M
    const int rle_len = FindMatchLength(argb + i, argb + i - 1, 0, max_len);
486
207M
    const int prev_row_len =
487
207M
        (i < xsize) ? 0
488
207M
                    : FindMatchLength(argb + i, argb + i - xsize, 0, max_len);
489
207M
    if (rle_len >= prev_row_len && rle_len >= MIN_LENGTH) {
490
1.45M
      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.45M
      i += rle_len;
495
206M
    } else if (prev_row_len >= MIN_LENGTH) {
496
1.30M
      VP8LBackwardRefsCursorAdd(refs, PixOrCopyCreateCopy(xsize, prev_row_len));
497
1.30M
      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.30M
      i += prev_row_len;
503
205M
    } else {
504
205M
      AddSingleLiteral(argb[i], use_color_cache, &hashers, refs);
505
205M
      i++;
506
205M
    }
507
207M
  }
508
6.39k
  if (use_color_cache) VP8LColorCacheClear(&hashers);
509
6.39k
  return !refs->error;
510
6.39k
}
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.43k
                                  VP8LBackwardRefs* const refs) {
516
7.43k
  int i;
517
7.43k
  int i_last_check = -1;
518
7.43k
  int ok = 0;
519
7.43k
  int cc_init = 0;
520
7.43k
  const int use_color_cache = (cache_bits > 0);
521
7.43k
  const int pix_count = xsize * ysize;
522
7.43k
  VP8LColorCache hashers;
523
524
7.43k
  if (use_color_cache) {
525
0
    cc_init = VP8LColorCacheInit(&hashers, cache_bits);
526
0
    if (!cc_init) goto Error;
527
0
  }
528
7.43k
  VP8LClearBackwardRefs(refs);
529
100M
  for (i = 0; i < pix_count;) {
530
    // Alternative#1: Code the pixels starting at 'i' using backward reference.
531
100M
    int offset = 0;
532
100M
    int len = 0;
533
100M
    int j;
534
100M
    VP8LHashChainFindCopy(hash_chain, i, &offset, &len);
535
100M
    if (len >= MIN_LENGTH) {
536
9.00M
      const int len_ini = len;
537
9.00M
      int max_reach = 0;
538
9.00M
      const int j_max =
539
9.00M
          (i + len_ini >= pix_count) ? pix_count - 1 : i + len_ini;
540
      // Only start from what we have not checked already.
541
9.00M
      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.04G
      for (j = i_last_check + 1; j <= j_max; ++j) {
549
1.03G
        const int len_j = VP8LHashChainFindLength(hash_chain, j);
550
1.03G
        const int reach =
551
1.03G
            j + (len_j >= MIN_LENGTH ? len_j : 1);  // 1 for single literal.
552
1.03G
        if (reach > max_reach) {
553
541M
          len = j - i;
554
541M
          max_reach = reach;
555
541M
          if (max_reach >= pix_count) break;
556
541M
        }
557
1.03G
      }
558
91.7M
    } else {
559
91.7M
      len = 1;
560
91.7M
    }
561
    // Go with literal or backward reference.
562
100M
    assert(len > 0);
563
100M
    if (len == 1) {
564
94.1M
      AddSingleLiteral(argb[i], use_color_cache, &hashers, refs);
565
94.1M
    } else {
566
6.56M
      VP8LBackwardRefsCursorAdd(refs, PixOrCopyCreateCopy(offset, len));
567
6.56M
      if (use_color_cache) {
568
0
        for (j = i; j < i + len; ++j) VP8LColorCacheInsert(&hashers, argb[j]);
569
0
      }
570
6.56M
    }
571
100M
    i += len;
572
100M
  }
573
574
7.43k
  ok = !refs->error;
575
7.43k
Error:
576
7.43k
  if (cc_init) VP8LColorCacheClear(&hashers);
577
7.43k
  return ok;
578
7.43k
}
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
85.6M
  for (; i >= 0; --i, --counts) {
606
85.6M
    if (argb[i] == argb[i + 1]) {
607
      // Max out the counts to MAX_LENGTH.
608
83.0M
      counts[0] = counts[1] + (counts[1] != MAX_LENGTH);
609
83.0M
    } else {
610
2.63M
      counts[0] = 1;
611
2.63M
    }
612
85.6M
  }
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.36k
    for (y = 0; y <= 6; ++y) {
619
102k
      for (x = -6; x <= 6; ++x) {
620
95.1k
        const int offset = y * xsize + x;
621
95.1k
        int plane_code;
622
        // Ignore offsets that bring us after the pixel.
623
95.1k
        if (offset <= 0) continue;
624
82.0k
        plane_code = VP8LDistanceToPlaneCode(xsize, offset) - 1;
625
82.0k
        if (plane_code >= WINDOW_OFFSETS_SIZE_MAX) continue;
626
35.6k
        window_offsets[plane_code] = offset;
627
35.6k
      }
628
7.32k
    }
629
    // For narrow images, not all plane codes are reached, so remove those.
630
34.5k
    for (i = 0; i < WINDOW_OFFSETS_SIZE_MAX; ++i) {
631
33.4k
      if (window_offsets[i] == 0) continue;
632
23.5k
      window_offsets[window_offsets_size++] = window_offsets[i];
633
23.5k
    }
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.6k
    for (i = 0; i < window_offsets_size; ++i) {
637
23.5k
      int j;
638
23.5k
      int is_reachable = 0;
639
394k
      for (j = 0; j < window_offsets_size && !is_reachable; ++j) {
640
370k
        is_reachable |= (window_offsets[i] == window_offsets[j] + 1);
641
370k
      }
642
23.5k
      if (!is_reachable) {
643
3.75k
        window_offsets_new[window_offsets_new_size] = window_offsets[i];
644
3.75k
        ++window_offsets_new_size;
645
3.75k
      }
646
23.5k
    }
647
1.04k
  }
648
649
1.04k
  hash_chain->offset_length[0] = 0;
650
85.6M
  for (i = 1; i < pix_count; ++i) {
651
85.6M
    int ind;
652
85.6M
    int best_length = VP8LHashChainFindLength(hash_chain_best, i);
653
85.6M
    int best_offset;
654
85.6M
    int do_compute = 1;
655
656
85.6M
    if (best_length >= MAX_LENGTH) {
657
      // Do not recompute the best match if we already have a maximal one in the
658
      // window.
659
75.2M
      best_offset = VP8LHashChainFindOffset(hash_chain_best, i);
660
91.9M
      for (ind = 0; ind < window_offsets_size; ++ind) {
661
91.5M
        if (best_offset == window_offsets[ind]) {
662
74.8M
          do_compute = 0;
663
74.8M
          break;
664
74.8M
        }
665
91.5M
      }
666
75.2M
    }
667
85.6M
    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
10.7M
      const int use_prev =
672
10.7M
          (best_length_prev > 1) && (best_length_prev < MAX_LENGTH);
673
10.7M
      const int num_ind =
674
10.7M
          use_prev ? window_offsets_new_size : window_offsets_size;
675
10.7M
      best_length = use_prev ? best_length_prev - 1 : 0;
676
10.7M
      best_offset = use_prev ? best_offset_prev : 0;
677
      // Find the longest match in a window around the pixel.
678
79.2M
      for (ind = 0; ind < num_ind; ++ind) {
679
68.5M
        int curr_length = 0;
680
68.5M
        int j = i;
681
68.5M
        int j_offset =
682
68.5M
            use_prev ? i - window_offsets_new[ind] : i - window_offsets[ind];
683
68.5M
        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
186M
        do {
687
186M
          const int counts_j_offset = counts_ini[j_offset];
688
186M
          const int counts_j = counts_ini[j];
689
186M
          if (counts_j_offset != counts_j) {
690
40.7M
            curr_length +=
691
40.7M
                (counts_j_offset < counts_j) ? counts_j_offset : counts_j;
692
40.7M
            break;
693
40.7M
          }
694
          // The same color is repeated counts_pos times at j_offset and j.
695
146M
          curr_length += counts_j_offset;
696
146M
          j_offset += counts_j_offset;
697
146M
          j += counts_j_offset;
698
146M
        } while (curr_length <= MAX_LENGTH && j < pix_count &&
699
145M
                 argb[j_offset] == argb[j]);
700
42.7M
        if (best_length < curr_length) {
701
529k
          best_offset =
702
529k
              use_prev ? window_offsets_new[ind] : window_offsets[ind];
703
529k
          if (curr_length >= MAX_LENGTH) {
704
4.23k
            best_length = MAX_LENGTH;
705
4.23k
            break;
706
525k
          } else {
707
525k
            best_length = curr_length;
708
525k
          }
709
529k
        }
710
42.7M
      }
711
10.7M
    }
712
713
85.6M
    assert(i + best_length <= pix_count);
714
85.6M
    assert(best_length <= MAX_LENGTH);
715
85.6M
    if (best_length <= MIN_LENGTH) {
716
567k
      hash_chain->offset_length[i] = 0;
717
567k
      best_offset_prev = 0;
718
567k
      best_length_prev = 0;
719
85.0M
    } else {
720
85.0M
      hash_chain->offset_length[i] =
721
85.0M
          (best_offset << MAX_LENGTH_BITS) | (uint32_t)best_length;
722
85.0M
      best_offset_prev = best_offset;
723
85.0M
      best_length_prev = best_length;
724
85.0M
    }
725
85.6M
  }
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.43k
                                         const VP8LBackwardRefs* const refs) {
737
7.43k
  VP8LRefsCursor c = VP8LRefsCursorInit(refs);
738
101M
  while (VP8LRefsCursorOk(&c)) {
739
101M
    if (PixOrCopyIsCopy(c.cur_pos)) {
740
5.37M
      const int dist = c.cur_pos->argb_or_distance;
741
5.37M
      const int transformed_dist = VP8LDistanceToPlaneCode(xsize, dist);
742
5.37M
      c.cur_pos->argb_or_distance = transformed_dist;
743
5.37M
    }
744
101M
    VP8LRefsCursorNext(&c);
745
101M
  }
746
7.43k
}
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
13.8k
                                  int* const best_cache_bits) {
756
13.8k
  int i;
757
13.8k
  const int cache_bits_max = (quality <= 25) ? 0 : *best_cache_bits;
758
13.8k
  uint64_t entropy_min = WEBP_UINT64_MAX;
759
13.8k
  int cc_init[MAX_COLOR_CACHE_BITS + 1] = {0};
760
13.8k
  VP8LColorCache hashers[MAX_COLOR_CACHE_BITS + 1];
761
13.8k
  VP8LRefsCursor c = VP8LRefsCursorInit(refs);
762
13.8k
  VP8LHistogram* histos[MAX_COLOR_CACHE_BITS + 1] = {NULL};
763
13.8k
  int ok = 0;
764
765
13.8k
  assert(cache_bits_max >= 0 && cache_bits_max <= MAX_COLOR_CACHE_BITS);
766
767
13.8k
  if (cache_bits_max == 0) {
768
7.42k
    *best_cache_bits = 0;
769
    // Local color cache is disabled.
770
7.42k
    return 1;
771
7.42k
  }
772
773
  // Allocate data.
774
50.4k
  for (i = 0; i <= cache_bits_max; ++i) {
775
44.0k
    histos[i] = VP8LAllocateHistogram(i);
776
44.0k
    if (histos[i] == NULL) goto Error;
777
44.0k
    VP8LHistogramInit(histos[i], i, /*init_arrays=*/1);
778
44.0k
    if (i == 0) continue;
779
37.6k
    cc_init[i] = VP8LColorCacheInit(&hashers[i], i);
780
37.6k
    if (!cc_init[i]) goto Error;
781
37.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
308M
  while (VP8LRefsCursorOk(&c)) {
787
308M
    const PixOrCopy* const v = c.cur_pos;
788
308M
    if (PixOrCopyIsLiteral(v)) {
789
299M
      const uint32_t pix = *argb++;
790
299M
      const uint32_t a = (pix >> 24) & 0xff;
791
299M
      const uint32_t r = (pix >> 16) & 0xff;
792
299M
      const uint32_t g = (pix >> 8) & 0xff;
793
299M
      const uint32_t b = (pix >> 0) & 0xff;
794
      // The keys of the caches can be derived from the longest one.
795
299M
      int key = VP8LHashPix(pix, 32 - cache_bits_max);
796
      // Do not use the color cache for cache_bits = 0.
797
299M
      ++histos[0]->blue[b];
798
299M
      ++histos[0]->literal[g];
799
299M
      ++histos[0]->red[r];
800
299M
      ++histos[0]->alpha[a];
801
      // Deal with cache_bits > 0.
802
3.09G
      for (i = cache_bits_max; i >= 1; --i, key >>= 1) {
803
2.79G
        if (VP8LColorCacheLookup(&hashers[i], key) == pix) {
804
746M
          ++histos[i]->literal[NUM_LITERAL_CODES + NUM_LENGTH_CODES + key];
805
2.04G
        } else {
806
2.04G
          VP8LColorCacheSet(&hashers[i], key, pix);
807
2.04G
          ++histos[i]->blue[b];
808
2.04G
          ++histos[i]->literal[g];
809
2.04G
          ++histos[i]->red[r];
810
2.04G
          ++histos[i]->alpha[a];
811
2.04G
        }
812
2.79G
      }
813
299M
    } else {
814
9.24M
      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.24M
      int len = PixOrCopyLength(v);
821
9.24M
      uint32_t argb_prev = *argb ^ 0xffffffffu;
822
9.24M
      VP8LPrefixEncode(len, &code, &extra_bits, &extra_bits_value);
823
103M
      for (i = 0; i <= cache_bits_max; ++i) {
824
94.5M
        ++histos[i]->literal[NUM_LITERAL_CODES + code];
825
94.5M
      }
826
      // Update the color caches.
827
1.71G
      do {
828
1.71G
        if (*argb != argb_prev) {
829
          // Efficiency: insert only if the color changes.
830
138M
          int key = VP8LHashPix(*argb, 32 - cache_bits_max);
831
1.39G
          for (i = cache_bits_max; i >= 1; --i, key >>= 1) {
832
1.26G
            hashers[i].colors[key] = *argb;
833
1.26G
          }
834
138M
          argb_prev = *argb;
835
138M
        }
836
1.71G
        argb++;
837
1.71G
      } while (--len != 0);
838
9.24M
    }
839
308M
    VP8LRefsCursorNext(&c);
840
308M
  }
841
842
50.4k
  for (i = 0; i <= cache_bits_max; ++i) {
843
44.0k
    const uint64_t entropy = VP8LHistogramEstimateBits(histos[i]);
844
44.0k
    if (i == 0 || entropy < entropy_min) {
845
11.0k
      entropy_min = entropy;
846
11.0k
      *best_cache_bits = i;
847
11.0k
    }
848
44.0k
  }
849
6.40k
  ok = 1;
850
6.40k
Error:
851
50.4k
  for (i = 0; i <= cache_bits_max; ++i) {
852
44.0k
    if (cc_init[i]) VP8LColorCacheClear(&hashers[i]);
853
44.0k
    VP8LFreeHistogram(histos[i]);
854
44.0k
  }
855
6.40k
  return ok;
856
6.40k
}
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.82k
                                      VP8LBackwardRefs* const refs) {
862
1.82k
  int pixel_index = 0;
863
1.82k
  VP8LColorCache hashers;
864
1.82k
  VP8LRefsCursor c = VP8LRefsCursorInit(refs);
865
1.82k
  if (!VP8LColorCacheInit(&hashers, cache_bits)) return 0;
866
867
227M
  while (VP8LRefsCursorOk(&c)) {
868
227M
    PixOrCopy* const v = c.cur_pos;
869
227M
    if (PixOrCopyIsLiteral(v)) {
870
220M
      const uint32_t argb_literal = v->argb_or_distance;
871
220M
      const int ix = VP8LColorCacheContains(&hashers, argb_literal);
872
220M
      if (ix >= 0) {
873
        // hashers contains argb_literal
874
50.2M
        *v = PixOrCopyCreateCacheIdx(ix);
875
170M
      } else {
876
170M
        VP8LColorCacheInsert(&hashers, argb_literal);
877
170M
      }
878
220M
      ++pixel_index;
879
220M
    } else {
880
      // refs was created without local cache, so it can not have cache indexes.
881
6.41M
      int k;
882
6.41M
      assert(PixOrCopyIsCopy(v));
883
787M
      for (k = 0; k < v->len; ++k) {
884
781M
        VP8LColorCacheInsert(&hashers, argb[pixel_index++]);
885
781M
      }
886
6.41M
    }
887
227M
    VP8LRefsCursorNext(&c);
888
227M
  }
889
1.82k
  VP8LColorCacheClear(&hashers);
890
1.82k
  return 1;
891
1.82k
}
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.43k
                                 int* const cache_bits_best) {
915
7.43k
  VP8LHistogram* histo = NULL;
916
7.43k
  int i, lz77_type;
917
  // Index 0 is for a color cache, index 1 for no cache (if needed).
918
7.43k
  int lz77_types_best[2] = {0, 0};
919
7.43k
  uint64_t bit_costs_best[2] = {WEBP_UINT64_MAX, WEBP_UINT64_MAX};
920
7.43k
  VP8LHashChain hash_chain_box;
921
7.43k
  VP8LBackwardRefs* const refs_tmp = &refs[do_no_cache ? 2 : 1];
922
7.43k
  int status = 0;
923
7.43k
  memset(&hash_chain_box, 0, sizeof(hash_chain_box));
924
925
7.43k
  histo = VP8LAllocateHistogram(MAX_COLOR_CACHE_BITS);
926
7.43k
  if (histo == NULL) goto Error;
927
928
23.3k
  for (lz77_type = 1; lz77_types_to_try;
929
15.9k
       lz77_types_to_try &= ~lz77_type, lz77_type <<= 1) {
930
15.9k
    int res = 0;
931
15.9k
    uint64_t bit_cost = 0u;
932
15.9k
    if ((lz77_types_to_try & lz77_type) == 0) continue;
933
13.8k
    switch (lz77_type) {
934
6.39k
      case kLZ77RLE:
935
6.39k
        res = BackwardReferencesRle(width, height, argb, 0, refs_tmp);
936
6.39k
        break;
937
6.39k
      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.39k
        res = BackwardReferencesLz77(width, height, argb, 0, hash_chain,
941
6.39k
                                     refs_tmp);
942
6.39k
        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
13.8k
    }
951
13.8k
    if (!res) goto Error;
952
953
    // Start with the no color cache case.
954
41.4k
    for (i = 1; i >= 0; --i) {
955
27.6k
      int cache_bits = (i == 1) ? 0 : cache_bits_max;
956
957
27.6k
      if (i == 1 && !do_no_cache) continue;
958
959
13.8k
      if (i == 0) {
960
        // Try with a color cache.
961
13.8k
        if (!CalculateBestCacheSize(argb, quality, refs_tmp, &cache_bits)) {
962
0
          goto Error;
963
0
        }
964
13.8k
        if (cache_bits > 0) {
965
1.82k
          if (!BackwardRefsWithLocalCache(argb, cache_bits, refs_tmp)) {
966
0
            goto Error;
967
0
          }
968
1.82k
        }
969
13.8k
      }
970
971
13.8k
      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
13.8k
      } else {
974
13.8k
        VP8LHistogramCreate(histo, refs_tmp, cache_bits);
975
13.8k
        bit_cost = VP8LHistogramEstimateBits(histo);
976
13.8k
      }
977
978
13.8k
      if (bit_cost < bit_costs_best[i]) {
979
10.2k
        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.2k
        } else {
984
10.2k
          BackwardRefsSwap(refs_tmp, &refs[0]);
985
10.2k
        }
986
10.2k
        bit_costs_best[i] = bit_cost;
987
10.2k
        lz77_types_best[i] = lz77_type;
988
10.2k
        if (i == 0) *cache_bits_best = cache_bits;
989
10.2k
      }
990
13.8k
    }
991
13.8k
  }
992
7.43k
  assert(lz77_types_best[0] > 0);
993
7.43k
  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.3k
  for (i = 1; i >= 0; --i) {
998
14.8k
    if (i == 1 && !do_no_cache) continue;
999
7.43k
    if ((lz77_types_best[i] == kLZ77Standard ||
1000
3.85k
         lz77_types_best[i] == kLZ77Box) &&
1001
4.63k
        quality >= 25) {
1002
3.58k
      const VP8LHashChain* const hash_chain_tmp =
1003
3.58k
          (lz77_types_best[i] == kLZ77Standard) ? hash_chain : &hash_chain_box;
1004
3.58k
      const int cache_bits = (i == 1) ? 0 : *cache_bits_best;
1005
3.58k
      uint64_t bit_cost_trace;
1006
3.58k
      if (!VP8LBackwardReferencesTraceBackwards(width, height, argb, cache_bits,
1007
3.58k
                                                hash_chain_tmp, &refs[i],
1008
3.58k
                                                refs_tmp)) {
1009
0
        goto Error;
1010
0
      }
1011
3.58k
      VP8LHistogramCreate(histo, refs_tmp, cache_bits);
1012
3.58k
      bit_cost_trace = VP8LHistogramEstimateBits(histo);
1013
3.58k
      if (bit_cost_trace < bit_costs_best[i]) {
1014
1.59k
        BackwardRefsSwap(refs_tmp, &refs[i]);
1015
1.59k
      }
1016
3.58k
    }
1017
1018
7.43k
    BackwardReferences2DLocality(width, &refs[i]);
1019
1020
7.43k
    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.43k
  }
1028
7.43k
  status = 1;
1029
1030
7.43k
Error:
1031
7.43k
  VP8LHashChainClear(&hash_chain_box);
1032
7.43k
  VP8LFreeHistogram(histo);
1033
7.43k
  return status;
1034
7.43k
}
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.43k
    int* const percent) {
1042
7.43k
  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.43k
  } else {
1053
7.43k
    if (!GetBackwardReferences(width, height, argb, quality, lz77_types_to_try,
1054
7.43k
                               cache_bits_max, do_no_cache, hash_chain, refs,
1055
7.43k
                               cache_bits_best)) {
1056
0
      return WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
1057
0
    }
1058
7.43k
  }
1059
1060
7.43k
  return WebPReportProgress(pic, *percent + percent_range, percent);
1061
7.43k
}