Coverage Report

Created: 2026-11-12 06:47

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libwebp/src/enc/predictor_enc.c
Line
Count
Source
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 <assert.h>
18
#include <stdlib.h>
19
#include <string.h>
20
21
#include "src/dsp/lossless.h"
22
#include "src/dsp/lossless_common.h"
23
#include "src/enc/vp8i_enc.h"
24
#include "src/enc/vp8li_enc.h"
25
#include "src/utils/utils.h"
26
#include "src/webp/encode.h"
27
#include "src/webp/format_constants.h"
28
#include "src/webp/types.h"
29
30
0
#define HISTO_SIZE (4 * 256)
31
static const int64_t kSpatialPredictorBias = 15ll << LOG_2_PRECISION_BITS;
32
static const int kPredLowEffort = 11;
33
static const uint32_t kMaskAlpha = 0xff000000;
34
static const int kNumPredModes = 14;
35
36
// Mostly used to reduce code size + readability
37
0
static WEBP_INLINE int GetMin(int a, int b) { return (a > b) ? b : a; }
38
0
static WEBP_INLINE int GetMax(int a, int b) { return (a < b) ? b : a; }
39
40
//------------------------------------------------------------------------------
41
// Methods to calculate Entropy (Shannon).
42
43
// Compute a bias for prediction entropy using a global heuristic to favor
44
// values closer to 0. Hence the final negative sign.
45
// 'exp_val' has a scaling factor of 1/100.
46
static int64_t PredictionCostBias(const uint32_t counts[256], uint64_t weight_0,
47
0
                                  uint64_t exp_val) {
48
0
  const int significant_symbols = 256 >> 4;
49
0
  const uint64_t exp_decay_factor = 6;  // has a scaling factor of 1/10
50
0
  uint64_t bits = (weight_0 * counts[0]) << LOG_2_PRECISION_BITS;
51
0
  int i;
52
0
  exp_val <<= LOG_2_PRECISION_BITS;
53
0
  for (i = 1; i < significant_symbols; ++i) {
54
0
    bits += DivRound(exp_val * (counts[i] + counts[256 - i]), 100);
55
0
    exp_val = DivRound(exp_decay_factor * exp_val, 10);
56
0
  }
57
0
  return -DivRound((int64_t)bits, 10);
58
0
}
59
60
static int64_t PredictionCostSpatialHistogram(
61
    const uint32_t accumulated[HISTO_SIZE], const uint32_t tile[HISTO_SIZE],
62
0
    int mode, int left_mode, int above_mode, uint32_t diff_mask) {
63
0
  int i;
64
0
  int64_t retval = 0;
65
0
  for (i = 0; i < 4; ++i) {
66
0
    if ((diff_mask >> i) & 1) {
67
0
      const uint64_t kExpValue = 94;
68
0
      retval += PredictionCostBias(&tile[i * 256], 1, kExpValue);
69
      // Compute the new cost if 'tile' is added to 'accumulate' but also add
70
      // the cost of the current histogram to guide the spatial predictor
71
      // selection. Basically, favor low entropy, locally and globally.
72
0
      retval += (int64_t)VP8LCombinedShannonEntropy(&tile[i * 256],
73
0
                                                    &accumulated[i * 256]);
74
0
    }
75
0
  }
76
  // Favor keeping the areas locally similar.
77
0
  if (mode == left_mode) retval -= kSpatialPredictorBias;
78
0
  if (mode == above_mode) retval -= kSpatialPredictorBias;
79
0
  return retval;
80
0
}
81
82
static WEBP_INLINE void UpdateHisto(uint32_t histo_argb[HISTO_SIZE],
83
                                    const uint32_t* const residuals, int max_x,
84
0
                                    uint32_t diff_mask) {
85
0
  int plane, x;
86
0
  for (plane = 0; plane < 4; ++plane) {
87
0
    if ((diff_mask >> plane) & 1) {
88
0
      uint32_t* const histo = &histo_argb[plane * 256];
89
0
      const int shift = (3 - plane) * 8;
90
0
      for (x = 0; x < max_x; ++x) {
91
0
        ++histo[(residuals[x] >> shift) & 0xff];
92
0
      }
93
0
    }
94
0
  }
95
0
}
96
97
// Returns a 4-bit mask (bit 0 = Alpha, 1 = Red, 2 = Green, 3 = Blue) where bit
98
// i is set if plane i is non-constant and must be included in residual
99
// histograms and entropy calculations.
100
// Sets *min_mode to 1 if predictor mode 0 (ARGB_BLACK) must be skipped, or 0
101
// otherwise.
102
// TODO(skal): could be SIMD'd
103
static uint32_t GetPlaneDiffMask(const uint32_t* const argb, int width,
104
                                 int height, int max_quantization, int exact,
105
0
                                 int* const min_mode) {
106
0
  const int n = width * height;
107
0
  const uint32_t first = argb[0];
108
0
  uint32_t has_diff = 0u;
109
0
  uint32_t diff_mask = 0u;
110
0
  int i;
111
0
  *min_mode = 0;
112
  // In near-lossless mode, GetResidual() modifies pixels in-place based on
113
  // local smoothness, so an initially constant plane may not remain constant.
114
0
  if (max_quantization > 1) return 0xfu;
115
0
  for (i = 1; i < n; ++i) has_diff |= argb[i] ^ first;
116
0
  if (!exact) {
117
    // When !exact, GetResidual() zeroes RGB residuals on transparent pixels
118
    // (alpha == 0) and overwrites their RGB values with the prediction.
119
0
    if ((has_diff & 0xff000000u) == 0) {
120
0
      if ((first & 0xff000000u) == 0) {
121
        // Alpha is constantly 0: all RGB residuals are forced to 0 and alpha
122
        // is constant. Skip mode 0 (which predicts alpha = 0xff) and all
123
        // planes.
124
0
        *min_mode = 1;
125
0
        return 0u;
126
0
      }
127
0
    } else {
128
      // Alpha varies, so some pixels have alpha == 0 and others have
129
      // alpha != 0. A constant RGB channel remains constant after transparent
130
      // pixel cleanup only if its constant value is 0 (and mode 0 is also
131
      // fine since ARGB_BLACK has RGB == 0).
132
0
      has_diff |= first & 0x00ffffffu;
133
0
    }
134
0
  }
135
0
  if (has_diff & 0xff000000u) diff_mask |= 1;
136
0
  if (has_diff & 0x00ff0000u) diff_mask |= 2;
137
0
  if (has_diff & 0x0000ff00u) diff_mask |= 4;
138
0
  if (has_diff & 0x000000ffu) diff_mask |= 8;
139
  // For a constant plane i, predictors 1..13 predict from neighboring pixels
140
  // and yield 0 residuals everywhere (except at (0, 0)), whereas mode 0
141
  // predicts ARGB_BLACK on interior pixels (x > 0, y > 0). If the constant
142
  // plane value differs from ARGB_BLACK, skip mode 0 so it cannot be selected
143
  // and pollute the constant plane with non-zero residuals.
144
0
  for (i = 0; i < 4; ++i) {
145
0
    if (((diff_mask >> i) & 1) == 0) {
146
0
      const uint32_t mask = 0xff000000u >> (8 * i);
147
0
      if ((first & mask) != (ARGB_BLACK & mask)) *min_mode = 1;
148
0
    }
149
0
  }
150
0
  return diff_mask;
151
0
}
152
153
//------------------------------------------------------------------------------
154
// Spatial transform functions.
155
156
static WEBP_INLINE void PredictBatch(int mode, int x_start, int y,
157
                                     int num_pixels, const uint32_t* current,
158
0
                                     const uint32_t* upper, uint32_t* out) {
159
0
  if (x_start == 0) {
160
0
    if (y == 0) {
161
      // ARGB_BLACK.
162
0
      VP8LPredictorsSub[0](current, NULL, 1, out);
163
0
    } else {
164
      // Top one.
165
0
      VP8LPredictorsSub[2](current, upper, 1, out);
166
0
    }
167
0
    ++x_start;
168
0
    ++out;
169
0
    --num_pixels;
170
0
  }
171
0
  if (y == 0) {
172
    // Left one.
173
0
    VP8LPredictorsSub[1](current + x_start, NULL, num_pixels, out);
174
0
  } else {
175
0
    VP8LPredictorsSub[mode](current + x_start, upper + x_start, num_pixels,
176
0
                            out);
177
0
  }
178
0
}
179
180
#if (WEBP_NEAR_LOSSLESS == 1)
181
0
static int MaxDiffBetweenPixels(uint32_t p1, uint32_t p2) {
182
0
  const int diff_a = abs((int)(p1 >> 24) - (int)(p2 >> 24));
183
0
  const int diff_r = abs((int)((p1 >> 16) & 0xff) - (int)((p2 >> 16) & 0xff));
184
0
  const int diff_g = abs((int)((p1 >> 8) & 0xff) - (int)((p2 >> 8) & 0xff));
185
0
  const int diff_b = abs((int)(p1 & 0xff) - (int)(p2 & 0xff));
186
0
  return GetMax(GetMax(diff_a, diff_r), GetMax(diff_g, diff_b));
187
0
}
188
189
static int MaxDiffAroundPixel(uint32_t current, uint32_t up, uint32_t down,
190
0
                              uint32_t left, uint32_t right) {
191
0
  const int diff_up = MaxDiffBetweenPixels(current, up);
192
0
  const int diff_down = MaxDiffBetweenPixels(current, down);
193
0
  const int diff_left = MaxDiffBetweenPixels(current, left);
194
0
  const int diff_right = MaxDiffBetweenPixels(current, right);
195
0
  return GetMax(GetMax(diff_up, diff_down), GetMax(diff_left, diff_right));
196
0
}
197
198
0
static uint32_t AddGreenToBlueAndRed(uint32_t argb) {
199
0
  const uint32_t green = (argb >> 8) & 0xff;
200
0
  uint32_t red_blue = argb & 0x00ff00ffu;
201
0
  red_blue += (green << 16) | green;
202
0
  red_blue &= 0x00ff00ffu;
203
0
  return (argb & 0xff00ff00u) | red_blue;
204
0
}
205
206
static void MaxDiffsForRow(int width, int stride, const uint32_t* const argb,
207
0
                           uint8_t* const max_diffs, int used_subtract_green) {
208
0
  uint32_t current, up, down, left, right;
209
0
  int x;
210
0
  if (width <= 2) return;
211
0
  current = argb[0];
212
0
  right = argb[1];
213
0
  if (used_subtract_green) {
214
0
    current = AddGreenToBlueAndRed(current);
215
0
    right = AddGreenToBlueAndRed(right);
216
0
  }
217
  // max_diffs[0] and max_diffs[width - 1] are never used.
218
0
  for (x = 1; x < width - 1; ++x) {
219
0
    up = argb[-stride + x];
220
0
    down = argb[stride + x];
221
0
    left = current;
222
0
    current = right;
223
0
    right = argb[x + 1];
224
0
    if (used_subtract_green) {
225
0
      up = AddGreenToBlueAndRed(up);
226
0
      down = AddGreenToBlueAndRed(down);
227
0
      right = AddGreenToBlueAndRed(right);
228
0
    }
229
0
    max_diffs[x] = MaxDiffAroundPixel(current, up, down, left, right);
230
0
  }
231
0
}
232
233
// Quantize the difference between the actual component value and its prediction
234
// to a multiple of quantization, working modulo 256, taking care not to cross
235
// a boundary (inclusive upper limit).
236
static uint8_t NearLosslessComponent(uint8_t value, uint8_t predict,
237
0
                                     uint8_t boundary, int quantization) {
238
0
  const int residual = (value - predict) & 0xff;
239
0
  const int boundary_residual = (boundary - predict) & 0xff;
240
0
  const int lower = residual & ~(quantization - 1);
241
0
  const int upper = lower + quantization;
242
  // Resolve ties towards a value closer to the prediction (i.e. towards lower
243
  // if value comes after prediction and towards upper otherwise).
244
0
  const int bias = ((boundary - value) & 0xff) < boundary_residual;
245
0
  if (residual - lower < upper - residual + bias) {
246
    // lower is closer to residual than upper.
247
0
    if (residual > boundary_residual && lower <= boundary_residual) {
248
      // Halve quantization step to avoid crossing boundary. This midpoint is
249
      // on the same side of boundary as residual because midpoint >= residual
250
      // (since lower is closer than upper) and residual is above the boundary.
251
0
      return lower + (quantization >> 1);
252
0
    }
253
0
    return lower;
254
0
  } else {
255
    // upper is closer to residual than lower.
256
0
    if (residual <= boundary_residual && upper > boundary_residual) {
257
      // Halve quantization step to avoid crossing boundary. This midpoint is
258
      // on the same side of boundary as residual because midpoint <= residual
259
      // (since upper is closer than lower) and residual is below the boundary.
260
0
      return lower + (quantization >> 1);
261
0
    }
262
0
    return upper & 0xff;
263
0
  }
264
0
}
265
266
0
static WEBP_INLINE uint8_t NearLosslessDiff(uint8_t a, uint8_t b) {
267
0
  return (uint8_t)((((int)(a) - (int)(b))) & 0xff);
268
0
}
269
270
// Quantize every component of the difference between the actual pixel value and
271
// its prediction to a multiple of a quantization (a power of 2, not larger than
272
// max_quantization which is a power of 2, smaller than max_diff). Take care if
273
// value and predict have undergone subtract green, which means that red and
274
// blue are represented as offsets from green.
275
static uint32_t NearLossless(uint32_t value, uint32_t predict,
276
                             int max_quantization, int max_diff,
277
0
                             int used_subtract_green) {
278
0
  int quantization;
279
0
  uint8_t new_green = 0;
280
0
  uint8_t green_diff = 0;
281
0
  uint8_t a, r, g, b;
282
0
  if (max_diff <= 2) {
283
0
    return VP8LSubPixels(value, predict);
284
0
  }
285
0
  quantization = max_quantization;
286
0
  while (quantization >= max_diff) {
287
0
    quantization >>= 1;
288
0
  }
289
0
  if ((value >> 24) == 0 || (value >> 24) == 0xff) {
290
    // Preserve transparency of fully transparent or fully opaque pixels.
291
0
    a = NearLosslessDiff((value >> 24) & 0xff, (predict >> 24) & 0xff);
292
0
  } else {
293
0
    a = NearLosslessComponent(value >> 24, predict >> 24, 0xff, quantization);
294
0
  }
295
0
  g = NearLosslessComponent((value >> 8) & 0xff, (predict >> 8) & 0xff, 0xff,
296
0
                            quantization);
297
0
  if (used_subtract_green) {
298
    // The green offset will be added to red and blue components during decoding
299
    // to obtain the actual red and blue values.
300
0
    new_green = ((predict >> 8) + g) & 0xff;
301
    // The amount by which green has been adjusted during quantization. It is
302
    // subtracted from red and blue for compensation, to avoid accumulating two
303
    // quantization errors in them.
304
0
    green_diff = NearLosslessDiff(new_green, (value >> 8) & 0xff);
305
0
  }
306
0
  r = NearLosslessComponent(NearLosslessDiff((value >> 16) & 0xff, green_diff),
307
0
                            (predict >> 16) & 0xff, 0xff - new_green,
308
0
                            quantization);
309
0
  b = NearLosslessComponent(NearLosslessDiff(value & 0xff, green_diff),
310
0
                            predict & 0xff, 0xff - new_green, quantization);
311
0
  return ((uint32_t)a << 24) | ((uint32_t)r << 16) | ((uint32_t)g << 8) | b;
312
0
}
313
#endif  // (WEBP_NEAR_LOSSLESS == 1)
314
315
// Stores the difference between the pixel and its prediction in "out".
316
// In case of a lossy encoding, updates the source image to avoid propagating
317
// the deviation further to pixels which depend on the current pixel for their
318
// predictions.
319
static WEBP_INLINE void GetResidual(
320
    int width, int height, uint32_t* const upper_row,
321
    uint32_t* const current_row, const uint8_t* const max_diffs, int mode,
322
    int x_start, int x_end, int y, int max_quantization, int exact,
323
0
    int used_subtract_green, uint32_t* const out) {
324
0
  if (exact) {
325
0
    PredictBatch(mode, x_start, y, x_end - x_start, current_row, upper_row,
326
0
                 out);
327
0
  } else {
328
0
    const VP8LPredictorFunc pred_func = VP8LPredictors[mode];
329
0
    int x;
330
0
    for (x = x_start; x < x_end; ++x) {
331
0
      uint32_t predict;
332
0
      uint32_t residual;
333
0
      if (y == 0) {
334
0
        predict = (x == 0) ? ARGB_BLACK : current_row[x - 1];  // Left.
335
0
      } else if (x == 0) {
336
0
        predict = upper_row[x];  // Top.
337
0
      } else {
338
0
        predict = pred_func(&current_row[x - 1], upper_row + x);
339
0
      }
340
0
#if (WEBP_NEAR_LOSSLESS == 1)
341
0
      if (max_quantization == 1 || mode == 0 || y == 0 || y == height - 1 ||
342
0
          x == 0 || x == width - 1) {
343
0
        residual = VP8LSubPixels(current_row[x], predict);
344
0
      } else {
345
0
        residual = NearLossless(current_row[x], predict, max_quantization,
346
0
                                max_diffs[x], used_subtract_green);
347
        // Update the source image.
348
0
        current_row[x] = VP8LAddPixels(predict, residual);
349
        // x is never 0 here so we do not need to update upper_row like below.
350
0
      }
351
#else
352
      (void)max_diffs;
353
      (void)height;
354
      (void)max_quantization;
355
      (void)used_subtract_green;
356
      residual = VP8LSubPixels(current_row[x], predict);
357
#endif
358
0
      if ((current_row[x] & kMaskAlpha) == 0) {
359
        // If alpha is 0, cleanup RGB. We can choose the RGB values of the
360
        // residual for best compression. The prediction of alpha itself can be
361
        // non-zero and must be kept though. We choose RGB of the residual to be
362
        // 0.
363
0
        residual &= kMaskAlpha;
364
        // Update the source image.
365
0
        current_row[x] = predict & ~kMaskAlpha;
366
        // The prediction for the rightmost pixel in a row uses the leftmost
367
        // pixel
368
        // in that row as its top-right context pixel. Hence if we change the
369
        // leftmost pixel of current_row, the corresponding change must be
370
        // applied
371
        // to upper_row as well where top-right context is being read from.
372
0
        if (x == 0 && y != 0) upper_row[width] = current_row[0];
373
0
      }
374
0
      out[x - x_start] = residual;
375
0
    }
376
0
  }
377
0
}
378
379
// Accessors to residual histograms.
380
static WEBP_INLINE uint32_t* GetHistoArgb(uint32_t* const all_histos,
381
0
                                          int subsampling_index, int mode) {
382
0
  return &all_histos[(subsampling_index * kNumPredModes + mode) * HISTO_SIZE];
383
0
}
384
385
static WEBP_INLINE const uint32_t* GetHistoArgbConst(
386
0
    const uint32_t* const all_histos, int subsampling_index, int mode) {
387
0
  return &all_histos[subsampling_index * kNumPredModes * HISTO_SIZE +
388
0
                     mode * HISTO_SIZE];
389
0
}
390
391
// Accessors to accumulated residual histogram.
392
static WEBP_INLINE uint32_t* GetAccumulatedHisto(uint32_t* all_accumulated,
393
0
                                                 int subsampling_index) {
394
0
  return &all_accumulated[subsampling_index * HISTO_SIZE];
395
0
}
396
397
// Find and store the best predictor for a tile at subsampling
398
// 'subsampling_index'.
399
static void GetBestPredictorForTile(const uint32_t* const all_argb,
400
                                    int subsampling_index, int tile_x,
401
                                    int tile_y, int tiles_per_row,
402
                                    uint32_t* all_accumulated_argb,
403
                                    uint32_t** const all_modes,
404
                                    uint32_t* const all_pred_histos,
405
0
                                    int min_mode, uint32_t diff_mask) {
406
0
  uint32_t* const accumulated_argb =
407
0
      GetAccumulatedHisto(all_accumulated_argb, subsampling_index);
408
0
  uint32_t* const modes = all_modes[subsampling_index];
409
0
  uint32_t* const pred_histos =
410
0
      &all_pred_histos[subsampling_index * kNumPredModes];
411
  // Prediction modes of the left and above neighbor tiles.
412
0
  const int left_mode =
413
0
      (tile_x > 0) ? (modes[tile_y * tiles_per_row + tile_x - 1] >> 8) & 0xff
414
0
                   : 0xff;
415
0
  const int above_mode =
416
0
      (tile_y > 0) ? (modes[(tile_y - 1) * tiles_per_row + tile_x] >> 8) & 0xff
417
0
                   : 0xff;
418
0
  int mode, plane;
419
0
  int64_t best_diff = WEBP_INT64_MAX;
420
0
  uint32_t best_mode = min_mode;
421
0
  const uint32_t* best_histo =
422
0
      GetHistoArgbConst(all_argb, subsampling_index, best_mode);
423
0
  for (mode = min_mode; mode < kNumPredModes; ++mode) {
424
0
    const uint32_t* const histo_argb =
425
0
        GetHistoArgbConst(all_argb, subsampling_index, mode);
426
0
    const int64_t cur_diff = PredictionCostSpatialHistogram(
427
0
        accumulated_argb, histo_argb, mode, left_mode, above_mode, diff_mask);
428
429
0
    if (cur_diff < best_diff) {
430
0
      best_histo = histo_argb;
431
0
      best_diff = cur_diff;
432
0
      best_mode = mode;
433
0
    }
434
0
  }
435
  // Update the accumulated histogram.
436
0
  for (plane = 0; plane < 4; ++plane) {
437
0
    if ((diff_mask >> plane) & 1) {
438
0
      VP8LAddVectorEq(&best_histo[plane * 256], &accumulated_argb[plane * 256],
439
0
                      256);
440
0
    }
441
0
  }
442
0
  modes[tile_y * tiles_per_row + tile_x] = ARGB_BLACK | (best_mode << 8);
443
0
  ++pred_histos[best_mode];
444
0
}
445
446
// Computes the residuals for the different predictors.
447
// If max_quantization > 1, assumes that near lossless processing will be
448
// applied, quantizing residuals to multiples of quantization levels up to
449
// max_quantization (the actual quantization level depends on smoothness near
450
// the given pixel).
451
static void ComputeResidualsForTile(
452
    int width, int height, int tile_x, int tile_y, int min_bits,
453
    uint32_t update_up_to_index, uint32_t* const all_argb,
454
    uint32_t* const argb_scratch, const uint32_t* const argb,
455
    int max_quantization, int exact, int used_subtract_green, int min_mode,
456
0
    uint32_t diff_mask) {
457
0
  const int start_x = tile_x << min_bits;
458
0
  const int start_y = tile_y << min_bits;
459
0
  const int tile_size = 1 << min_bits;
460
0
  const int max_y = GetMin(tile_size, height - start_y);
461
0
  const int max_x = GetMin(tile_size, width - start_x);
462
  // Whether there exist columns just outside the tile.
463
0
  const int have_left = (start_x > 0);
464
  // Position and size of the strip covering the tile and adjacent columns if
465
  // they exist.
466
0
  const int context_start_x = start_x - have_left;
467
0
#if (WEBP_NEAR_LOSSLESS == 1)
468
0
  const int context_width = max_x + have_left + (max_x < width - start_x);
469
0
#endif
470
  // The width of upper_row and current_row is one pixel larger than image width
471
  // to allow the top right pixel to point to the leftmost pixel of the next row
472
  // when at the right edge.
473
0
  uint32_t* upper_row = argb_scratch;
474
0
  uint32_t* current_row = upper_row + width + 1;
475
0
  uint8_t* const max_diffs = (uint8_t*)(current_row + width + 1);
476
0
  int mode;
477
  // Need pointers to be able to swap arrays.
478
0
  uint32_t residuals[1 << MAX_TRANSFORM_BITS];
479
0
  assert(max_x <= (1 << MAX_TRANSFORM_BITS));
480
0
  for (mode = min_mode; mode < kNumPredModes; ++mode) {
481
0
    int relative_y;
482
0
    uint32_t* const histo_argb =
483
0
        GetHistoArgb(all_argb, /*subsampling_index=*/0, mode);
484
0
    if (start_y > 0) {
485
      // Read the row above the tile which will become the first upper_row.
486
      // Include a pixel to the left if it exists; include a pixel to the right
487
      // in all cases (wrapping to the leftmost pixel of the next row if it does
488
      // not exist).
489
0
      memcpy(current_row + context_start_x,
490
0
             argb + (start_y - 1) * width + context_start_x,
491
0
             sizeof(*argb) * (max_x + have_left + 1));
492
0
    }
493
0
    for (relative_y = 0; relative_y < max_y; ++relative_y) {
494
0
      const int y = start_y + relative_y;
495
0
      uint32_t* tmp = upper_row;
496
0
      upper_row = current_row;
497
0
      current_row = tmp;
498
      // Read current_row. Include a pixel to the left if it exists; include a
499
      // pixel to the right in all cases except at the bottom right corner of
500
      // the image (wrapping to the leftmost pixel of the next row if it does
501
      // not exist in the current row).
502
0
      memcpy(current_row + context_start_x, argb + y * width + context_start_x,
503
0
             sizeof(*argb) * (max_x + have_left + (y + 1 < height)));
504
0
#if (WEBP_NEAR_LOSSLESS == 1)
505
0
      if (max_quantization > 1 && y >= 1 && y + 1 < height) {
506
0
        MaxDiffsForRow(context_width, width, argb + y * width + context_start_x,
507
0
                       max_diffs + context_start_x, used_subtract_green);
508
0
      }
509
0
#endif
510
511
0
      GetResidual(width, height, upper_row, current_row, max_diffs, mode,
512
0
                  start_x, start_x + max_x, y, max_quantization, exact,
513
0
                  used_subtract_green, residuals);
514
0
      UpdateHisto(histo_argb, residuals, max_x, diff_mask);
515
0
      if (update_up_to_index > 0) {
516
0
        uint32_t subsampling_index;
517
0
        for (subsampling_index = 1; subsampling_index <= update_up_to_index;
518
0
             ++subsampling_index) {
519
0
          uint32_t* const super_histo =
520
0
              GetHistoArgb(all_argb, subsampling_index, mode);
521
0
          UpdateHisto(super_histo, residuals, max_x, diff_mask);
522
0
        }
523
0
      }
524
0
    }
525
0
  }
526
0
}
527
528
// Converts pixels of the image to residuals with respect to predictions.
529
// If max_quantization > 1, applies near lossless processing, quantizing
530
// residuals to multiples of quantization levels up to max_quantization
531
// (the actual quantization level depends on smoothness near the given pixel).
532
static void CopyImageWithPrediction(int width, int height, int bits,
533
                                    const uint32_t* const modes,
534
                                    uint32_t* const argb_scratch,
535
                                    uint32_t* const argb, int low_effort,
536
                                    int max_quantization, int exact,
537
0
                                    int used_subtract_green) {
538
0
  const int tiles_per_row = VP8LSubSampleSize(width, bits);
539
  // The width of upper_row and current_row is one pixel larger than image width
540
  // to allow the top right pixel to point to the leftmost pixel of the next row
541
  // when at the right edge.
542
0
  uint32_t* upper_row = argb_scratch;
543
0
  uint32_t* current_row = upper_row + width + 1;
544
0
  uint8_t* current_max_diffs = (uint8_t*)(current_row + width + 1);
545
0
#if (WEBP_NEAR_LOSSLESS == 1)
546
0
  uint8_t* lower_max_diffs = current_max_diffs + width;
547
0
#endif
548
0
  int y;
549
550
0
  for (y = 0; y < height; ++y) {
551
0
    int x;
552
0
    uint32_t* const tmp32 = upper_row;
553
0
    upper_row = current_row;
554
0
    current_row = tmp32;
555
0
    memcpy(current_row, argb + y * width,
556
0
           sizeof(*argb) * (width + (y + 1 < height)));
557
558
0
    if (low_effort) {
559
0
      PredictBatch(kPredLowEffort, 0, y, width, current_row, upper_row,
560
0
                   argb + y * width);
561
0
    } else {
562
0
#if (WEBP_NEAR_LOSSLESS == 1)
563
0
      if (max_quantization > 1) {
564
        // Compute max_diffs for the lower row now, because that needs the
565
        // contents of argb for the current row, which we will overwrite with
566
        // residuals before proceeding with the next row.
567
0
        uint8_t* const tmp8 = current_max_diffs;
568
0
        current_max_diffs = lower_max_diffs;
569
0
        lower_max_diffs = tmp8;
570
0
        if (y + 2 < height) {
571
0
          MaxDiffsForRow(width, width, argb + (y + 1) * width, lower_max_diffs,
572
0
                         used_subtract_green);
573
0
        }
574
0
      }
575
0
#endif
576
0
      for (x = 0; x < width;) {
577
0
        const int mode =
578
0
            (modes[(y >> bits) * tiles_per_row + (x >> bits)] >> 8) & 0xff;
579
0
        int x_end = x + (1 << bits);
580
0
        if (x_end > width) x_end = width;
581
0
        GetResidual(width, height, upper_row, current_row, current_max_diffs,
582
0
                    mode, x, x_end, y, max_quantization, exact,
583
0
                    used_subtract_green, argb + y * width + x);
584
0
        x = x_end;
585
0
      }
586
0
    }
587
0
  }
588
0
}
589
590
// Checks whether 'image' can be subsampled by finding the biggest power of 2
591
// squares (defined by 'best_bits') of uniform value it is made out of.
592
void VP8LOptimizeSampling(uint32_t* const image, int full_width,
593
                          int full_height, int bits, int max_bits,
594
0
                          int* best_bits_out) {
595
0
  int width = VP8LSubSampleSize(full_width, bits);
596
0
  int height = VP8LSubSampleSize(full_height, bits);
597
0
  int old_width, x, y, square_size;
598
0
  int best_bits = bits;
599
0
  *best_bits_out = bits;
600
  // Check rows first.
601
0
  while (best_bits < max_bits) {
602
0
    const int new_square_size = 1 << (best_bits + 1 - bits);
603
0
    int is_good = 1;
604
0
    square_size = 1 << (best_bits - bits);
605
0
    for (y = 0; y + square_size < height; y += new_square_size) {
606
      // Check the first lines of consecutive line groups.
607
0
      if (memcmp(&image[y * width], &image[(y + square_size) * width],
608
0
                 width * sizeof(*image)) != 0) {
609
0
        is_good = 0;
610
0
        break;
611
0
      }
612
0
    }
613
0
    if (is_good) {
614
0
      ++best_bits;
615
0
    } else {
616
0
      break;
617
0
    }
618
0
  }
619
0
  if (best_bits == bits) return;
620
621
  // Check columns.
622
0
  while (best_bits > bits) {
623
0
    int is_good = 1;
624
0
    square_size = 1 << (best_bits - bits);
625
0
    for (y = 0; is_good && y < height; ++y) {
626
0
      for (x = 0; is_good && x < width; x += square_size) {
627
0
        int i;
628
0
        for (i = x + 1; i < GetMin(x + square_size, width); ++i) {
629
0
          if (image[y * width + i] != image[y * width + x]) {
630
0
            is_good = 0;
631
0
            break;
632
0
          }
633
0
        }
634
0
      }
635
0
    }
636
0
    if (is_good) {
637
0
      break;
638
0
    }
639
0
    --best_bits;
640
0
  }
641
0
  if (best_bits == bits) return;
642
643
  // Subsample the image.
644
0
  old_width = width;
645
0
  square_size = 1 << (best_bits - bits);
646
0
  width = VP8LSubSampleSize(full_width, best_bits);
647
0
  height = VP8LSubSampleSize(full_height, best_bits);
648
0
  for (y = 0; y < height; ++y) {
649
0
    for (x = 0; x < width; ++x) {
650
0
      image[y * width + x] = image[square_size * (y * old_width + x)];
651
0
    }
652
0
  }
653
0
  *best_bits_out = best_bits;
654
0
}
655
656
// Computes the best predictor image.
657
// Finds the best predictors per tile. Once done, finds the best predictor image
658
// sampling.
659
// best_bits is set to 0 in case of error.
660
// The following requires some glossary:
661
// - a tile is a square of side 2^min_bits pixels.
662
// - a super-tile of a tile is a square of side 2^bits pixels with bits in
663
// [min_bits+1, max_bits].
664
// - the max-tile of a tile is the square of 2^max_bits pixels containing it.
665
//   If this max-tile crosses the border of an image, it is cropped.
666
// - tile, super-tiles and max_tile are aligned on powers of 2 in the original
667
//   image.
668
// - coordinates for tile, super-tile, max-tile are respectively named
669
//   tile_x, super_tile_x, max_tile_x at their bit scale.
670
// - in the max-tile, a tile has local coordinates (local_tile_x, local_tile_y).
671
// The tiles are processed in the following zigzag order to complete the
672
// super-tiles as soon as possible:
673
//   1  2|  5  6
674
//   3  4|  7  8
675
// --------------
676
//   9 10| 13 14
677
//  11 12| 15 16
678
// When computing the residuals for a tile, the histogram of the above
679
// super-tile is updated. If this super-tile is finished, its histogram is used
680
// to update the histogram of the next super-tile and so on up to the max-tile.
681
static void GetBestPredictorsAndSubSampling(
682
    int width, int height, const int min_bits, const int max_bits,
683
    uint32_t* const argb_scratch, const uint32_t* const argb,
684
    int max_quantization, int exact, int used_subtract_green, int min_mode,
685
    uint32_t diff_mask, const WebPPicture* const pic, int percent_range,
686
    int* const percent, uint32_t** const all_modes, int* best_bits,
687
0
    uint32_t** best_mode) {
688
0
  const uint32_t tiles_per_row = VP8LSubSampleSize(width, min_bits);
689
0
  const uint32_t tiles_per_col = VP8LSubSampleSize(height, min_bits);
690
0
  int64_t best_cost;
691
0
  uint32_t subsampling_index;
692
0
  const uint32_t max_subsampling_index = max_bits - min_bits;
693
  // Compute the needed memory size for residual histograms, accumulated
694
  // residual histograms and predictor histograms.
695
0
  const int num_argb = (max_subsampling_index + 1) * kNumPredModes * HISTO_SIZE;
696
0
  const int num_accumulated_rgb = (max_subsampling_index + 1) * HISTO_SIZE;
697
0
  const int num_predictors = (max_subsampling_index + 1) * kNumPredModes;
698
0
  uint32_t* const raw_data = (uint32_t*)WebPSafeCalloc(
699
0
      num_argb + num_accumulated_rgb + num_predictors, sizeof(uint32_t));
700
0
  uint32_t* const all_argb = raw_data;
701
0
  uint32_t* const all_accumulated_argb = all_argb + num_argb;
702
0
  uint32_t* const all_pred_histos = all_accumulated_argb + num_accumulated_rgb;
703
0
  const int max_tile_size = 1 << max_subsampling_index;  // in tile size
704
0
  int percent_start = *percent;
705
  // When using the residuals of a tile for its super-tiles, you can either:
706
  // - use each residual to update the histogram of the super-tile, with a cost
707
  //   of 4 * (1<<n)^2 increment operations (4 for the number of channels, and
708
  //   (1<<n)^2 for the number of pixels in the tile)
709
  // - use the histogram of the tile to update the histogram of the super-tile,
710
  //   with a cost of HISTO_SIZE (1024)
711
  // The first method is therefore faster until n==4. 'update_up_to_index'
712
  // defines the maximum subsampling_index for which the residuals should be
713
  // individually added to the super-tile histogram.
714
0
  const uint32_t update_up_to_index =
715
0
      GetMax(GetMin(4, max_bits), min_bits) - min_bits;
716
  // Coordinates in the max-tile in tile units.
717
0
  uint32_t local_tile_x = 0, local_tile_y = 0;
718
0
  uint32_t max_tile_x = 0, max_tile_y = 0;
719
0
  uint32_t tile_x = 0, tile_y = 0;
720
721
0
  *best_bits = 0;
722
0
  *best_mode = NULL;
723
0
  if (raw_data == NULL) {
724
0
    WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
725
0
    return;
726
0
  }
727
728
0
  while (tile_y < tiles_per_col) {
729
0
    uint32_t s;
730
0
    int mode, plane;
731
0
    ComputeResidualsForTile(width, height, tile_x, tile_y, min_bits,
732
0
                            update_up_to_index, all_argb, argb_scratch, argb,
733
0
                            max_quantization, exact, used_subtract_green,
734
0
                            min_mode, diff_mask);
735
736
    // Update all the super-tiles that are complete.
737
0
    subsampling_index = 0;
738
0
    while (1) {
739
0
      const uint32_t super_tile_x = tile_x >> subsampling_index;
740
0
      const uint32_t super_tile_y = tile_y >> subsampling_index;
741
0
      const uint32_t super_tiles_per_row =
742
0
          VP8LSubSampleSize(width, min_bits + subsampling_index);
743
0
      GetBestPredictorForTile(all_argb, subsampling_index, super_tile_x,
744
0
                              super_tile_y, super_tiles_per_row,
745
0
                              all_accumulated_argb, all_modes, all_pred_histos,
746
0
                              min_mode, diff_mask);
747
0
      if (subsampling_index == max_subsampling_index) break;
748
749
      // Update the following super-tile histogram if it has not been updated
750
      // yet.
751
0
      ++subsampling_index;
752
0
      if (subsampling_index > update_up_to_index &&
753
0
          subsampling_index <= max_subsampling_index) {
754
0
        for (mode = min_mode; mode < kNumPredModes; ++mode) {
755
0
          const uint32_t* const src =
756
0
              GetHistoArgbConst(all_argb, subsampling_index - 1, mode);
757
0
          uint32_t* const dst = GetHistoArgb(all_argb, subsampling_index, mode);
758
0
          for (plane = 0; plane < 4; ++plane) {
759
0
            if ((diff_mask >> plane) & 1) {
760
0
              VP8LAddVectorEq(&src[plane * 256], &dst[plane * 256], 256);
761
0
            }
762
0
          }
763
0
        }
764
0
      }
765
      // Check whether the super-tile is not complete (if the smallest tile
766
      // is not at the end of a line/column or at the beginning of a super-tile
767
      // of size (1 << subsampling_index)).
768
0
      if (!((tile_x == (tiles_per_row - 1) ||
769
0
             (local_tile_x + 1) % (1 << subsampling_index) == 0) &&
770
0
            (tile_y == (tiles_per_col - 1) ||
771
0
             (local_tile_y + 1) % (1 << subsampling_index) == 0))) {
772
0
        --subsampling_index;
773
        // subsampling_index now is the index of the last finished super-tile.
774
0
        break;
775
0
      }
776
0
    }
777
    // Reset all the histograms belonging to finished tiles.
778
0
    if (diff_mask == 0xf) {
779
      // If all planes are used, we can just zero the whole buffer.
780
0
      memset(all_argb, 0,
781
0
             HISTO_SIZE * kNumPredModes * (subsampling_index + 1) *
782
0
                 sizeof(*all_argb));
783
0
    } else {
784
0
      for (s = 0; s <= subsampling_index; ++s) {
785
0
        for (mode = min_mode; mode < kNumPredModes; ++mode) {
786
0
          uint32_t* const histo = GetHistoArgb(all_argb, s, mode);
787
0
          for (plane = 0; plane < 4; ++plane) {
788
0
            if ((diff_mask >> plane) & 1) {
789
0
              memset(&histo[plane * 256], 0, 256 * sizeof(*histo));
790
0
            }
791
0
          }
792
0
        }
793
0
      }
794
0
    }
795
796
0
    if (subsampling_index == max_subsampling_index) {
797
      // If a new max-tile is started.
798
0
      if (tile_x == (tiles_per_row - 1)) {
799
0
        max_tile_x = 0;
800
0
        ++max_tile_y;
801
0
      } else {
802
0
        ++max_tile_x;
803
0
      }
804
0
      local_tile_x = 0;
805
0
      local_tile_y = 0;
806
0
    } else {
807
      // Proceed with the Z traversal.
808
0
      uint32_t coord_x = local_tile_x >> subsampling_index;
809
0
      uint32_t coord_y = local_tile_y >> subsampling_index;
810
0
      if (tile_x == (tiles_per_row - 1) && coord_x % 2 == 0) {
811
0
        ++coord_y;
812
0
      } else {
813
0
        if (coord_x % 2 == 0) {
814
0
          ++coord_x;
815
0
        } else {
816
          // Z traversal.
817
0
          ++coord_y;
818
0
          --coord_x;
819
0
        }
820
0
      }
821
0
      local_tile_x = coord_x << subsampling_index;
822
0
      local_tile_y = coord_y << subsampling_index;
823
0
    }
824
0
    tile_x = max_tile_x * max_tile_size + local_tile_x;
825
0
    tile_y = max_tile_y * max_tile_size + local_tile_y;
826
827
0
    if (tile_x == 0 &&
828
0
        !WebPReportProgress(
829
0
            pic, percent_start + percent_range * tile_y / tiles_per_col,
830
0
            percent)) {
831
0
      WebPSafeFree(raw_data);
832
0
      return;
833
0
    }
834
0
  }
835
836
  // Figure out the best sampling.
837
0
  best_cost = WEBP_INT64_MAX;
838
0
  for (subsampling_index = 0; subsampling_index <= max_subsampling_index;
839
0
       ++subsampling_index) {
840
0
    int plane;
841
0
    const uint32_t* const accumulated =
842
0
        GetAccumulatedHisto(all_accumulated_argb, subsampling_index);
843
0
    int64_t cost = VP8LShannonEntropy(
844
0
        &all_pred_histos[subsampling_index * kNumPredModes], kNumPredModes);
845
0
    for (plane = 0; plane < 4; ++plane) {
846
0
      if ((diff_mask >> plane) & 1) {
847
0
        cost += VP8LShannonEntropy(&accumulated[plane * 256], 256);
848
0
      }
849
0
    }
850
0
    if (cost < best_cost) {
851
0
      best_cost = cost;
852
0
      *best_bits = min_bits + subsampling_index;
853
0
      *best_mode = all_modes[subsampling_index];
854
0
    }
855
0
  }
856
857
0
  WebPSafeFree(raw_data);
858
859
0
  VP8LOptimizeSampling(*best_mode, width, height, *best_bits,
860
0
                       MAX_TRANSFORM_BITS, best_bits);
861
0
}
862
863
// Finds the best predictor for each tile, and converts the image to residuals
864
// with respect to predictions. If near_lossless_quality < 100, applies
865
// near lossless processing, shaving off more bits of residuals for lower
866
// qualities.
867
int VP8LResidualImage(int width, int height, int min_bits, int max_bits,
868
                      int low_effort, uint32_t* const argb,
869
                      uint32_t* const argb_scratch, uint32_t* const image,
870
                      int near_lossless_quality, int exact,
871
                      int used_subtract_green, const WebPPicture* const pic,
872
                      int percent_range, int* const percent,
873
0
                      int* const best_bits) {
874
0
  int percent_start = *percent;
875
0
  const int max_quantization = 1 << VP8LNearLosslessBits(near_lossless_quality);
876
0
  if (low_effort) {
877
0
    const int tiles_per_row = VP8LSubSampleSize(width, max_bits);
878
0
    const int tiles_per_col = VP8LSubSampleSize(height, max_bits);
879
0
    int i;
880
0
    for (i = 0; i < tiles_per_row * tiles_per_col; ++i) {
881
0
      image[i] = ARGB_BLACK | (kPredLowEffort << 8);
882
0
    }
883
0
    *best_bits = max_bits;
884
0
  } else {
885
    // Allocate data to try all samplings from min_bits to max_bits.
886
0
    int bits, min_mode;
887
0
    uint32_t sum_num_pixels = 0u;
888
0
    uint32_t *modes_raw, *best_mode;
889
0
    uint32_t* modes[MAX_TRANSFORM_BITS + 1];
890
0
    uint32_t num_pixels[MAX_TRANSFORM_BITS + 1];
891
0
    const uint32_t diff_mask = GetPlaneDiffMask(
892
0
        argb, width, height, max_quantization, exact, &min_mode);
893
0
    for (bits = min_bits; bits <= max_bits; ++bits) {
894
0
      const int tiles_per_row = VP8LSubSampleSize(width, bits);
895
0
      const int tiles_per_col = VP8LSubSampleSize(height, bits);
896
0
      num_pixels[bits] = tiles_per_row * tiles_per_col;
897
0
      sum_num_pixels += num_pixels[bits];
898
0
    }
899
0
    modes_raw = (uint32_t*)WebPSafeMalloc(sum_num_pixels, sizeof(*modes_raw));
900
0
    if (modes_raw == NULL) {
901
0
      return WebPEncodingSetError(pic, VP8_ENC_ERROR_OUT_OF_MEMORY);
902
0
    }
903
    // Have modes point to the right global memory modes_raw.
904
0
    modes[min_bits] = modes_raw;
905
0
    for (bits = min_bits + 1; bits <= max_bits; ++bits) {
906
0
      modes[bits] = modes[bits - 1] + num_pixels[bits - 1];
907
0
    }
908
    // Find the best sampling.
909
0
    GetBestPredictorsAndSubSampling(
910
0
        width, height, min_bits, max_bits, argb_scratch, argb, max_quantization,
911
0
        exact, used_subtract_green, min_mode, diff_mask, pic, percent_range,
912
0
        percent, &modes[min_bits], best_bits, &best_mode);
913
0
    if (*best_bits == 0) {
914
0
      WebPSafeFree(modes_raw);
915
0
      return 0;
916
0
    }
917
    // Keep the best predictor image.
918
0
    memcpy(image, best_mode,
919
0
           VP8LSubSampleSize(width, *best_bits) *
920
0
               VP8LSubSampleSize(height, *best_bits) * sizeof(*image));
921
0
    WebPSafeFree(modes_raw);
922
0
  }
923
924
0
  CopyImageWithPrediction(width, height, *best_bits, image, argb_scratch, argb,
925
0
                          low_effort, max_quantization, exact,
926
0
                          used_subtract_green);
927
0
  return WebPReportProgress(pic, percent_start + percent_range, percent);
928
0
}
929
930
//------------------------------------------------------------------------------
931
// Color transform functions.
932
933
0
static WEBP_INLINE void MultipliersClear(VP8LMultipliers* const m) {
934
0
  m->green_to_red = 0;
935
0
  m->green_to_blue = 0;
936
0
  m->red_to_blue = 0;
937
0
}
938
939
static WEBP_INLINE void ColorCodeToMultipliers(uint32_t color_code,
940
0
                                               VP8LMultipliers* const m) {
941
0
  m->green_to_red = (color_code >> 0) & 0xff;
942
0
  m->green_to_blue = (color_code >> 8) & 0xff;
943
0
  m->red_to_blue = (color_code >> 16) & 0xff;
944
0
}
945
946
static WEBP_INLINE uint32_t
947
0
MultipliersToColorCode(const VP8LMultipliers* const m) {
948
0
  return 0xff000000u | ((uint32_t)(m->red_to_blue) << 16) |
949
0
         ((uint32_t)(m->green_to_blue) << 8) | m->green_to_red;
950
0
}
951
952
static int64_t PredictionCostCrossColor(const uint32_t accumulated[256],
953
0
                                        const uint32_t counts[256]) {
954
  // Favor low entropy, locally and globally.
955
  // Favor small absolute values for PredictionCostSpatial
956
0
  static const uint64_t kExpValue = 240;
957
0
  return (int64_t)VP8LCombinedShannonEntropy(counts, accumulated) +
958
0
         PredictionCostBias(counts, 3, kExpValue);
959
0
}
960
961
static int64_t GetPredictionCostCrossColorRed(
962
    const uint32_t* argb, int stride, int tile_width, int tile_height,
963
    VP8LMultipliers prev_x, VP8LMultipliers prev_y, int green_to_red,
964
0
    const uint32_t accumulated_red_histo[256]) {
965
0
  uint32_t histo[256] = {0};
966
0
  int64_t cur_diff;
967
968
0
  VP8LCollectColorRedTransforms(argb, stride, tile_width, tile_height,
969
0
                                green_to_red, histo);
970
971
0
  cur_diff = PredictionCostCrossColor(accumulated_red_histo, histo);
972
0
  if ((uint8_t)green_to_red == prev_x.green_to_red) {
973
    // favor keeping the areas locally similar
974
0
    cur_diff -= 3ll << LOG_2_PRECISION_BITS;
975
0
  }
976
0
  if ((uint8_t)green_to_red == prev_y.green_to_red) {
977
    // favor keeping the areas locally similar
978
0
    cur_diff -= 3ll << LOG_2_PRECISION_BITS;
979
0
  }
980
0
  if (green_to_red == 0) {
981
0
    cur_diff -= 3ll << LOG_2_PRECISION_BITS;
982
0
  }
983
0
  return cur_diff;
984
0
}
985
986
static void GetBestGreenToRed(const uint32_t* argb, int stride, int tile_width,
987
                              int tile_height, VP8LMultipliers prev_x,
988
                              VP8LMultipliers prev_y, int quality,
989
                              const uint32_t accumulated_red_histo[256],
990
0
                              VP8LMultipliers* const best_tx) {
991
0
  const int kMaxIters = 4 + ((7 * quality) >> 8);  // in range [4..6]
992
0
  int green_to_red_best = 0;
993
0
  int iter, offset;
994
0
  int64_t best_diff = GetPredictionCostCrossColorRed(
995
0
      argb, stride, tile_width, tile_height, prev_x, prev_y, green_to_red_best,
996
0
      accumulated_red_histo);
997
0
  for (iter = 0; iter < kMaxIters; ++iter) {
998
    // ColorTransformDelta is a 3.5 bit fixed point, so 32 is equal to
999
    // one in color computation. Having initial delta here as 1 is sufficient
1000
    // to explore the range of (-2, 2).
1001
0
    const int delta = 32 >> iter;
1002
    // Try a negative and a positive delta from the best known value.
1003
0
    for (offset = -delta; offset <= delta; offset += 2 * delta) {
1004
0
      const int green_to_red_cur = offset + green_to_red_best;
1005
0
      const int64_t cur_diff = GetPredictionCostCrossColorRed(
1006
0
          argb, stride, tile_width, tile_height, prev_x, prev_y,
1007
0
          green_to_red_cur, accumulated_red_histo);
1008
0
      if (cur_diff < best_diff) {
1009
0
        best_diff = cur_diff;
1010
0
        green_to_red_best = green_to_red_cur;
1011
0
      }
1012
0
    }
1013
0
  }
1014
0
  best_tx->green_to_red = (green_to_red_best & 0xff);
1015
0
}
1016
1017
static int64_t GetPredictionCostCrossColorBlue(
1018
    const uint32_t* argb, int stride, int tile_width, int tile_height,
1019
    VP8LMultipliers prev_x, VP8LMultipliers prev_y, int green_to_blue,
1020
0
    int red_to_blue, const uint32_t accumulated_blue_histo[256]) {
1021
0
  uint32_t histo[256] = {0};
1022
0
  int64_t cur_diff;
1023
1024
0
  VP8LCollectColorBlueTransforms(argb, stride, tile_width, tile_height,
1025
0
                                 green_to_blue, red_to_blue, histo);
1026
1027
0
  cur_diff = PredictionCostCrossColor(accumulated_blue_histo, histo);
1028
0
  if ((uint8_t)green_to_blue == prev_x.green_to_blue) {
1029
    // favor keeping the areas locally similar
1030
0
    cur_diff -= 3ll << LOG_2_PRECISION_BITS;
1031
0
  }
1032
0
  if ((uint8_t)green_to_blue == prev_y.green_to_blue) {
1033
    // favor keeping the areas locally similar
1034
0
    cur_diff -= 3ll << LOG_2_PRECISION_BITS;
1035
0
  }
1036
0
  if ((uint8_t)red_to_blue == prev_x.red_to_blue) {
1037
    // favor keeping the areas locally similar
1038
0
    cur_diff -= 3ll << LOG_2_PRECISION_BITS;
1039
0
  }
1040
0
  if ((uint8_t)red_to_blue == prev_y.red_to_blue) {
1041
    // favor keeping the areas locally similar
1042
0
    cur_diff -= 3ll << LOG_2_PRECISION_BITS;
1043
0
  }
1044
0
  if (green_to_blue == 0) {
1045
0
    cur_diff -= 3ll << LOG_2_PRECISION_BITS;
1046
0
  }
1047
0
  if (red_to_blue == 0) {
1048
0
    cur_diff -= 3ll << LOG_2_PRECISION_BITS;
1049
0
  }
1050
0
  return cur_diff;
1051
0
}
1052
1053
0
#define kGreenRedToBlueNumAxis 8
1054
0
#define kGreenRedToBlueMaxIters 7
1055
static void GetBestGreenRedToBlue(const uint32_t* argb, int stride,
1056
                                  int tile_width, int tile_height,
1057
                                  VP8LMultipliers prev_x,
1058
                                  VP8LMultipliers prev_y, int quality,
1059
                                  const uint32_t accumulated_blue_histo[256],
1060
0
                                  VP8LMultipliers* const best_tx) {
1061
0
  const int8_t offset[kGreenRedToBlueNumAxis][2] = {
1062
0
      {0, -1}, {0, 1}, {-1, 0}, {1, 0}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}};
