Coverage Report

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