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