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_cost_enc.c
Line
Count
Source
1
// Copyright 2017 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
// Improves a given set of backward references by analyzing its bit cost.
11
// The algorithm is similar to the Zopfli compression algorithm but tailored to
12
// images.
13
//
14
// Author: Vincent Rabaud (vrabaud@google.com)
15
//
16
17
#include <assert.h>
18
#include <string.h>
19
20
#include "src/dsp/lossless_common.h"
21
#include "src/enc/backward_references_enc.h"
22
#include "src/enc/histogram_enc.h"
23
#include "src/utils/color_cache_utils.h"
24
#include "src/utils/utils.h"
25
#include "src/webp/format_constants.h"
26
#include "src/webp/types.h"
27
28
204M
#define VALUES_IN_BYTE 256
29
30
extern void VP8LClearBackwardRefs(VP8LBackwardRefs* const refs);
31
extern int VP8LDistanceToPlaneCode(int xsize, int dist);
32
extern void VP8LBackwardRefsCursorAdd(VP8LBackwardRefs* const refs,
33
                                      const PixOrCopy v);
34
35
typedef struct {
36
  uint32_t alpha[VALUES_IN_BYTE];
37
  uint32_t red[VALUES_IN_BYTE];
38
  uint32_t blue[VALUES_IN_BYTE];
39
  uint32_t distance[NUM_DISTANCE_CODES];
40
  uint32_t* literal;
41
} CostModel;
42
43
static void ConvertPopulationCountTableToBitEstimates(
44
18.5k
    int num_symbols, const uint32_t population_counts[], uint32_t output[]) {
45
18.5k
  uint32_t sum = 0;
46
18.5k
  int nonzeros = 0;
47
18.5k
  int i;
48
4.12M
  for (i = 0; i < num_symbols; ++i) {
49
4.10M
    sum += population_counts[i];
50
4.10M
    if (population_counts[i] > 0) {
51
317k
      ++nonzeros;
52
317k
    }
53
4.10M
  }
54
18.5k
  if (nonzeros <= 1) {
55
12.3k
    memset(output, 0, num_symbols * sizeof(*output));
56
12.3k
  } else {
57
6.20k
    const uint32_t logsum = VP8LFastLog2(sum);
58
1.29M
    for (i = 0; i < num_symbols; ++i) {
59
1.28M
      output[i] = logsum - VP8LFastLog2(population_counts[i]);
60
1.28M
    }
61
6.20k
  }
62
18.5k
}
63
64
static int CostModelBuild(CostModel* const m, int xsize, int cache_bits,
65
3.71k
                          const VP8LBackwardRefs* const refs) {
66
3.71k
  int ok = 0;
67
3.71k
  VP8LHistogram* const histo = VP8LAllocateHistogram(cache_bits);
68
3.71k
  if (histo == NULL) goto Error;
69
70
  // The following code is similar to VP8LHistogramCreate but converts the
71
  // distance to plane code.
72
3.71k
  VP8LHistogramInit(histo, cache_bits, /*init_arrays=*/1);
73
3.71k
  VP8LHistogramStoreRefs(refs, VP8LDistanceToPlaneCode, xsize, histo);
74
75
3.71k
  ConvertPopulationCountTableToBitEstimates(
76
3.71k
      VP8LHistogramNumCodes(histo->palette_code_bits), histo->literal,
77
3.71k
      m->literal);
78
3.71k
  ConvertPopulationCountTableToBitEstimates(VALUES_IN_BYTE, histo->red, m->red);
79
3.71k
  ConvertPopulationCountTableToBitEstimates(VALUES_IN_BYTE, histo->blue,
80
3.71k
                                            m->blue);
81
3.71k
  ConvertPopulationCountTableToBitEstimates(VALUES_IN_BYTE, histo->alpha,
82
3.71k
                                            m->alpha);
83
3.71k
  ConvertPopulationCountTableToBitEstimates(NUM_DISTANCE_CODES, histo->distance,
84
3.71k
                                            m->distance);
85
3.71k
  ok = 1;
86
87
3.71k
Error:
88
3.71k
  VP8LFreeHistogram(histo);
89
3.71k
  return ok;
90
3.71k
}
91
92
static WEBP_INLINE int64_t GetLiteralCost(const CostModel* const m,
93
463M
                                          uint32_t v) {
94
463M
  return (int64_t)m->alpha[v >> 24] + m->red[(v >> 16) & 0xff] +
95
463M
         m->literal[(v >> 8) & 0xff] + m->blue[v & 0xff];
96
463M
}
97
98
static WEBP_INLINE int64_t GetCacheCost(const CostModel* const m,
99
198M
                                        uint32_t idx) {
100
198M
  const int literal_idx = VALUES_IN_BYTE + NUM_LENGTH_CODES + idx;
101
198M
  return (int64_t)m->literal[literal_idx];
102
198M
}
103
104
static WEBP_INLINE int64_t GetLengthCost(const CostModel* const m,
105
6.75M
                                         uint32_t length) {
106
6.75M
  int code, extra_bits;
107
6.75M
  VP8LPrefixEncodeBits(length, &code, &extra_bits);
108
6.75M
  return (int64_t)m->literal[VALUES_IN_BYTE + code] +
109
6.75M
         ((int64_t)extra_bits << LOG_2_PRECISION_BITS);
110
6.75M
}
111
112
static WEBP_INLINE int64_t GetDistanceCost(const CostModel* const m,
113
37.2M
                                           uint32_t distance) {
114
37.2M
  int code, extra_bits;
115
37.2M
  VP8LPrefixEncodeBits(distance, &code, &extra_bits);
116
37.2M
  return (int64_t)m->distance[code] +
117
37.2M
         ((int64_t)extra_bits << LOG_2_PRECISION_BITS);
118
37.2M
}
119
120
static WEBP_INLINE void AddSingleLiteralWithCostModel(
121
    const uint32_t* const argb, VP8LColorCache* const hashers,
122
    const CostModel* const cost_model, int idx, int use_color_cache,
123
661M
    int64_t prev_cost, int64_t* const cost, uint16_t* const dist_array) {
124
661M
  int64_t cost_val = prev_cost;
125
661M
  const uint32_t color = argb[idx];
126
661M
  const int ix = use_color_cache ? VP8LColorCacheContains(hashers, color) : -1;
127
661M
  if (ix >= 0) {
128
    // use_color_cache is true and hashers contains color
129
198M
    cost_val += DivRound(GetCacheCost(cost_model, ix) * 68, 100);
130
463M
  } else {
131
463M
    if (use_color_cache) VP8LColorCacheInsert(hashers, color);
132
463M
    cost_val += DivRound(GetLiteralCost(cost_model, color) * 82, 100);
133
463M
  }
134
661M
  if (cost[idx] > cost_val) {
135
654M
    cost[idx] = cost_val;
136
654M
    dist_array[idx] = 1;  // only one is inserted.
137
654M
  }
138
661M
}
139
140
// -----------------------------------------------------------------------------
141
// CostManager and interval handling
142
143
// Empirical value to avoid high memory consumption but good for performance.
144
25.0M
#define COST_CACHE_INTERVAL_SIZE_MAX 500
145
146
// To perform backward reference every pixel at index 'index' is considered and
147
// the cost for the MAX_LENGTH following pixels computed. Those following pixels
148
// at index 'index' + k (k from 0 to MAX_LENGTH) have a cost of:
149
//     cost = distance cost at index + GetLengthCost(cost_model, k)
150
// and the minimum value is kept. GetLengthCost(cost_model, k) is cached in an
151
// array of size MAX_LENGTH.
152
// Instead of performing MAX_LENGTH comparisons per pixel, we keep track of the
153
// minimal values using intervals of constant cost.
154
// An interval is defined by the 'index' of the pixel that generated it and
155
// is only useful in a range of indices from 'start' to 'end' (exclusive), i.e.
156
// it contains the minimum value for pixels between start and end.
157
// Intervals are stored in a linked list and ordered by 'start'. When a new
158
// interval has a better value, old intervals are split or removed. There are
159
// therefore no overlapping intervals.
160
typedef struct CostInterval CostInterval;
161
struct CostInterval {
162
  int64_t cost;
163
  int start;
164
  int end;
165
  int index;
166
  CostInterval* previous;
167
  CostInterval* next;
168
};
169
170
// The GetLengthCost(cost_model, k) are cached in a CostCacheInterval.
171
typedef struct {
172
  int64_t cost;
173
  int start;
174
  int end;  // Exclusive.
175
} CostCacheInterval;
176
177
// This structure is in charge of managing intervals and costs.
178
// It caches the different CostCacheInterval, caches the different
179
// GetLengthCost(cost_model, k) in cost_cache and the CostInterval's (whose
180
// 'count' is limited by COST_CACHE_INTERVAL_SIZE_MAX).
181
21.0M
#define COST_MANAGER_MAX_FREE_LIST 10
182
typedef struct {
183
  CostInterval* head;
184
  int count;  // The number of stored intervals.
185
  CostCacheInterval* cache_intervals;
186
  size_t cache_intervals_size;
187
  // Contains the GetLengthCost(cost_model, k).
188
  int64_t cost_cache[MAX_LENGTH];
189
  int64_t* costs;
190
  uint16_t* dist_array;
191
  // Most of the time, we only need few intervals -> use a free-list, to avoid
192
  // fragmentation with small allocs in most common cases.
193
  CostInterval intervals[COST_MANAGER_MAX_FREE_LIST];
194
  CostInterval* free_intervals;
195
  // These are regularly malloc'd remains. This list can't grow larger than than
196
  // size COST_CACHE_INTERVAL_SIZE_MAX - COST_MANAGER_MAX_FREE_LIST, note.
197
  CostInterval* recycled_intervals;
198
} CostManager;
199
200
static void CostIntervalAddToFreeList(CostManager* const manager,
201
20.5M
                                      CostInterval* const interval) {
202
20.5M
  interval->next = manager->free_intervals;
203
20.5M
  manager->free_intervals = interval;
204
20.5M
}
205
206
static int CostIntervalIsInFreeList(const CostManager* const manager,
207
25.0M
                                    const CostInterval* const interval) {
208
25.0M
  return (interval >= &manager->intervals[0] &&
209
20.9M
          interval <= &manager->intervals[COST_MANAGER_MAX_FREE_LIST - 1]);
210
25.0M
}
211
212
7.43k
static void CostManagerInitFreeList(CostManager* const manager) {
213
7.43k
  int i;
214
7.43k
  manager->free_intervals = NULL;
215
81.7k
  for (i = 0; i < COST_MANAGER_MAX_FREE_LIST; ++i) {
216
74.3k
    CostIntervalAddToFreeList(manager, &manager->intervals[i]);
217
74.3k
  }
218
7.43k
}
219
220
static void DeleteIntervalList(CostManager* const manager,
221
7.43k
                               const CostInterval* interval) {
222
31.1k
  while (interval != NULL) {
223
23.7k
    const CostInterval* const next = interval->next;
224
23.7k
    if (!CostIntervalIsInFreeList(manager, interval)) {
225
23.4k
      WebPSafeFree((void*)interval);
226
23.4k
    }  // else: do nothing
227
23.7k
    interval = next;
228
23.7k
  }
229
7.43k
}
230
231
3.71k
static void CostManagerClear(CostManager* const manager) {
232
3.71k
  if (manager == NULL) return;
233
234
3.71k
  WebPSafeFree(manager->costs);
235
3.71k
  WebPSafeFree(manager->cache_intervals);
236
237
  // Clear the interval lists.
238
3.71k
  DeleteIntervalList(manager, manager->head);
239
3.71k
  manager->head = NULL;
240
3.71k
  DeleteIntervalList(manager, manager->recycled_intervals);
241
3.71k
  manager->recycled_intervals = NULL;
242
243
  // Reset pointers, 'count' and 'cache_intervals_size'.
244
3.71k
  memset(manager, 0, sizeof(*manager));
245
3.71k
  CostManagerInitFreeList(manager);
246
3.71k
}
247
248
static int CostManagerInit(CostManager* const manager,
249
                           uint16_t* const dist_array, int pix_count,
250
3.71k
                           const CostModel* const cost_model) {
251
3.71k
  int i;
252
3.71k
  const int cost_cache_size = (pix_count > MAX_LENGTH) ? MAX_LENGTH : pix_count;
253
254
3.71k
  manager->costs = NULL;
255
3.71k
  manager->cache_intervals = NULL;
256
3.71k
  manager->head = NULL;
257
3.71k
  manager->recycled_intervals = NULL;
258
3.71k
  manager->count = 0;
259
3.71k
  manager->dist_array = dist_array;
260
3.71k
  CostManagerInitFreeList(manager);
261
262
  // Fill in the 'cost_cache'.
263
  // Has to be done in two passes due to a GCC bug on i686
264
  // related to https://gcc.gnu.org/bugzilla/show_bug.cgi?id=323
265
6.75M
  for (i = 0; i < cost_cache_size; ++i) {
266
6.75M
    manager->cost_cache[i] = GetLengthCost(cost_model, i);
267
6.75M
  }
268
3.71k
  manager->cache_intervals_size = 1;
269
6.75M
  for (i = 1; i < cost_cache_size; ++i) {
270
    // Get the number of bound intervals.
271
6.74M
    if (manager->cost_cache[i] != manager->cost_cache[i - 1]) {
272
31.1k
      ++manager->cache_intervals_size;
273
31.1k
    }
274
6.74M
  }
275
276
  // With the current cost model, we usually have below 20 intervals.
277
  // The worst case scenario with a cost model would be if every length has a
278
  // different cost, hence MAX_LENGTH but that is impossible with the current
279
  // implementation that spirals around a pixel.
280
3.71k
  assert(manager->cache_intervals_size <= MAX_LENGTH);
281
3.71k
  manager->cache_intervals = (CostCacheInterval*)WebPSafeMalloc(
282
3.71k
      manager->cache_intervals_size, sizeof(*manager->cache_intervals));
283
3.71k
  if (manager->cache_intervals == NULL) {
284
0
    CostManagerClear(manager);
285
0
    return 0;
286
0
  }
287
288
  // Fill in the 'cache_intervals'.
289
3.71k
  {
290
3.71k
    CostCacheInterval* cur = manager->cache_intervals;
291
292
    // Consecutive values in 'cost_cache' are compared and if a big enough
293
    // difference is found, a new interval is created and bounded.
294
3.71k
    cur->start = 0;
295
3.71k
    cur->end = 1;
296
3.71k
    cur->cost = manager->cost_cache[0];
297
6.75M
    for (i = 1; i < cost_cache_size; ++i) {
298
6.74M
      const int64_t cost_val = manager->cost_cache[i];
299
6.74M
      if (cost_val != cur->cost) {
300
31.1k
        ++cur;
301
        // Initialize an interval.
302
31.1k
        cur->start = i;
303
31.1k
        cur->cost = cost_val;
304
31.1k
      }
305
6.74M
      cur->end = i + 1;
306
6.74M
    }
307
3.71k
    assert((size_t)(cur - manager->cache_intervals) + 1 ==
308
3.71k
           manager->cache_intervals_size);
309
3.71k
  }
310
311
3.71k
  manager->costs = (int64_t*)WebPSafeMalloc(pix_count, sizeof(*manager->costs));
312
3.71k
  if (manager->costs == NULL) {
313
0
    CostManagerClear(manager);
314
0
    return 0;
315
0
  }
316
  // Set the initial 'costs' to INT64_MAX for every pixel as we will keep the
317
  // minimum.
318
661M
  for (i = 0; i < pix_count; ++i) manager->costs[i] = WEBP_INT64_MAX;
319
320
3.71k
  return 1;
321
3.71k
}
322
323
// Given the cost and the position that define an interval, update the cost at
324
// pixel 'i' if it is smaller than the previously computed value.
325
static WEBP_INLINE void UpdateCost(CostManager* const manager, int i,
326
564M
                                   int position, int64_t cost) {
327
564M
  const int k = i - position;
328
564M
  assert(k >= 0 && k < MAX_LENGTH);
329
330
564M
  if (manager->costs[i] > cost) {
331
538M
    manager->costs[i] = cost;
332
538M
    manager->dist_array[i] = k + 1;
333
538M
  }
334
564M
}
335
336
// Given the cost and the position that define an interval, update the cost for
337
// all the pixels between 'start' and 'end' excluded.
338
static WEBP_INLINE void UpdateCostPerInterval(CostManager* const manager,
339
                                              int start, int end, int position,
340
0
                                              int64_t cost) {
341
0
  int i;
342
0
  for (i = start; i < end; ++i) UpdateCost(manager, i, position, cost);
343
0
}
344
345
// Given two intervals, make 'prev' be the previous one of 'next' in 'manager'.
346
static WEBP_INLINE void ConnectIntervals(CostManager* const manager,
347
                                         CostInterval* const prev,
348
75.1M
                                         CostInterval* const next) {
349
75.1M
  if (prev != NULL) {
350
51.1M
    prev->next = next;
351
51.1M
  } else {
352
23.9M
    manager->head = next;
353
23.9M
  }
354
355
75.1M
  if (next != NULL) next->previous = prev;
356
75.1M
}
357
358
// Pop an interval in the manager.
359
static WEBP_INLINE void PopInterval(CostManager* const manager,
360
25.0M
                                    CostInterval* const interval) {
361
25.0M
  if (interval == NULL) return;
362
363
25.0M
  ConnectIntervals(manager, interval->previous, interval->next);
364
25.0M
  if (CostIntervalIsInFreeList(manager, interval)) {
365
20.4M
    CostIntervalAddToFreeList(manager, interval);
366
20.4M
  } else {  // recycle regularly malloc'd intervals too
367
4.54M
    interval->next = manager->recycled_intervals;
368
4.54M
    manager->recycled_intervals = interval;
369
4.54M
  }
370
25.0M
  --manager->count;
371
25.0M
  assert(manager->count >= 0);
372
25.0M
}
373
374
// Update the cost at index i by going over all the stored intervals that
375
// overlap with i.
376
// If 'do_clean_intervals' is set to something different than 0, intervals that
377
// end before 'i' will be popped.
378
static WEBP_INLINE void UpdateCostAtIndex(CostManager* const manager, int i,
379
662M
                                          int do_clean_intervals) {
380
662M
  CostInterval* current = manager->head;
381
382
1.25G
  while (current != NULL && current->start <= i) {
383
588M
    CostInterval* const next = current->next;
384
588M
    if (current->end <= i) {
385
23.9M
      if (do_clean_intervals) {
386
        // We have an outdated interval, remove it.
387
22.8M
        PopInterval(manager, current);
388
22.8M
      }
389
564M
    } else {
390
564M
      UpdateCost(manager, i, current->index, current->cost);
391
564M
    }
392
588M
    current = next;
393
588M
  }
394
662M
}
395
396
// Given a current orphan interval and its previous interval, before
397
// it was orphaned (which can be NULL), set it at the right place in the list
398
// of intervals using the 'start' ordering and the previous interval as a hint.
399
static WEBP_INLINE void PositionOrphanInterval(CostManager* const manager,
400
                                               CostInterval* const current,
401
25.0M
                                               CostInterval* previous) {
402
25.0M
  assert(current != NULL);
403
404
25.0M
  if (previous == NULL) previous = manager->head;
405
27.5M
  while (previous != NULL && current->start < previous->start) {
406
2.54M
    previous = previous->previous;
407
2.54M
  }
408
145M
  while (previous != NULL && previous->next != NULL &&
409
123M
         previous->next->start < current->start) {
410
120M
    previous = previous->next;
411
120M
  }
412
413
25.0M
  if (previous != NULL) {
414
23.9M
    ConnectIntervals(manager, current, previous->next);
415
23.9M
  } else {
416
1.12M
    ConnectIntervals(manager, current, manager->head);
417
1.12M
  }
418
25.0M
  ConnectIntervals(manager, previous, current);
419
25.0M
}
420
421
// Insert an interval in the list contained in the manager by starting at
422
// 'interval_in' as a hint. The intervals are sorted by 'start' value.
423
static WEBP_INLINE void InsertInterval(CostManager* const manager,
424
                                       CostInterval* const interval_in,
425
                                       int64_t cost, int position, int start,
426
89.9M
                                       int end) {
427
89.9M
  CostInterval* interval_new;
428
429
89.9M
  if (start >= end) return;
430
25.0M
  if (manager->count >= COST_CACHE_INTERVAL_SIZE_MAX) {
431
    // Serialize the interval if we cannot store it.
432
0
    UpdateCostPerInterval(manager, start, end, position, cost);
433
0
    return;
434
0
  }
435
25.0M
  if (manager->free_intervals != NULL) {
436
20.4M
    interval_new = manager->free_intervals;
437
20.4M
    manager->free_intervals = interval_new->next;
438
20.4M
  } else if (manager->recycled_intervals != NULL) {
439
4.52M
    interval_new = manager->recycled_intervals;
440
4.52M
    manager->recycled_intervals = interval_new->next;
441
4.52M
  } else {  // malloc for good
442
23.4k
    interval_new = (CostInterval*)WebPSafeMalloc(1, sizeof(*interval_new));
443
23.4k
    if (interval_new == NULL) {
444
      // Write down the interval if we cannot create it.
445
0
      UpdateCostPerInterval(manager, start, end, position, cost);
446
0
      return;
447
0
    }
448
23.4k
  }
449
450
25.0M
  interval_new->cost = cost;
451
25.0M
  interval_new->index = position;
452
25.0M
  interval_new->start = start;
453
25.0M
  interval_new->end = end;
454
25.0M
  PositionOrphanInterval(manager, interval_new, interval_in);
455
456
25.0M
  ++manager->count;
457
25.0M
}
458
459
// Given a new cost interval defined by its start at position, its length value
460
// and distance_cost, add its contributions to the previous intervals and costs.
461
// If handling the interval or one of its subintervals becomes to heavy, its
462
// contribution is added to the costs right away.
463
static WEBP_INLINE void PushInterval(CostManager* const manager,
464
                                     int64_t distance_cost, int position,
465
37.3M
                                     int len) {
466
37.3M
  size_t i;
467
37.3M
  CostInterval* interval = manager->head;
468
37.3M
  CostInterval* interval_next;
469
37.3M
  const CostCacheInterval* const cost_cache_intervals =
470
37.3M
      manager->cache_intervals;
471
  // If the interval is small enough, no need to deal with the heavy
472
  // interval logic, just serialize it right away. This constant is empirical.
473
37.3M
  const int kSkipDistance = 10;
474
475
37.3M
  if (len < kSkipDistance) {
476
32.3M
    int j;
477
123M
    for (j = position; j < position + len; ++j) {
478
90.7M
      const int k = j - position;
479
90.7M
      int64_t cost_tmp;
480
90.7M
      assert(k >= 0 && k < MAX_LENGTH);
481
90.7M
      cost_tmp = distance_cost + manager->cost_cache[k];
482
483
90.7M
      if (manager->costs[j] > cost_tmp) {
484
45.3M
        manager->costs[j] = cost_tmp;
485
45.3M
        manager->dist_array[j] = k + 1;
486
45.3M
      }
487
90.7M
    }
488
32.3M
    return;
489
32.3M
  }
490
491
5.00M
  for (i = 0;
492
58.0M
       i < manager->cache_intervals_size && cost_cache_intervals[i].start < len;
493
53.0M
       ++i) {
494
    // Define the intersection of the ith interval with the new one.
495
53.0M
    int start = position + cost_cache_intervals[i].start;
496
53.0M
    const int end =
497
53.0M
        position +
498
53.0M
        (cost_cache_intervals[i].end > len ? len : cost_cache_intervals[i].end);
499
53.0M
    const int64_t cost = distance_cost + cost_cache_intervals[i].cost;
500
501
70.8M
    for (; interval != NULL && interval->start < end;
502
53.0M
         interval = interval_next) {
503
47.9M
      interval_next = interval->next;
504
505
      // Make sure we have some overlap
506
47.9M
      if (start >= interval->end) continue;
507
508
41.1M
      if (cost >= interval->cost) {
509
        // When intervals are represented, the lower, the better.
510
        // [**********************************************************[
511
        // start                                                    end
512
        //                   [----------------------------------[
513
        //                   interval->start        interval->end
514
        // If we are worse than what we already have, add whatever we have so
515
        // far up to interval.
516
36.8M
        const int start_new = interval->end;
517
36.8M
        InsertInterval(manager, interval, cost, position, start,
518
36.8M
                       interval->start);
519
36.8M
        start = start_new;
520
36.8M
        if (start >= end) break;
521
8.76M
        continue;
522
36.8M
      }
523
524
4.30M
      if (start <= interval->start) {
525
4.12M
        if (interval->end <= end) {
526
          //                   [----------------------------------[
527
          //                   interval->start        interval->end
528
          // [**************************************************************[
529
          // start                                                        end
530
          // We can safely remove the old interval as it is fully included.
531
2.17M
          PopInterval(manager, interval);
532
2.17M
        } else {
533
          //              [------------------------------------[
534
          //              interval->start          interval->end
535
          // [*****************************[
536
          // start                       end
537
1.95M
          interval->start = end;
538
1.95M
          break;
539
1.95M
        }
540
4.12M
      } else {
541
174k
        if (end < interval->end) {
542
          // [--------------------------------------------------------------[
543
          // interval->start                                    interval->end
544
          //                     [*****************************[
545
          //                     start                       end
546
          // We have to split the old interval as it fully contains the new one.
547
43.4k
          const int end_original = interval->end;
548
43.4k
          interval->end = start;
549
43.4k
          InsertInterval(manager, interval, interval->cost, interval->index,
550
43.4k
                         end, end_original);
551
43.4k
          interval = interval->next;
552
43.4k
          break;
553
131k
        } else {
554
          // [------------------------------------[
555
          // interval->start          interval->end
556
          //                     [*****************************[
557
          //                     start                       end
558
131k
          interval->end = start;
559
131k
        }
560
174k
      }
561
4.30M
    }
562
    // Insert the remaining interval from start to end.
563
53.0M
    InsertInterval(manager, interval, cost, position, start, end);
564
53.0M
  }
565
5.00M
}
566
567
static int BackwardReferencesHashChainDistanceOnly(
568
    int xsize, int ysize, const uint32_t* const argb, int cache_bits,
569
    const VP8LHashChain* const hash_chain, const VP8LBackwardRefs* const refs,
570
3.71k
    uint16_t* const dist_array) {
571
3.71k
  int i;
572
3.71k
  int ok = 0;
573
3.71k
  int cc_init = 0;
574
3.71k
  const int pix_count = xsize * ysize;
575
3.71k
  const int use_color_cache = (cache_bits > 0);
576
3.71k
  const size_t literal_array_size =
577
3.71k
      sizeof(*((CostModel*)NULL)->literal) * VP8LHistogramNumCodes(cache_bits);
578
3.71k
  const size_t cost_model_size = sizeof(CostModel) + literal_array_size;
579
3.71k
  CostModel* const cost_model =
580
3.71k
      (CostModel*)WebPSafeCalloc(1ULL, cost_model_size);
581
3.71k
  VP8LColorCache hashers;
582
3.71k
  CostManager* cost_manager =
583
3.71k
      (CostManager*)WebPSafeCalloc(1ULL, sizeof(*cost_manager));
584
3.71k
  int offset_prev = -1, len_prev = -1;
585
3.71k
  int64_t offset_cost = -1;
586
3.71k
  int first_offset_is_constant = -1;  // initialized with 'impossible' value
587
3.71k
  int reach = 0;
588
589
3.71k
  if (cost_model == NULL || cost_manager == NULL) goto Error;
590
591
3.71k
  cost_model->literal = (uint32_t*)(cost_model + 1);
592
3.71k
  if (use_color_cache) {
593
830
    cc_init = VP8LColorCacheInit(&hashers, cache_bits);
594
830
    if (!cc_init) goto Error;
595
830
  }
596
597
3.71k
  if (!CostModelBuild(cost_model, xsize, cache_bits, refs)) {
598
0
    goto Error;
599
0
  }
600
601
3.71k
  if (!CostManagerInit(cost_manager, dist_array, pix_count, cost_model)) {
602
0
    goto Error;
603
0
  }
604
605
  // We loop one pixel at a time, but store all currently best points to
606
  // non-processed locations from this point.
607
3.71k
  dist_array[0] = 0;
608
  // Add first pixel as literal.
609
3.71k
  AddSingleLiteralWithCostModel(argb, &hashers, cost_model, /*idx=*/0,
610
3.71k
                                use_color_cache, /*prev_cost=*/0,
611
3.71k
                                cost_manager->costs, dist_array);
612
613
661M
  for (i = 1; i < pix_count; ++i) {
614
661M
    const int64_t prev_cost = cost_manager->costs[i - 1];
615
661M
    int offset, len;
616
661M
    VP8LHashChainFindCopy(hash_chain, i, &offset, &len);
617
618
    // Try adding the pixel as a literal.
619
661M
    AddSingleLiteralWithCostModel(argb, &hashers, cost_model, i,
620
661M
                                  use_color_cache, prev_cost,
621
661M
                                  cost_manager->costs, dist_array);
622
623
    // If we are dealing with a non-literal.
624
661M
    if (len >= 2) {
625
600M
      if (offset != offset_prev) {
626
37.2M
        const int code = VP8LDistanceToPlaneCode(xsize, offset);
627
37.2M
        offset_cost = GetDistanceCost(cost_model, code);
628
37.2M
        first_offset_is_constant = 1;
629
37.2M
        PushInterval(cost_manager, prev_cost + offset_cost, i, len);
630
563M
      } else {
631
563M
        assert(offset_cost >= 0);
632
563M
        assert(len_prev >= 0);
633
563M
        assert(first_offset_is_constant == 0 || first_offset_is_constant == 1);
634
        // Instead of considering all contributions from a pixel i by calling:
635
        //         PushInterval(cost_manager, prev_cost + offset_cost, i, len);
636
        // we optimize these contributions in case offset_cost stays the same
637
        // for consecutive pixels. This describes a set of pixels similar to a
638
        // previous set (e.g. constant color regions).
639
563M
        if (first_offset_is_constant) {
640
9.79M
          reach = i - 1 + len_prev - 1;
641
9.79M
          first_offset_is_constant = 0;
642
9.79M
        }
643
644
563M
        if (i + len - 1 > reach) {
645
          // We can only be go further with the same offset if the previous
646
          // length was maxed, hence len_prev == len == MAX_LENGTH.
647
          // TODO(vrabaud), bump i to the end right away (insert cache and
648
          // update cost).
649
          // TODO(vrabaud), check if one of the points in between does not have
650
          // a lower cost.
651
          // Already consider the pixel at "reach" to add intervals that are
652
          // better than whatever we add.
653
51.4k
          int offset_j, len_j = 0;
654
51.4k
          int j;
655
51.4k
          assert(len == MAX_LENGTH || len == pix_count - i);
656
          // Figure out the last consecutive pixel within [i, reach + 1] with
657
          // the same offset.
658
199M
          for (j = i; j <= reach; ++j) {
659
199M
            VP8LHashChainFindCopy(hash_chain, j + 1, &offset_j, &len_j);
660
199M
            if (offset_j != offset) {
661
3.78k
              VP8LHashChainFindCopy(hash_chain, j, &offset_j, &len_j);
662
3.78k
              break;
663
3.78k
            }
664
199M
          }
665
          // Update the cost at j - 1 and j.
666
51.4k
          UpdateCostAtIndex(cost_manager, j - 1, 0);
667
51.4k
          UpdateCostAtIndex(cost_manager, j, 0);
668
669
51.4k
          PushInterval(cost_manager, cost_manager->costs[j - 1] + offset_cost,
670
51.4k
                       j, len_j);
671
51.4k
          reach = j + len_j - 1;
672
51.4k
        }
673
563M
      }
674
600M
    }
675
676
661M
    UpdateCostAtIndex(cost_manager, i, 1);
677
661M
    offset_prev = offset;
678
661M
    len_prev = len;
679
661M
  }
680
681
3.71k
  ok = !refs->error;
682
3.71k
Error:
683
3.71k
  if (cc_init) VP8LColorCacheClear(&hashers);
684
3.71k
  CostManagerClear(cost_manager);
685
3.71k
  WebPSafeFree(cost_model);
686
3.71k
  WebPSafeFree(cost_manager);
687
3.71k
  return ok;
688
3.71k
}
689
690
// We pack the path at the end of *dist_array and return
691
// a pointer to this part of the array. Example:
692
// dist_array = [1x2xx3x2] => packed [1x2x1232], chosen_path = [1232]
693
static void TraceBackwards(uint16_t* const dist_array, int dist_array_size,
694
                           uint16_t** const chosen_path,
695
3.71k
                           int* const chosen_path_size) {
696
3.71k
  uint16_t* path = dist_array + dist_array_size;
697
3.71k
  uint16_t* cur = dist_array + dist_array_size - 1;
698
93.2M
  while (cur >= dist_array) {
699
93.2M
    const int k = *cur;
700
93.2M
    --path;
701
93.2M
    *path = k;
702
93.2M
    cur -= k;
703
93.2M
  }
704
3.71k
  *chosen_path = path;
705
3.71k
  *chosen_path_size = (int)(dist_array + dist_array_size - path);
706
3.71k
}
707
708
static int BackwardReferencesHashChainFollowChosenPath(
709
    const uint32_t* const argb, int cache_bits,
710
    const uint16_t* const chosen_path, int chosen_path_size,
711
3.71k
    const VP8LHashChain* const hash_chain, VP8LBackwardRefs* const refs) {
712
3.71k
  const int use_color_cache = (cache_bits > 0);
713
3.71k
  int ix;
714
3.71k
  int i = 0;
715
3.71k
  int ok = 0;
716
3.71k
  int cc_init = 0;
717
3.71k
  VP8LColorCache hashers;
718
719
3.71k
  if (use_color_cache) {
720
830
    cc_init = VP8LColorCacheInit(&hashers, cache_bits);
721
830
    if (!cc_init) goto Error;
722
830
  }
723
724
3.71k
  VP8LClearBackwardRefs(refs);
725
93.2M
  for (ix = 0; ix < chosen_path_size; ++ix) {
726
93.2M
    const int len = chosen_path[ix];
727
93.2M
    if (len != 1) {
728
4.76M
      int k;
729
4.76M
      const int offset = VP8LHashChainFindOffset(hash_chain, i);
730
4.76M
      VP8LBackwardRefsCursorAdd(refs, PixOrCopyCreateCopy(offset, len));
731
4.76M
      if (use_color_cache) {
732
231M
        for (k = 0; k < len; ++k) {
733
229M
          VP8LColorCacheInsert(&hashers, argb[i + k]);
734
229M
        }
735
2.50M
      }
736
4.76M
      i += len;
737
88.4M
    } else {
738
88.4M
      PixOrCopy v;
739
88.4M
      const int idx =
740
88.4M
          use_color_cache ? VP8LColorCacheContains(&hashers, argb[i]) : -1;
741
88.4M
      if (idx >= 0) {
742
        // use_color_cache is true and hashers contains argb[i]
743
        // push pixel as a color cache index
744
4.78M
        v = PixOrCopyCreateCacheIdx(idx);
745
83.6M
      } else {
746
83.6M
        if (use_color_cache) VP8LColorCacheInsert(&hashers, argb[i]);
747
83.6M
        v = PixOrCopyCreateLiteral(argb[i]);
748
83.6M
      }
749
88.4M
      VP8LBackwardRefsCursorAdd(refs, v);
750
88.4M
      ++i;
751
88.4M
    }
752
93.2M
  }
753
3.71k
  ok = !refs->error;
754
3.71k
Error:
755
3.71k
  if (cc_init) VP8LColorCacheClear(&hashers);
756
3.71k
  return ok;
757
3.71k
}
758
759
// Returns 1 on success.
760
extern int VP8LBackwardReferencesTraceBackwards(
761
    int xsize, int ysize, const uint32_t* const argb, int cache_bits,
762
    const VP8LHashChain* const hash_chain,
763
    const VP8LBackwardRefs* const refs_src, VP8LBackwardRefs* const refs_dst);
