Coverage Report

Created: 2024-06-18 06:09

/src/libwebp/src/enc/predictor_enc.c
Line
Count
Source (jump to first uncovered line)
1
// Copyright 2016 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
// Image transform methods for lossless encoder.
11
//
12
// Authors: Vikas Arora (vikaas.arora@gmail.com)
13
//          Jyrki Alakuijala (jyrki@google.com)
14
//          Urvang Joshi (urvang@google.com)
15
//          Vincent Rabaud (vrabaud@google.com)
16
17
#include "src/dsp/lossless.h"
18
#include "src/dsp/lossless_common.h"
19
#include "src/enc/vp8i_enc.h"
20
#include "src/enc/vp8li_enc.h"
21
22
0
#define MAX_DIFF_COST (1e30f)
23
0
#define HISTO_SIZE (4 * 256)
24
static const float kSpatialPredictorBias = 15.f;
25
static const int kPredLowEffort = 11;
26
static const uint32_t kMaskAlpha = 0xff000000;
27
28
// Mostly used to reduce code size + readability
29
0
static WEBP_INLINE int GetMin(int a, int b) { return (a > b) ? b : a; }
30
31
//------------------------------------------------------------------------------
32
// Methods to calculate Entropy (Shannon).
33
34
// Compute a bias for prediction entropy using a global heuristic to favor
35
// values closer to 0. Hence the final negative sign.
36
static float PredictionCostBias(const uint32_t counts[256], int weight_0,
37
0
                                float exp_val) {
38
0
  const int significant_symbols = 256 >> 4;
39
0
  const float exp_decay_factor = 0.6f;
40
0
  float bits = (float)weight_0 * counts[0];
41
0
  int i;
42
0
  for (i = 1; i < significant_symbols; ++i) {
43
0
    bits += exp_val * (counts[i] + counts[256 - i]);
44
0
    exp_val *= exp_decay_factor;
45
0
  }
46
0
  return (float)(-0.1 * bits);
47
0
}
48
49
static float PredictionCostSpatialHistogram(
50
    const uint32_t accumulated[HISTO_SIZE], const uint32_t tile[HISTO_SIZE],
51
0
    int mode, int left_mode, int above_mode) {
52
0
  int i;
53
0
  float retval = 0.f;
54
0
  for (i = 0; i < 4; ++i) {
55
0
    const float kExpValue = 0.94f;
56
0
    retval += PredictionCostBias(&tile[i * 256], 1, kExpValue);
57
    // Compute the new cost if 'tile' is added to 'accumulate' but also add the
58
    // cost of the current histogram to guide the spatial predictor selection.
59
    // Basically, favor low entropy, locally and globally.
60
0
    retval += VP8LCombinedShannonEntropy(&tile[i * 256], &accumulated[i * 256]);
61
0
  }
62
  // Favor keeping the areas locally similar.
63
0
  if (mode == left_mode) retval -= kSpatialPredictorBias;
64
0
  if (mode == above_mode) retval -= kSpatialPredictorBias;
65
0
  return retval;
66
0
}
67
68
static WEBP_INLINE void UpdateHisto(uint32_t histo_argb[HISTO_SIZE],
69
0
                                    uint32_t argb) {
70
0
  ++histo_argb[0 * 256 + (argb >> 24)];
71
0
  ++histo_argb[1 * 256 + ((argb >> 16) & 0xff)];
72
0
  ++histo_argb[2 * 256 + ((argb >> 8) & 0xff)];
73
0
  ++histo_argb[3 * 256 + (argb & 0xff)];
74
0
}
75
76
//------------------------------------------------------------------------------
77
// Spatial transform functions.
78
79
static WEBP_INLINE void PredictBatch(int mode, int x_start, int y,
80
                                     int num_pixels, const uint32_t* current,
81
0
                                     const uint32_t* upper, uint32_t* out) {
82
0
  if (x_start == 0) {
83
0
    if (y == 0) {
84
      // ARGB_BLACK.
85
0
      VP8LPredictorsSub[0](current, NULL, 1, out);
86
0
    } else {
87
      // Top one.
88
0
      VP8LPredictorsSub[2](current, upper, 1, out);
89
0
    }
90
0
    ++x_start;
91
0
    ++out;
92
0
    --num_pixels;
93
0
  }
94
0
  if (y == 0) {
95
    // Left one.
96
0
    VP8LPredictorsSub[1](current + x_start, NULL, num_pixels, out);
97
0
  } else {
98
0
    VP8LPredictorsSub[mode](current + x_start, upper + x_start, num_pixels,
99
0
                            out);
100
0
  }
101
0
}
102
103
#if (WEBP_NEAR_LOSSLESS == 1)
104
0
static WEBP_INLINE int GetMax(int a, int b) { return (a < b) ? b : a; }
105
106
0
static int MaxDiffBetweenPixels(uint32_t p1, uint32_t p2) {
107
0
  const int diff_a = abs((int)(p1 >> 24) - (int)(p2 >> 24));
108
0
  const int diff_r = abs((int)((p1 >> 16) & 0xff) - (int)((p2 >> 16) & 0xff));
109
0
  const int diff_g = abs((int)((p1 >> 8) & 0xff) - (int)((p2 >> 8) & 0xff));
110
0
  const int diff_b = abs((int)(p1 & 0xff) - (int)(p2 & 0xff));
111
0
  return GetMax(GetMax(diff_a, diff_r), GetMax(diff_g, diff_b));
112
0
}
113
114
static int MaxDiffAroundPixel(uint32_t current, uint32_t up, uint32_t down,
115
0
                              uint32_t left, uint32_t right) {
116
0
  const int diff_up = MaxDiffBetweenPixels(current, up);
117
0
  const int diff_down = MaxDiffBetweenPixels(current, down);
118
0
  const int diff_left = MaxDiffBetweenPixels(current, left);
119
0
  const int diff_right = MaxDiffBetweenPixels(current, right);
120
0
  return GetMax(GetMax(diff_up, diff_down), GetMax(diff_left, diff_right));
121
0
}
122
123
0
static uint32_t AddGreenToBlueAndRed(uint32_t argb) {
124
0
  const uint32_t green = (argb >> 8) & 0xff;
125
0
  uint32_t red_blue = argb & 0x00ff00ffu;
126
0
  red_blue += (green << 16) | green;
127
0
  red_blue &= 0x00ff00ffu;
128
0
  return (argb & 0xff00ff00u) | red_blue;
129
0
}
130
131
static void MaxDiffsForRow(int width, int stride, const uint32_t* const argb,
132
0
                           uint8_t* const max_diffs, int used_subtract_green) {
133
0
  uint32_t current, up, down, left, right;
134
0
  int x;
135
0
  if (width <= 2) return;
136
0
  current = argb[0];
137
0
  right = argb[1];
138
0
  if (used_subtract_green) {
139
0
    current = AddGreenToBlueAndRed(current);
140
0
    right = AddGreenToBlueAndRed(right);
141
0
  }
142
  // max_diffs[0] and max_diffs[width - 1] are never used.
143
0
  for (x = 1; x < width - 1; ++x) {
144
0
    up = argb[-stride + x];
145
0
    down = argb[stride + x];
146
0
    left = current;
147
0
    current = right;
148
0
    right = argb[x + 1];
149
0
    if (used_subtract_green) {
150
0
      up = AddGreenToBlueAndRed(up);
151
0
      down = AddGreenToBlueAndRed(down);
152
0
      right = AddGreenToBlueAndRed(right);
153
0
    }
154
0
    max_diffs[x] = MaxDiffAroundPixel(current, up, down, left, right);
155
0
  }
156
0
}
157
158
// Quantize the difference between the actual component value and its prediction
159
// to a multiple of quantization, working modulo 256, taking care not to cross
160
// a boundary (inclusive upper limit).
161
static uint8_t NearLosslessComponent(uint8_t value, uint8_t predict,
162
0
                                     uint8_t boundary, int quantization) {
163
0
  const int residual = (value - predict) & 0xff;
164
0
  const int boundary_residual = (boundary - predict) & 0xff;
165
0
  const int lower = residual & ~(quantization - 1);
166
0
  const int upper = lower + quantization;
167
  // Resolve ties towards a value closer to the prediction (i.e. towards lower
168
  // if value comes after prediction and towards upper otherwise).
169
0
  const int bias = ((boundary - value) & 0xff) < boundary_residual;
170
0
  if (residual - lower < upper - residual + bias) {
171
    // lower is closer to residual than upper.
172
0
    if (residual > boundary_residual && lower <= boundary_residual) {
173
      // Halve quantization step to avoid crossing boundary. This midpoint is
174
      // on the same side of boundary as residual because midpoint >= residual
175
      // (since lower is closer than upper) and residual is above the boundary.
176
0
      return lower + (quantization >> 1);
177
0
    }
178
0
    return lower;
179
0
  } else {
180
    // upper is closer to residual than lower.
181
0
    if (residual <= boundary_residual && upper > boundary_residual) {
182
      // Halve quantization step to avoid crossing boundary. This midpoint is
183
      // on the same side of boundary as residual because midpoint <= residual
184
      // (since upper is closer than lower) and residual is below the boundary.
185
0
      return lower + (quantization >> 1);
186
0
    }
187
0
    return upper & 0xff;
188
0
  }
189
0
}
190
191
0
static WEBP_INLINE uint8_t NearLosslessDiff(uint8_t a, uint8_t b) {
192
0
  return (uint8_t)((((int)(a) - (int)(b))) & 0xff);
193
0
}
194
195
// Quantize every component of the difference between the actual pixel value and
196
// its prediction to a multiple of a quantization (a power of 2, not larger than
197
// max_quantization which is a power of 2, smaller than max_diff). Take care if
198
// value and predict have undergone subtract green, which means that red and
199
// blue are represented as offsets from green.
200
static uint32_t NearLossless(uint32_t value, uint32_t predict,
201
                             int max_quantization, int max_diff,
202
0
                             int used_subtract_green) {
203
0
  int quantization;
204
0
  uint8_t new_green = 0;
205
0
  uint8_t green_diff = 0;
206
0
  uint8_t a, r, g, b;
207
0
  if (max_diff <= 2) {
208
0
    return VP8LSubPixels(value, predict);
209
0
  }
210
0
  quantization = max_quantization;
211
0
  while (quantization >= max_diff) {
212
0
    quantization >>= 1;
213
0
  }
214
0
  if ((value >> 24) == 0 || (value >> 24) == 0xff) {
215
    // Preserve transparency of fully transparent or fully opaque pixels.
216
0
    a = NearLosslessDiff((value >> 24) & 0xff, (predict >> 24) & 0xff);
217
0
  } else {
218
0
    a = NearLosslessComponent(value >> 24, predict >> 24, 0xff, quantization);
219
0
  }
220
0
  g = NearLosslessComponent((value >> 8) & 0xff, (predict >> 8) & 0xff, 0xff,
221
0
                            quantization);
222
0
  if (used_subtract_green) {
223
    // The green offset will be added to red and blue components during decoding
224
    // to obtain the actual red and blue values.
225
0
    new_green = ((predict >> 8) + g) & 0xff;
226
    // The amount by which green has been adjusted during quantization. It is
227
    // subtracted from red and blue for compensation, to avoid accumulating two
228
    // quantization errors in them.
229
0
    green_diff = NearLosslessDiff(new_green, (value >> 8) & 0xff);
230
0
  }
231
0
  r = NearLosslessComponent(NearLosslessDiff((value >> 16) & 0xff, green_diff),
232
0
                            (predict >> 16) & 0xff, 0xff - new_green,
233
0
                            quantization);
234
0
  b = NearLosslessComponent(NearLosslessDiff(value & 0xff, green_diff),
235
0
                            predict & 0xff, 0xff - new_green, quantization);
236
0
  return ((uint32_t)a << 24) | ((uint32_t)r << 16) | ((uint32_t)g << 8) | b;
237
0
}
238
#endif  // (WEBP_NEAR_LOSSLESS == 1)
239
240
// Stores the difference between the pixel and its prediction in "out".
241
// In case of a lossy encoding, updates the source image to avoid propagating
242
// the deviation further to pixels which depend on the current pixel for their
243
// predictions.
244
static WEBP_INLINE void GetResidual(
245
    int width, int height, uint32_t* const upper_row,
246
    uint32_t* const current_row, const uint8_t* const max_diffs, int mode,
247
    int x_start, int x_end, int y, int max_quantization, int exact,
248
0
    int used_subtract_green, uint32_t* const out) {
249
0
  if (exact) {
250
0
    PredictBatch(mode, x_start, y, x_end - x_start, current_row, upper_row,
251
0
                 out);
252
0
  } else {
253
0
    const VP8LPredictorFunc pred_func = VP8LPredictors[mode];
254
0
    int x;
255
0
    for (x = x_start; x < x_end; ++x) {
256
0
      uint32_t predict;
257
0
      uint32_t residual;
258
0
      if (y == 0) {
259
0
        predict = (x == 0) ? ARGB_BLACK : current_row[x - 1];  // Left.
260
0
      } else if (x == 0) {
261
0
        predict = upper_row[x];  // Top.
262
0
      } else {
263
0
        predict = pred_func(&current_row[x - 1], upper_row + x);
264
0
      }
265
0
#if (WEBP_NEAR_LOSSLESS == 1)
266
0
      if (max_quantization == 1 || mode == 0 || y == 0 || y == height - 1 ||
267
0
          x == 0 || x == width - 1) {
268
0
        residual = VP8LSubPixels(current_row[x], predict);
269
0
      } else {
270
0
        residual = NearLossless(current_row[x], predict, max_quantization,
271
0
                                max_diffs[x], used_subtract_green);
272
        // Update the source image.
273
0
        current_row[x] = VP8LAddPixels(predict, residual);
274
        // x is never 0 here so we do not need to update upper_row like below.
275
0
      }
276
#else
277
      (void)max_diffs;
278
      (void)height;
279
      (void)max_quantization;
280
      (void)used_subtract_green;
281
      residual = VP8LSubPixels(current_row[x], predict);
282
#endif
283
0
      if ((current_row[x] & kMaskAlpha) == 0) {
284
        // If alpha is 0, cleanup RGB. We can choose the RGB values of the
285
        // residual for best compression. The prediction of alpha itself can be
286
        // non-zero and must be kept though. We choose RGB of the residual to be
287
        // 0.
288
0
        residual &= kMaskAlpha;
289
        // Update the source image.
290
0
        current_row[x] = predict & ~kMaskAlpha;
291
        // The prediction for the rightmost pixel in a row uses the leftmost
292
        // pixel
293
        // in that row as its top-right context pixel. Hence if we change the
294
        // leftmost pixel of current_row, the corresponding change must be
295
        // applied
296
        // to upper_row as well where top-right context is being read from.
297
0
        if (x == 0 && y != 0) upper_row[width] = current_row[0];
298
0
      }
299
0
      out[x - x_start] = residual;
300
0
    }
301
0
  }
302
0
}
303
304
// Returns best predictor and updates the accumulated histogram.
305
// If max_quantization > 1, assumes that near lossless processing will be
306
// applied, quantizing residuals to multiples of quantization levels up to
307
// max_quantization (the actual quantization level depends on smoothness near
308
// the given pixel).
309
static int GetBestPredictorForTile(
310
    int width, int height, int tile_x, int tile_y, int bits,
311
    uint32_t accumulated[HISTO_SIZE], uint32_t* const argb_scratch,
312
    const uint32_t* const argb, int max_quantization, int exact,
313
0
    int used_subtract_green, const uint32_t* const modes) {
314
0
  const int kNumPredModes = 14;
315
0
  const int start_x = tile_x << bits;
316
0
  const int start_y = tile_y << bits;
317
0
  const int tile_size = 1 << bits;
318
0
  const int max_y = GetMin(tile_size, height - start_y);
319
0
  const int max_x = GetMin(tile_size, width - start_x);
320
  // Whether there exist columns just outside the tile.
321
0
  const int have_left = (start_x > 0);
322
  // Position and size of the strip covering the tile and adjacent columns if
323
  // they exist.
324
0
  const int context_start_x = start_x - have_left;
325
0
#if (WEBP_NEAR_LOSSLESS == 1)
326
0
  const int context_width = max_x + have_left + (max_x < width - start_x);
327
0
#endif
328
0
  const int tiles_per_row = VP8LSubSampleSize(width, bits);
329
  // Prediction modes of the left and above neighbor tiles.
330
0
  const int left_mode = (tile_x > 0) ?
331
0
      (modes[tile_y * tiles_per_row + tile_x - 1] >> 8) & 0xff : 0xff;
332
0
  const int above_mode = (tile_y > 0) ?
333
0
      (modes[(tile_y - 1) * tiles_per_row + tile_x] >> 8) & 0xff : 0xff;
334
  // The width of upper_row and current_row is one pixel larger than image width
335
  // to allow the top right pixel to point to the leftmost pixel of the next row
336
  // when at the right edge.
337
0
  uint32_t* upper_row = argb_scratch;
338
0
  uint32_t* current_row = upper_row + width + 1;
339
0
  uint8_t* const max_diffs = (uint8_t*)(current_row + width + 1);
340
0
  float best_diff = MAX_DIFF_COST;
341
0
  int best_mode = 0;
342
0
  int mode;
343
0
  uint32_t histo_stack_1[HISTO_SIZE];
344
0
  uint32_t histo_stack_2[HISTO_SIZE];
345
  // Need pointers to be able to swap arrays.
346
0
  uint32_t* histo_argb = histo_stack_1;
347
0
  uint32_t* best_histo = histo_stack_2;
348
0
  uint32_t residuals[1 << MAX_TRANSFORM_BITS];
349
0
  assert(bits <= MAX_TRANSFORM_BITS);
350
0
  assert(max_x <= (1 << MAX_TRANSFORM_BITS));
351
352
0
  for (mode = 0; mode < kNumPredModes; ++mode) {
353
0
    float cur_diff;
354
0
    int relative_y;
355
0
    memset(histo_argb, 0, sizeof(histo_stack_1));
356
0
    if (start_y > 0) {
357
      // Read the row above the tile which will become the first upper_row.
358
      // Include a pixel to the left if it exists; include a pixel to the right
359
      // in all cases (wrapping to the leftmost pixel of the next row if it does
360
      // not exist).
361
0
      memcpy(current_row + context_start_x,
362
0
             argb + (start_y - 1) * width + context_start_x,
363
0
             sizeof(*argb) * (max_x + have_left + 1));
364
0
    }
365
0
    for (relative_y = 0; relative_y < max_y; ++relative_y) {
366
0
      const int y = start_y + relative_y;
367
0
      int relative_x;
368
0
      uint32_t* tmp = upper_row;
369
0
      upper_row = current_row;
370
0
      current_row = tmp;
371
      // Read current_row. Include a pixel to the left if it exists; include a
372
      // pixel to the right in all cases except at the bottom right corner of
373
      // the image (wrapping to the leftmost pixel of the next row if it does
374
      // not exist in the current row).
375
0
      memcpy(current_row + context_start_x,
376
0
             argb + y * width + context_start_x,
377
0
             sizeof(*argb) * (max_x + have_left + (y + 1 < height)));
378
0
#if (WEBP_NEAR_LOSSLESS == 1)
379
0
      if (max_quantization > 1 && y >= 1 && y + 1 < height) {
380
0
        MaxDiffsForRow(context_width, width, argb + y * width + context_start_x,
381
0
                       max_diffs + context_start_x, used_subtract_green);
382
0
      }
383
0
#endif
384
385
0
      GetResidual(width, height, upper_row, current_row, max_diffs, mode,
386
0
                  start_x, start_x + max_x, y, max_quantization, exact,
387
0
                  used_subtract_green, residuals);
388
0
      for (relative_x = 0; relative_x < max_x; ++relative_x) {
389
0
        UpdateHisto(histo_argb, residuals[relative_x]);
390
0
      }
391
0
    }
392
0
    cur_diff = PredictionCostSpatialHistogram(accumulated, histo_argb, mode,
393
0
                                              left_mode, above_mode);
394
395
0
    if (cur_diff < best_diff) {
396
0
      uint32_t* tmp = histo_argb;
397
0
      histo_argb = best_histo;
398
0
      best_histo = tmp;
399
0
      best_diff = cur_diff;
400
0
      best_mode = mode;
401
0
    }
402
0
  }
403
404
0
  VP8LAddVectorEq(best_histo, accumulated, HISTO_SIZE);
405
0
  return best_mode;
406
0
}
407
408
// Converts pixels of the image to residuals with respect to predictions.
409
// If max_quantization > 1, applies near lossless processing, quantizing
410
// residuals to multiples of quantization levels up to max_quantization
411
// (the actual quantization level depends on smoothness near the given pixel).
412
static void CopyImageWithPrediction(int width, int height, int bits,
413
                                    const uint32_t* const modes,
414
                                    uint32_t* const argb_scratch,
415
                                    uint32_t* const argb, int low_effort,
416
                                    int max_quantization, int exact,
417
0
                                    int used_subtract_green) {
418
0
  const int tiles_per_row = VP8LSubSampleSize(width, bits);
419
  // The width of upper_row and current_row is one pixel larger than image width
420
  // to allow the top right pixel to point to the leftmost pixel of the next row
421
  // when at the right edge.
422
0
  uint32_t* upper_row = argb_scratch;
423
0
  uint32_t* current_row = upper_row + width + 1;
424
0
  uint8_t* current_max_diffs = (uint8_t*)(current_row + width + 1);
425
0
#if (WEBP_NEAR_LOSSLESS == 1)
426
0
  uint8_t* lower_max_diffs = current_max_diffs + width;
427
0
#endif
428
0
  int y;
429
430
0
  for (y = 0; y < height; ++y) {
431
0
    int x;
432
0
    uint32_t* const tmp32 = upper_row;
433
0
    upper_row = current_row;
434
0
    current_row = tmp32;
435
0
    memcpy(current_row, argb + y * width,
436
0
           sizeof(*argb) * (width + (y + 1 < height)));
437
438
0
    if (low_effort) {
439
0
      PredictBatch(kPredLowEffort, 0, y, width, current_row, upper_row,
440
0
                   argb + y * width);
441
0
    } else {
442
0
#if (WEBP_NEAR_LOSSLESS == 1)
443
0
      if (max_quantization > 1) {
444
        // Compute max_diffs for the lower row now, because that needs the
445
        // contents of argb for the current row, which we will overwrite with
446
        // residuals before proceeding with the next row.
447
0
        uint8_t* const tmp8 = current_max_diffs;
448
0
        current_max_diffs = lower_max_diffs;
449
0
        lower_max_diffs = tmp8;
450
0
        if (y + 2 < height) {
451
0
          MaxDiffsForRow(width, width, argb + (y + 1) * width, lower_max_diffs,
452
0
                         used_subtract_green);
453
0
        }
454
0
      }
455
0
#endif
456
0
      for (x = 0; x < width;) {
457
0
        const int mode =
458
0
            (modes[(y >> bits) * tiles_per_row + (x >> bits)] >> 8) & 0xff;
459
0
        int x_end = x + (1 << bits);
460
0
        if (x_end > width) x_end = width;
461
0
        GetResidual(width, height, upper_row, current_row, current_max_diffs,
462
0
                    mode, x, x_end, y, max_quantization, exact,
463
0
                    used_subtract_green, argb + y * width + x);
464
0
        x = x_end;
465
0
      }
466
0
    }
467
0
  }
468
0
}
469
470
// Finds the best predictor for each tile, and converts the image to residuals
471
// with respect to predictions. If near_lossless_quality < 100, applies
472
// near lossless processing, shaving off more bits of residuals for lower
473
// qualities.
474
int VP8LResidualImage(int width, int height, int bits, int low_effort,
475
                      uint32_t* const argb, uint32_t* const argb_scratch,
476
                      uint32_t* const image, int near_lossless_quality,
477
                      int exact, int used_subtract_green,
478
                      const WebPPicture* const pic, int percent_range,
479
0
                      int* const percent) {
480
0
  const int tiles_per_row = VP8LSubSampleSize(width, bits);
481
0
  const int tiles_per_col = VP8LSubSampleSize(height, bits);
482
0
  int percent_start = *percent;
483
0
  const int max_quantization = 1 << VP8LNearLosslessBits(near_lossless_quality);
484
0
  if (low_effort) {
485
0
    int i;
486
0
    for (i = 0; i < tiles_per_row * tiles_per_col; ++i) {
487
0
      image[i] = ARGB_BLACK | (kPredLowEffort << 8);
488
0
    }
489
0
  } else {
490
0
    int tile_y;
491
0
    uint32_t histo[HISTO_SIZE] = { 0 };
492
0
    for (tile_y = 0; tile_y < tiles_per_col; ++tile_y) {
493
0
      int tile_x;
494
0
      for (tile_x = 0; tile_x < tiles_per_row; ++tile_x) {
495
0
        const int pred = GetBestPredictorForTile(
496
0
            width, height, tile_x, tile_y, bits, histo, argb_scratch, argb,
497
0
            max_quantization, exact, used_subtract_green, image);
498
0
        image[tile_y * tiles_per_row + tile_x] = ARGB_BLACK | (pred << 8);
499
0
      }
500
501
0
      if (!WebPReportProgress(
502
0
              pic, percent_start + percent_range * tile_y / tiles_per_col,
503
0
              percent)) {
504
0
        return 0;
505
0
      }
506
0
    }
507
0
  }
508
509
0
  CopyImageWithPrediction(width, height, bits, image, argb_scratch, argb,
510
0
                          low_effort, max_quantization, exact,
511
0
                          used_subtract_green);
512
0
  return WebPReportProgress(pic, percent_start + percent_range, percent);
513
0
}
514
515
//------------------------------------------------------------------------------
516
// Color transform functions.
517
518
0
static WEBP_INLINE void MultipliersClear(VP8LMultipliers* const m) {
519
0
  m->green_to_red_ = 0;
520
0
  m->green_to_blue_ = 0;
521
0
  m->red_to_blue_ = 0;
522
0
}
523
524
static WEBP_INLINE void ColorCodeToMultipliers(uint32_t color_code,
525
0
                                               VP8LMultipliers* const m) {
526
0
  m->green_to_red_  = (color_code >>  0) & 0xff;
527
0
  m->green_to_blue_ = (color_code >>  8) & 0xff;
528
0
  m->red_to_blue_   = (color_code >> 16) & 0xff;
529
0
}
530
531
static WEBP_INLINE uint32_t MultipliersToColorCode(
532
0
    const VP8LMultipliers* const m) {
533
0
  return 0xff000000u |
534
0
         ((uint32_t)(m->red_to_blue_) << 16) |
535
0
         ((uint32_t)(m->green_to_blue_) << 8) |
536
0
         m->green_to_red_;
537
0
}
538
539
static float PredictionCostCrossColor(const uint32_t accumulated[256],
540
0
                                      const uint32_t counts[256]) {
541
  // Favor low entropy, locally and globally.
542
  // Favor small absolute values for PredictionCostSpatial
543
0
  static const float kExpValue = 2.4f;
544
0
  return VP8LCombinedShannonEntropy(counts, accumulated) +
545
0
         PredictionCostBias(counts, 3, kExpValue);
546
0
}
547
548
static float GetPredictionCostCrossColorRed(
549
    const uint32_t* argb, int stride, int tile_width, int tile_height,
550
    VP8LMultipliers prev_x, VP8LMultipliers prev_y, int green_to_red,
551
0
    const uint32_t accumulated_red_histo[256]) {
552
0
  uint32_t histo[256] = { 0 };
553
0
  float cur_diff;
554
555
0
  VP8LCollectColorRedTransforms(argb, stride, tile_width, tile_height,
556
0
                                green_to_red, histo);
557
558
0
  cur_diff = PredictionCostCrossColor(accumulated_red_histo, histo);
559
0
  if ((uint8_t)green_to_red == prev_x.green_to_red_) {
560
0
    cur_diff -= 3;  // favor keeping the areas locally similar
561
0
  }
562
0
  if ((uint8_t)green_to_red == prev_y.green_to_red_) {
563
0
    cur_diff -= 3;  // favor keeping the areas locally similar
564
0
  }
565
0
  if (green_to_red == 0) {
566
0
    cur_diff -= 3;
567
0
  }
568
0
  return cur_diff;
569
0
}
570
571
static void GetBestGreenToRed(const uint32_t* argb, int stride, int tile_width,
572
                              int tile_height, VP8LMultipliers prev_x,
573
                              VP8LMultipliers prev_y, int quality,
574
                              const uint32_t accumulated_red_histo[256],
575
0
                              VP8LMultipliers* const best_tx) {
576
0
  const int kMaxIters = 4 + ((7 * quality) >> 8);  // in range [4..6]
577
0
  int green_to_red_best = 0;
578
0
  int iter, offset;
579
0
  float best_diff = GetPredictionCostCrossColorRed(
580
0
      argb, stride, tile_width, tile_height, prev_x, prev_y,
581
0
      green_to_red_best, accumulated_red_histo);
582
0
  for (iter = 0; iter < kMaxIters; ++iter) {
583
    // ColorTransformDelta is a 3.5 bit fixed point, so 32 is equal to
584
    // one in color computation. Having initial delta here as 1 is sufficient
585
    // to explore the range of (-2, 2).
586
0
    const int delta = 32 >> iter;
587
    // Try a negative and a positive delta from the best known value.
588
0
    for (offset = -delta; offset <= delta; offset += 2 * delta) {
589
0
      const int green_to_red_cur = offset + green_to_red_best;
590
0
      const float cur_diff = GetPredictionCostCrossColorRed(
591
0
          argb, stride, tile_width, tile_height, prev_x, prev_y,
592
0
          green_to_red_cur, accumulated_red_histo);
593
0
      if (cur_diff < best_diff) {
594
0
        best_diff = cur_diff;
595
0
        green_to_red_best = green_to_red_cur;
596
0
      }
597
0
    }
598
0
  }
599
0
  best_tx->green_to_red_ = (green_to_red_best & 0xff);
600
0
}
601
602
static float GetPredictionCostCrossColorBlue(
603
    const uint32_t* argb, int stride, int tile_width, int tile_height,
604
    VP8LMultipliers prev_x, VP8LMultipliers prev_y, int green_to_blue,
605
0
    int red_to_blue, const uint32_t accumulated_blue_histo[256]) {
606
0
  uint32_t histo[256] = { 0 };
607
0
  float cur_diff;
608
609
0
  VP8LCollectColorBlueTransforms(argb, stride, tile_width, tile_height,
610
0
                                 green_to_blue, red_to_blue, histo);
611
612
0
  cur_diff = PredictionCostCrossColor(accumulated_blue_histo, histo);
613
0
  if ((uint8_t)green_to_blue == prev_x.green_to_blue_) {
614
0
    cur_diff -= 3;  // favor keeping the areas locally similar
615
0
  }
616
0
  if ((uint8_t)green_to_blue == prev_y.green_to_blue_) {
617
0
    cur_diff -= 3;  // favor keeping the areas locally similar
618
0
  }
619
0
  if ((uint8_t)red_to_blue == prev_x.red_to_blue_) {
620
0
    cur_diff -= 3;  // favor keeping the areas locally similar
621
0
  }
622
0
  if ((uint8_t)red_to_blue == prev_y.red_to_blue_) {
623
0
    cur_diff -= 3;  // favor keeping the areas locally similar
624
0
  }
625
0
  if (green_to_blue == 0) {
626
0
    cur_diff -= 3;
627
0
  }
628
0
  if (red_to_blue == 0) {
629
0
    cur_diff -= 3;
630
0
  }
631
0
  return cur_diff;
632
0
}
633
634
0
#define kGreenRedToBlueNumAxis 8
635
0
#define kGreenRedToBlueMaxIters 7
636
static void GetBestGreenRedToBlue(const uint32_t* argb, int stride,
637
                                  int tile_width, int tile_height,
638
                                  VP8LMultipliers prev_x,
639
                                  VP8LMultipliers prev_y, int quality,
640
                                  const uint32_t accumulated_blue_histo[256],
641
0
                                  VP8LMultipliers* const best_tx) {
642
0
  const int8_t offset[kGreenRedToBlueNumAxis][2] =
643
0
      {{0, -1}, {0, 1}, {-1, 0}, {1, 0}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}};