1063
  // Must stay positive and non-increasing: skip_delta below assumes a value
1064
  // never recurs once a smaller one has been tried, and uses -1 as "none".
1065
0
  const int8_t delta_lut[kGreenRedToBlueMaxIters] = {16, 16, 8, 4, 2, 2, 2};
1066
  // Only axis aligned diffs for lower quality.
1067
0
  const int iters = (quality < 25)   ? 1
1068
0
                    : (quality > 50) ? kGreenRedToBlueMaxIters
1069
0
                                     : 4;
1070
0
  int green_to_blue_best = 0;
1071
0
  int red_to_blue_best = 0;
1072
0
  int iter;
1073
  // The delta that just found nothing, if any: repeating it would re-probe
1074
  // the same eight points around the same centre for the same result.
1075
0
  int skip_delta = -1;
1076
  // Initial value at origin:
1077
0
  int64_t best_diff = GetPredictionCostCrossColorBlue(
1078
0
      argb, stride, tile_width, tile_height, prev_x, prev_y, green_to_blue_best,
1079
0
      red_to_blue_best, accumulated_blue_histo);
1080
0
  for (iter = 0; iter < iters; ++iter) {
1081
0
    const int delta = delta_lut[iter];
1082
0
    int axis;
1083
0
    if (delta == skip_delta) continue;
1084
0
    skip_delta = delta;
1085
0
    for (axis = 0; axis < kGreenRedToBlueNumAxis; ++axis) {
1086
0
      const int green_to_blue_cur =
1087
0
          offset[axis][0] * delta + green_to_blue_best;
1088
0
      const int red_to_blue_cur = offset[axis][1] * delta + red_to_blue_best;
1089
0
      const int64_t cur_diff = GetPredictionCostCrossColorBlue(
1090
0
          argb, stride, tile_width, tile_height, prev_x, prev_y,
1091
0
          green_to_blue_cur, red_to_blue_cur, accumulated_blue_histo);
1092
0
      if (cur_diff < best_diff) {
1093
0
        best_diff = cur_diff;
1094
0
        green_to_blue_best = green_to_blue_cur;
1095
0
        red_to_blue_best = red_to_blue_cur;
1096
0
        skip_delta = -1;
1097
0
      }
1098
0
    }
1099
0
    if (delta == 2 && green_to_blue_best == 0 && red_to_blue_best == 0) {
1100
      // Further iterations would not help.
1101
0
      break;  // out of iter-loop.
1102
0
    }
1103
0
  }
