predictor_enc.c 31 KB

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