644
0
  const int8_t delta_lut[kGreenRedToBlueMaxIters] = { 16, 16, 8, 4, 2, 2, 2 };
645
0
  const int iters =
646
0
      (quality < 25) ? 1 : (quality > 50) ? kGreenRedToBlueMaxIters : 4;
647
0
  int green_to_blue_best = 0;
648
0
  int red_to_blue_best = 0;
649
0
  int iter;
650
  // Initial value at origin:
651
0
  float best_diff = GetPredictionCostCrossColorBlue(
652
0
      argb, stride, tile_width, tile_height, prev_x, prev_y,
653
0
      green_to_blue_best, red_to_blue_best, accumulated_blue_histo);
654
0
  for (iter = 0; iter < iters; ++iter) {
655
0
    const int delta = delta_lut[iter];
656
0
    int axis;
657
0
    for (axis = 0; axis < kGreenRedToBlueNumAxis; ++axis) {
658
0
      const int green_to_blue_cur =
659
0
          offset[axis][0] * delta + green_to_blue_best;
660
0
      const int red_to_blue_cur = offset[axis][1] * delta + red_to_blue_best;
661
0
      const float cur_diff = GetPredictionCostCrossColorBlue(
662
0
          argb, stride, tile_width, tile_height, prev_x, prev_y,
663
0
          green_to_blue_cur, red_to_blue_cur, accumulated_blue_histo);
664
0
      if (cur_diff < best_diff) {
665
0
        best_diff = cur_diff;
666
0
        green_to_blue_best = green_to_blue_cur;
667
0
        red_to_blue_best = red_to_blue_cur;
668
0
      }
669
0
      if (quality < 25 && iter == 4) {
670
        // Only axis aligned diffs for lower quality.
671
0
        break;  // next iter.
672
0
      }
673
0
    }
674
0
    if (delta == 2 && green_to_blue_best == 0 && red_to_blue_best == 0) {
675
      // Further iterations would not help.
676
0
      break;  // out of iter-loop.
677
0
    }
678
0
  }