1104
0
  best_tx->green_to_blue = green_to_blue_best & 0xff;
1105
0
  best_tx->red_to_blue = red_to_blue_best & 0xff;
1106
0
}
1107
#undef kGreenRedToBlueMaxIters
1108
#undef kGreenRedToBlueNumAxis
1109
1110
static VP8LMultipliers GetBestColorTransformForTile(
1111
    int tile_x, int tile_y, int bits, VP8LMultipliers prev_x,
1112
    VP8LMultipliers prev_y, int quality, int xsize, int ysize,
1113
    const uint32_t accumulated_red_histo[256],
1114
0
    const uint32_t accumulated_blue_histo[256], const uint32_t* const argb) {
1115
0
  const int max_tile_size = 1 << bits;
1116
0
  const int tile_y_offset = tile_y * max_tile_size;
1117
0
  const int tile_x_offset = tile_x * max_tile_size;
1118
0
  const int all_x_max = GetMin(tile_x_offset + max_tile_size, xsize);
1119
0
  const int all_y_max = GetMin(tile_y_offset + max_tile_size, ysize);
1120
0
  const int tile_width = all_x_max - tile_x_offset;
1121
0
  const int tile_height = all_y_max - tile_y_offset;
1122
0
  const uint32_t* const tile_argb =
1123
0
      argb + tile_y_offset * xsize + tile_x_offset;
1124
0
  VP8LMultipliers best_tx;
1125
0
  MultipliersClear(&best_tx);
1126
1127
0
  GetBestGreenToRed(tile_argb, xsize, tile_width, tile_height, prev_x, prev_y,
1128
0
                    quality, accumulated_red_histo, &best_tx);
1129
0
  GetBestGreenRedToBlue(tile_argb, xsize, tile_width, tile_height, prev_x,
1130
0
                        prev_y, quality, accumulated_blue_histo, &best_tx);
1131
0
  return best_tx;
1132
0
}
1133
1134
static void CopyTileWithColorTransform(int xsize, int ysize, int tile_x,
1135
                                       int tile_y, int max_tile_size,
1136
                                       VP8LMultipliers color_transform,
1137
0
                                       uint32_t* argb) {
1138
0
  const int xscan = GetMin(max_tile_size, xsize - tile_x);
1139
0
  int yscan = GetMin(max_tile_size, ysize - tile_y);
1140
0
  argb += tile_y * xsize + tile_x;
1141
0
  while (yscan-- > 0) {
1142
0
    VP8LTransformColor(&color_transform, argb, xscan);
1143
0
    argb += xsize;
1144
0
  }
1145
0
}
1146
1147
int VP8LColorSpaceTransform(int width, int height, int bits, int quality,
1148
                            uint32_t* const argb, uint32_t* image,
1149
                            const WebPPicture* const pic, int percent_range,
1150
0
                            int* const percent, int* const best_bits) {
1151
0
  const int max_tile_size = 1 << bits;
1152
0
  const int tile_xsize = VP8LSubSampleSize(width, bits);
1153
0
  const int tile_ysize = VP8LSubSampleSize(height, bits);
1154
0
  int percent_start = *percent;
1155
0
  uint32_t accumulated_red_histo[256] = {0};
1156
0
  uint32_t accumulated_blue_histo[256] = {0};
1157
0
  int tile_x, tile_y;
1158
0
  VP8LMultipliers prev_x, prev_y;
1159
0
  MultipliersClear(&prev_y);
1160
0
  MultipliersClear(&prev_x);
1161
0
  for (tile_y = 0; tile_y < tile_ysize; ++tile_y) {
1162
0
    for (tile_x = 0; tile_x < tile_xsize; ++tile_x) {
1163
0
      int y;
1164
0
      const int tile_x_offset = tile_x * max_tile_size;
1165
0
      const int tile_y_offset = tile_y * max_tile_size;
1166
0
      const int all_x_max = GetMin(tile_x_offset + max_tile_size, width);
1167
0
      const int all_y_max = GetMin(tile_y_offset + max_tile_size, height);
1168
0
      const int offset = tile_y * tile_xsize + tile_x;
1169
0
      if (tile_y != 0) {
1170
0
        ColorCodeToMultipliers(image[offset - tile_xsize], &prev_y);
1171
0
      }
1172
0
      prev_x = GetBestColorTransformForTile(
1173
0
          tile_x, tile_y, bits, prev_x, prev_y, quality, width, height,
1174
0
          accumulated_red_histo, accumulated_blue_histo, argb);
1175
0
      image[offset] = MultipliersToColorCode(&prev_x);
1176
0
      CopyTileWithColorTransform(width, height, tile_x_offset, tile_y_offset,
1177
0
                                 max_tile_size, prev_x, argb);
1178
1179
      // Gather accumulated histogram data.
1180
0
      for (y = tile_y_offset; y < all_y_max; ++y) {
1181
0
        int ix = y * width + tile_x_offset;
1182
0
        const int ix_end = ix + all_x_max - tile_x_offset;
1183
0
        for (; ix < ix_end; ++ix) {
1184
0
          const uint32_t pix = argb[ix];
1185
0
          if (ix >= 2 && pix == argb[ix - 2] && pix == argb[ix - 1]) {
1186
0
            continue;  // repeated pixels are handled by backward references
1187
0
          }
1188
0
          if (ix >= width + 2 && argb[ix - 2] == argb[ix - width - 2] &&
1189
0
              argb[ix - 1] == argb[ix - width - 1] && pix == argb[ix - width]) {
1190
0
            continue;  // repeated pixels are handled by backward references
1191
0
          }
1192
0
          ++accumulated_red_histo[(pix >> 16) & 0xff];
1193
0
          ++accumulated_blue_histo[(pix >> 0) & 0xff];
1194
0
        }
1195
0
      }
1196
0
    }
1197
0
    if (!WebPReportProgress(pic,
1198
0
                            percent_start + percent_range * tile_y / tile_ysize,
1199
0
                            percent)) {
1200
0
      return 0;
1201
0
    }
1202
0
  }
1203
0
  VP8LOptimizeSampling(image, width, height, bits, MAX_TRANSFORM_BITS,
1204
0
                       best_bits);
1205
0
  return 1;
1206
0
}