764
int VP8LBackwardReferencesTraceBackwards(int xsize, int ysize,
765
                                         const uint32_t* const argb,
766
                                         int cache_bits,
767
                                         const VP8LHashChain* const hash_chain,
768
                                         const VP8LBackwardRefs* const refs_src,
769
3.71k
                                         VP8LBackwardRefs* const refs_dst) {
770
3.71k
  int ok = 0;
771
3.71k
  const int dist_array_size = xsize * ysize;
772
3.71k
  uint16_t* chosen_path = NULL;
773
3.71k
  int chosen_path_size = 0;
774
3.71k
  uint16_t* dist_array =
775
3.71k
      (uint16_t*)WebPSafeMalloc(dist_array_size, sizeof(*dist_array));
776
777
3.71k
  if (dist_array == NULL) goto Error;
778
779
3.71k
  if (!BackwardReferencesHashChainDistanceOnly(
780
3.71k
          xsize, ysize, argb, cache_bits, hash_chain, refs_src, dist_array)) {
781
0
    goto Error;
782
0
  }
783
3.71k
  TraceBackwards(dist_array, dist_array_size, &chosen_path, &chosen_path_size);
784
3.71k
  if (!BackwardReferencesHashChainFollowChosenPath(
785
3.71k
          argb, cache_bits, chosen_path, chosen_path_size, hash_chain,
786
3.71k
          refs_dst)) {
787
0
    goto Error;
788
0
  }
789
3.71k
  ok = 1;
790
3.71k
Error:
791
3.71k
  WebPSafeFree(dist_array);
792
3.71k
  return ok;
793
3.71k
}