679
0
  best_tx->green_to_blue_ = green_to_blue_best & 0xff;
680
0
  best_tx->red_to_blue_ = red_to_blue_best & 0xff;
681
0
}
682
#undef kGreenRedToBlueMaxIters
683
#undef kGreenRedToBlueNumAxis
684
685
static VP8LMultipliers GetBestColorTransformForTile(
686
    int tile_x, int tile_y, int bits, VP8LMultipliers prev_x,
687
    VP8LMultipliers prev_y, int quality, int xsize, int ysize,
688
    const uint32_t accumulated_red_histo[256],
689
0
    const uint32_t accumulated_blue_histo[256], const uint32_t* const argb) {
690
0
  const int max_tile_size = 1 << bits;
691
0
  const int tile_y_offset = tile_y * max_tile_size;
692
0
  const int tile_x_offset = tile_x * max_tile_size;
693
0
  const int all_x_max = GetMin(tile_x_offset + max_tile_size, xsize);
694
0
  const int all_y_max = GetMin(tile_y_offset + max_tile_size, ysize);
695
0
  const int tile_width = all_x_max - tile_x_offset;
696
0
  const int tile_height = all_y_max - tile_y_offset;
697
0
  const uint32_t* const tile_argb = argb + tile_y_offset * xsize
698
0
                                  + tile_x_offset;
699
0
  VP8LMultipliers best_tx;
700
0
  MultipliersClear(&best_tx);
701
702
0
  GetBestGreenToRed(tile_argb, xsize, tile_width, tile_height,
703
0
                    prev_x, prev_y, quality, accumulated_red_histo, &best_tx);
704
0
  GetBestGreenRedToBlue(tile_argb, xsize, tile_width, tile_height,
705
0
                        prev_x, prev_y, quality, accumulated_blue_histo,
706
0
                        &best_tx);
707
0
  return best_tx;
708
0
}
709
710
static void CopyTileWithColorTransform(int xsize, int ysize,
711
                                       int tile_x, int tile_y,
712
                                       int max_tile_size,
713
                                       VP8LMultipliers color_transform,
714
0
                                       uint32_t* argb) {
715
0
  const int xscan = GetMin(max_tile_size, xsize - tile_x);
716
0
  int yscan = GetMin(max_tile_size, ysize - tile_y);
717
0
  argb += tile_y * xsize + tile_x;
718
0
  while (yscan-- > 0) {
719
0
    VP8LTransformColor(&color_transform, argb, xscan);
720
0
    argb += xsize;
721
0
  }
722
0
}
723
724
int VP8LColorSpaceTransform(int width, int height, int bits, int quality,
725
                            uint32_t* const argb, uint32_t* image,
726
                            const WebPPicture* const pic, int percent_range,
727
0
                            int* const percent) {
728
0
  const int max_tile_size = 1 << bits;
729
0
  const int tile_xsize = VP8LSubSampleSize(width, bits);
730
0
  const int tile_ysize = VP8LSubSampleSize(height, bits);
731
0
  int percent_start = *percent;
732
0
  uint32_t accumulated_red_histo[256] = { 0 };
733
0
  uint32_t accumulated_blue_histo[256] = { 0 };
734
0
  int tile_x, tile_y;
735
0
  VP8LMultipliers prev_x, prev_y;
736
0
  MultipliersClear(&prev_y);
737
0
  MultipliersClear(&prev_x);
738
0
  for (tile_y = 0; tile_y < tile_ysize; ++tile_y) {
739
0
    for (tile_x = 0; tile_x < tile_xsize; ++tile_x) {
740
0
      int y;
741
0
      const int tile_x_offset = tile_x * max_tile_size;
742
0
      const int tile_y_offset = tile_y * max_tile_size;
743
0
      const int all_x_max = GetMin(tile_x_offset + max_tile_size, width);
744
0
      const int all_y_max = GetMin(tile_y_offset + max_tile_size, height);
745
0
      const int offset = tile_y * tile_xsize + tile_x;
746
0
      if (tile_y != 0) {
747
0
        ColorCodeToMultipliers(image[offset - tile_xsize], &prev_y);
748
0
      }
749
0
      prev_x = GetBestColorTransformForTile(tile_x, tile_y, bits,
750
0
                                            prev_x, prev_y,
751
0
                                            quality, width, height,
752
0
                                            accumulated_red_histo,
753
0
                                            accumulated_blue_histo,
754
0
                                            argb);
755
0
      image[offset] = MultipliersToColorCode(&prev_x);
756
0
      CopyTileWithColorTransform(width, height, tile_x_offset, tile_y_offset,
757
0
                                 max_tile_size, prev_x, argb);
758
759
      // Gather accumulated histogram data.
760
0
      for (y = tile_y_offset; y < all_y_max; ++y) {
761
0
        int ix = y * width + tile_x_offset;
762
0
        const int ix_end = ix + all_x_max - tile_x_offset;
763
0
        for (; ix < ix_end; ++ix) {
764
0
          const uint32_t pix = argb[ix];
765
0
          if (ix >= 2 &&
766
0
              pix == argb[ix - 2] &&
767
0
              pix == argb[ix - 1]) {
768
0
            continue;  // repeated pixels are handled by backward references
769
0
          }
770
0
          if (ix >= width + 2 &&
771
0
              argb[ix - 2] == argb[ix - width - 2] &&
772
0
              argb[ix - 1] == argb[ix - width - 1] &&
773
0
              pix == argb[ix - width]) {
774
0
            continue;  // repeated pixels are handled by backward references
775
0
          }
776
0
          ++accumulated_red_histo[(pix >> 16) & 0xff];
777
0
          ++accumulated_blue_histo[(pix >> 0) & 0xff];
778
0
        }
779
0
      }
780
0
    }
781
0
    if (!WebPReportProgress(
782
0
            pic, percent_start + percent_range * tile_y / tile_ysize,
783
0
            percent)) {
784
0
      return 0;
785
0
    }
786
0
  }
787
0
  return 1;
788
0
}