Coverage Report

Created: 2025-06-13 06:57

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