vp8l_enc.c 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668
  1. // Copyright 2012 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. // main entry for the lossless encoder.
  11. //
  12. // Author: Vikas Arora (vikaas.arora@gmail.com)
  13. //
  14. #include <assert.h>
  15. #include <stdlib.h>
  16. #include "./backward_references_enc.h"
  17. #include "./histogram_enc.h"
  18. #include "./vp8i_enc.h"
  19. #include "./vp8li_enc.h"
  20. #include "../dsp/lossless.h"
  21. #include "../dsp/lossless_common.h"
  22. #include "../utils/bit_writer_utils.h"
  23. #include "../utils/huffman_encode_utils.h"
  24. #include "../utils/utils.h"
  25. #include "../webp/format_constants.h"
  26. #include "./delta_palettization_enc.h"
  27. #define PALETTE_KEY_RIGHT_SHIFT 22 // Key for 1K buffer.
  28. // Maximum number of histogram images (sub-blocks).
  29. #define MAX_HUFF_IMAGE_SIZE 2600
  30. // Palette reordering for smaller sum of deltas (and for smaller storage).
  31. static int PaletteCompareColorsForQsort(const void* p1, const void* p2) {
  32. const uint32_t a = WebPMemToUint32((uint8_t*)p1);
  33. const uint32_t b = WebPMemToUint32((uint8_t*)p2);
  34. assert(a != b);
  35. return (a < b) ? -1 : 1;
  36. }
  37. static WEBP_INLINE uint32_t PaletteComponentDistance(uint32_t v) {
  38. return (v <= 128) ? v : (256 - v);
  39. }
  40. // Computes a value that is related to the entropy created by the
  41. // palette entry diff.
  42. //
  43. // Note that the last & 0xff is a no-operation in the next statement, but
  44. // removed by most compilers and is here only for regularity of the code.
  45. static WEBP_INLINE uint32_t PaletteColorDistance(uint32_t col1, uint32_t col2) {
  46. const uint32_t diff = VP8LSubPixels(col1, col2);
  47. const int kMoreWeightForRGBThanForAlpha = 9;
  48. uint32_t score;
  49. score = PaletteComponentDistance((diff >> 0) & 0xff);
  50. score += PaletteComponentDistance((diff >> 8) & 0xff);
  51. score += PaletteComponentDistance((diff >> 16) & 0xff);
  52. score *= kMoreWeightForRGBThanForAlpha;
  53. score += PaletteComponentDistance((diff >> 24) & 0xff);
  54. return score;
  55. }
  56. static WEBP_INLINE void SwapColor(uint32_t* const col1, uint32_t* const col2) {
  57. const uint32_t tmp = *col1;
  58. *col1 = *col2;
  59. *col2 = tmp;
  60. }
  61. static void GreedyMinimizeDeltas(uint32_t palette[], int num_colors) {
  62. // Find greedily always the closest color of the predicted color to minimize
  63. // deltas in the palette. This reduces storage needs since the
  64. // palette is stored with delta encoding.
  65. uint32_t predict = 0x00000000;
  66. int i, k;
  67. for (i = 0; i < num_colors; ++i) {
  68. int best_ix = i;
  69. uint32_t best_score = ~0U;
  70. for (k = i; k < num_colors; ++k) {
  71. const uint32_t cur_score = PaletteColorDistance(palette[k], predict);
  72. if (best_score > cur_score) {
  73. best_score = cur_score;
  74. best_ix = k;
  75. }
  76. }
  77. SwapColor(&palette[best_ix], &palette[i]);
  78. predict = palette[i];
  79. }
  80. }
  81. // The palette has been sorted by alpha. This function checks if the other
  82. // components of the palette have a monotonic development with regards to
  83. // position in the palette. If all have monotonic development, there is
  84. // no benefit to re-organize them greedily. A monotonic development
  85. // would be spotted in green-only situations (like lossy alpha) or gray-scale
  86. // images.
  87. static int PaletteHasNonMonotonousDeltas(uint32_t palette[], int num_colors) {
  88. uint32_t predict = 0x000000;
  89. int i;
  90. uint8_t sign_found = 0x00;
  91. for (i = 0; i < num_colors; ++i) {
  92. const uint32_t diff = VP8LSubPixels(palette[i], predict);
  93. const uint8_t rd = (diff >> 16) & 0xff;
  94. const uint8_t gd = (diff >> 8) & 0xff;
  95. const uint8_t bd = (diff >> 0) & 0xff;
  96. if (rd != 0x00) {
  97. sign_found |= (rd < 0x80) ? 1 : 2;
  98. }
  99. if (gd != 0x00) {
  100. sign_found |= (gd < 0x80) ? 8 : 16;
  101. }
  102. if (bd != 0x00) {
  103. sign_found |= (bd < 0x80) ? 64 : 128;
  104. }
  105. predict = palette[i];
  106. }
  107. return (sign_found & (sign_found << 1)) != 0; // two consequent signs.
  108. }
  109. // -----------------------------------------------------------------------------
  110. // Palette
  111. // If number of colors in the image is less than or equal to MAX_PALETTE_SIZE,
  112. // creates a palette and returns true, else returns false.
  113. static int AnalyzeAndCreatePalette(const WebPPicture* const pic,
  114. int low_effort,
  115. uint32_t palette[MAX_PALETTE_SIZE],
  116. int* const palette_size) {
  117. const int num_colors = WebPGetColorPalette(pic, palette);
  118. if (num_colors > MAX_PALETTE_SIZE) return 0;
  119. *palette_size = num_colors;
  120. qsort(palette, num_colors, sizeof(*palette), PaletteCompareColorsForQsort);
  121. if (!low_effort && PaletteHasNonMonotonousDeltas(palette, num_colors)) {
  122. GreedyMinimizeDeltas(palette, num_colors);
  123. }
  124. return 1;
  125. }
  126. // These five modes are evaluated and their respective entropy is computed.
  127. typedef enum {
  128. kDirect = 0,
  129. kSpatial = 1,
  130. kSubGreen = 2,
  131. kSpatialSubGreen = 3,
  132. kPalette = 4,
  133. kNumEntropyIx = 5
  134. } EntropyIx;
  135. typedef enum {
  136. kHistoAlpha = 0,
  137. kHistoAlphaPred,
  138. kHistoGreen,
  139. kHistoGreenPred,
  140. kHistoRed,
  141. kHistoRedPred,
  142. kHistoBlue,
  143. kHistoBluePred,
  144. kHistoRedSubGreen,
  145. kHistoRedPredSubGreen,
  146. kHistoBlueSubGreen,
  147. kHistoBluePredSubGreen,
  148. kHistoPalette,
  149. kHistoTotal // Must be last.
  150. } HistoIx;
  151. static void AddSingleSubGreen(int p, uint32_t* const r, uint32_t* const b) {
  152. const int green = p >> 8; // The upper bits are masked away later.
  153. ++r[((p >> 16) - green) & 0xff];
  154. ++b[((p >> 0) - green) & 0xff];
  155. }
  156. static void AddSingle(uint32_t p,
  157. uint32_t* const a, uint32_t* const r,
  158. uint32_t* const g, uint32_t* const b) {
  159. ++a[(p >> 24) & 0xff];
  160. ++r[(p >> 16) & 0xff];
  161. ++g[(p >> 8) & 0xff];
  162. ++b[(p >> 0) & 0xff];
  163. }
  164. static WEBP_INLINE uint32_t HashPix(uint32_t pix) {
  165. // Note that masking with 0xffffffffu is for preventing an
  166. // 'unsigned int overflow' warning. Doesn't impact the compiled code.
  167. return ((((uint64_t)pix + (pix >> 19)) * 0x39c5fba7ull) & 0xffffffffu) >> 24;
  168. }
  169. static int AnalyzeEntropy(const uint32_t* argb,
  170. int width, int height, int argb_stride,
  171. int use_palette,
  172. EntropyIx* const min_entropy_ix,
  173. int* const red_and_blue_always_zero) {
  174. // Allocate histogram set with cache_bits = 0.
  175. uint32_t* const histo =
  176. (uint32_t*)WebPSafeCalloc(kHistoTotal, sizeof(*histo) * 256);
  177. if (histo != NULL) {
  178. int i, x, y;
  179. const uint32_t* prev_row = argb;
  180. const uint32_t* curr_row = argb + argb_stride;
  181. for (y = 1; y < height; ++y) {
  182. uint32_t prev_pix = curr_row[0];
  183. for (x = 1; x < width; ++x) {
  184. const uint32_t pix = curr_row[x];
  185. const uint32_t pix_diff = VP8LSubPixels(pix, prev_pix);
  186. if ((pix_diff == 0) || (pix == prev_row[x])) continue;
  187. prev_pix = pix;
  188. AddSingle(pix,
  189. &histo[kHistoAlpha * 256],
  190. &histo[kHistoRed * 256],
  191. &histo[kHistoGreen * 256],
  192. &histo[kHistoBlue * 256]);
  193. AddSingle(pix_diff,
  194. &histo[kHistoAlphaPred * 256],
  195. &histo[kHistoRedPred * 256],
  196. &histo[kHistoGreenPred * 256],
  197. &histo[kHistoBluePred * 256]);
  198. AddSingleSubGreen(pix,
  199. &histo[kHistoRedSubGreen * 256],
  200. &histo[kHistoBlueSubGreen * 256]);
  201. AddSingleSubGreen(pix_diff,
  202. &histo[kHistoRedPredSubGreen * 256],
  203. &histo[kHistoBluePredSubGreen * 256]);
  204. {
  205. // Approximate the palette by the entropy of the multiplicative hash.
  206. const uint32_t hash = HashPix(pix);
  207. ++histo[kHistoPalette * 256 + hash];
  208. }
  209. }
  210. prev_row = curr_row;
  211. curr_row += argb_stride;
  212. }
  213. {
  214. double entropy_comp[kHistoTotal];
  215. double entropy[kNumEntropyIx];
  216. int k;
  217. int last_mode_to_analyze = use_palette ? kPalette : kSpatialSubGreen;
  218. int j;
  219. // Let's add one zero to the predicted histograms. The zeros are removed
  220. // too efficiently by the pix_diff == 0 comparison, at least one of the
  221. // zeros is likely to exist.
  222. ++histo[kHistoRedPredSubGreen * 256];
  223. ++histo[kHistoBluePredSubGreen * 256];
  224. ++histo[kHistoRedPred * 256];
  225. ++histo[kHistoGreenPred * 256];
  226. ++histo[kHistoBluePred * 256];
  227. ++histo[kHistoAlphaPred * 256];
  228. for (j = 0; j < kHistoTotal; ++j) {
  229. entropy_comp[j] = VP8LBitsEntropy(&histo[j * 256], 256, NULL);
  230. }
  231. entropy[kDirect] = entropy_comp[kHistoAlpha] +
  232. entropy_comp[kHistoRed] +
  233. entropy_comp[kHistoGreen] +
  234. entropy_comp[kHistoBlue];
  235. entropy[kSpatial] = entropy_comp[kHistoAlphaPred] +
  236. entropy_comp[kHistoRedPred] +
  237. entropy_comp[kHistoGreenPred] +
  238. entropy_comp[kHistoBluePred];
  239. entropy[kSubGreen] = entropy_comp[kHistoAlpha] +
  240. entropy_comp[kHistoRedSubGreen] +
  241. entropy_comp[kHistoGreen] +
  242. entropy_comp[kHistoBlueSubGreen];
  243. entropy[kSpatialSubGreen] = entropy_comp[kHistoAlphaPred] +
  244. entropy_comp[kHistoRedPredSubGreen] +
  245. entropy_comp[kHistoGreenPred] +
  246. entropy_comp[kHistoBluePredSubGreen];
  247. // Palette mode seems more efficient in a breakeven case. Bias with 1.0.
  248. entropy[kPalette] = entropy_comp[kHistoPalette] - 1.0;
  249. *min_entropy_ix = kDirect;
  250. for (k = kDirect + 1; k <= last_mode_to_analyze; ++k) {
  251. if (entropy[*min_entropy_ix] > entropy[k]) {
  252. *min_entropy_ix = (EntropyIx)k;
  253. }
  254. }
  255. *red_and_blue_always_zero = 1;
  256. // Let's check if the histogram of the chosen entropy mode has
  257. // non-zero red and blue values. If all are zero, we can later skip
  258. // the cross color optimization.
  259. {
  260. static const uint8_t kHistoPairs[5][2] = {
  261. { kHistoRed, kHistoBlue },
  262. { kHistoRedPred, kHistoBluePred },
  263. { kHistoRedSubGreen, kHistoBlueSubGreen },
  264. { kHistoRedPredSubGreen, kHistoBluePredSubGreen },
  265. { kHistoRed, kHistoBlue }
  266. };
  267. const uint32_t* const red_histo =
  268. &histo[256 * kHistoPairs[*min_entropy_ix][0]];
  269. const uint32_t* const blue_histo =
  270. &histo[256 * kHistoPairs[*min_entropy_ix][1]];
  271. for (i = 1; i < 256; ++i) {
  272. if ((red_histo[i] | blue_histo[i]) != 0) {
  273. *red_and_blue_always_zero = 0;
  274. break;
  275. }
  276. }
  277. }
  278. }
  279. WebPSafeFree(histo);
  280. return 1;
  281. } else {
  282. return 0;
  283. }
  284. }
  285. static int GetHistoBits(int method, int use_palette, int width, int height) {
  286. // Make tile size a function of encoding method (Range: 0 to 6).
  287. int histo_bits = (use_palette ? 9 : 7) - method;
  288. while (1) {
  289. const int huff_image_size = VP8LSubSampleSize(width, histo_bits) *
  290. VP8LSubSampleSize(height, histo_bits);
  291. if (huff_image_size <= MAX_HUFF_IMAGE_SIZE) break;
  292. ++histo_bits;
  293. }
  294. return (histo_bits < MIN_HUFFMAN_BITS) ? MIN_HUFFMAN_BITS :
  295. (histo_bits > MAX_HUFFMAN_BITS) ? MAX_HUFFMAN_BITS : histo_bits;
  296. }
  297. static int GetTransformBits(int method, int histo_bits) {
  298. const int max_transform_bits = (method < 4) ? 6 : (method > 4) ? 4 : 5;
  299. const int res =
  300. (histo_bits > max_transform_bits) ? max_transform_bits : histo_bits;
  301. assert(res <= MAX_TRANSFORM_BITS);
  302. return res;
  303. }
  304. static int AnalyzeAndInit(VP8LEncoder* const enc) {
  305. const WebPPicture* const pic = enc->pic_;
  306. const int width = pic->width;
  307. const int height = pic->height;
  308. const int pix_cnt = width * height;
  309. const WebPConfig* const config = enc->config_;
  310. const int method = config->method;
  311. const int low_effort = (config->method == 0);
  312. // we round the block size up, so we're guaranteed to have
  313. // at max MAX_REFS_BLOCK_PER_IMAGE blocks used:
  314. int refs_block_size = (pix_cnt - 1) / MAX_REFS_BLOCK_PER_IMAGE + 1;
  315. assert(pic != NULL && pic->argb != NULL);
  316. enc->use_cross_color_ = 0;
  317. enc->use_predict_ = 0;
  318. enc->use_subtract_green_ = 0;
  319. enc->use_palette_ =
  320. AnalyzeAndCreatePalette(pic, low_effort,
  321. enc->palette_, &enc->palette_size_);
  322. // TODO(jyrki): replace the decision to be based on an actual estimate
  323. // of entropy, or even spatial variance of entropy.
  324. enc->histo_bits_ = GetHistoBits(method, enc->use_palette_,
  325. pic->width, pic->height);
  326. enc->transform_bits_ = GetTransformBits(method, enc->histo_bits_);
  327. if (low_effort) {
  328. // AnalyzeEntropy is somewhat slow.
  329. enc->use_predict_ = !enc->use_palette_;
  330. enc->use_subtract_green_ = !enc->use_palette_;
  331. enc->use_cross_color_ = 0;
  332. } else {
  333. int red_and_blue_always_zero;
  334. EntropyIx min_entropy_ix;
  335. if (!AnalyzeEntropy(pic->argb, width, height, pic->argb_stride,
  336. enc->use_palette_, &min_entropy_ix,
  337. &red_and_blue_always_zero)) {
  338. return 0;
  339. }
  340. enc->use_palette_ = (min_entropy_ix == kPalette);
  341. enc->use_subtract_green_ =
  342. (min_entropy_ix == kSubGreen) || (min_entropy_ix == kSpatialSubGreen);
  343. enc->use_predict_ =
  344. (min_entropy_ix == kSpatial) || (min_entropy_ix == kSpatialSubGreen);
  345. enc->use_cross_color_ = red_and_blue_always_zero ? 0 : enc->use_predict_;
  346. }
  347. if (!VP8LHashChainInit(&enc->hash_chain_, pix_cnt)) return 0;
  348. // palette-friendly input typically uses less literals
  349. // -> reduce block size a bit
  350. if (enc->use_palette_) refs_block_size /= 2;
  351. VP8LBackwardRefsInit(&enc->refs_[0], refs_block_size);
  352. VP8LBackwardRefsInit(&enc->refs_[1], refs_block_size);
  353. return 1;
  354. }
  355. // Returns false in case of memory error.
  356. static int GetHuffBitLengthsAndCodes(
  357. const VP8LHistogramSet* const histogram_image,
  358. HuffmanTreeCode* const huffman_codes) {
  359. int i, k;
  360. int ok = 0;
  361. uint64_t total_length_size = 0;
  362. uint8_t* mem_buf = NULL;
  363. const int histogram_image_size = histogram_image->size;
  364. int max_num_symbols = 0;
  365. uint8_t* buf_rle = NULL;
  366. HuffmanTree* huff_tree = NULL;
  367. // Iterate over all histograms and get the aggregate number of codes used.
  368. for (i = 0; i < histogram_image_size; ++i) {
  369. const VP8LHistogram* const histo = histogram_image->histograms[i];
  370. HuffmanTreeCode* const codes = &huffman_codes[5 * i];
  371. for (k = 0; k < 5; ++k) {
  372. const int num_symbols =
  373. (k == 0) ? VP8LHistogramNumCodes(histo->palette_code_bits_) :
  374. (k == 4) ? NUM_DISTANCE_CODES : 256;
  375. codes[k].num_symbols = num_symbols;
  376. total_length_size += num_symbols;
  377. }
  378. }
  379. // Allocate and Set Huffman codes.
  380. {
  381. uint16_t* codes;
  382. uint8_t* lengths;
  383. mem_buf = (uint8_t*)WebPSafeCalloc(total_length_size,
  384. sizeof(*lengths) + sizeof(*codes));
  385. if (mem_buf == NULL) goto End;
  386. codes = (uint16_t*)mem_buf;
  387. lengths = (uint8_t*)&codes[total_length_size];
  388. for (i = 0; i < 5 * histogram_image_size; ++i) {
  389. const int bit_length = huffman_codes[i].num_symbols;
  390. huffman_codes[i].codes = codes;
  391. huffman_codes[i].code_lengths = lengths;
  392. codes += bit_length;
  393. lengths += bit_length;
  394. if (max_num_symbols < bit_length) {
  395. max_num_symbols = bit_length;
  396. }
  397. }
  398. }
  399. buf_rle = (uint8_t*)WebPSafeMalloc(1ULL, max_num_symbols);
  400. huff_tree = (HuffmanTree*)WebPSafeMalloc(3ULL * max_num_symbols,
  401. sizeof(*huff_tree));
  402. if (buf_rle == NULL || huff_tree == NULL) goto End;
  403. // Create Huffman trees.
  404. for (i = 0; i < histogram_image_size; ++i) {
  405. HuffmanTreeCode* const codes = &huffman_codes[5 * i];
  406. VP8LHistogram* const histo = histogram_image->histograms[i];
  407. VP8LCreateHuffmanTree(histo->literal_, 15, buf_rle, huff_tree, codes + 0);
  408. VP8LCreateHuffmanTree(histo->red_, 15, buf_rle, huff_tree, codes + 1);
  409. VP8LCreateHuffmanTree(histo->blue_, 15, buf_rle, huff_tree, codes + 2);
  410. VP8LCreateHuffmanTree(histo->alpha_, 15, buf_rle, huff_tree, codes + 3);
  411. VP8LCreateHuffmanTree(histo->distance_, 15, buf_rle, huff_tree, codes + 4);
  412. }
  413. ok = 1;
  414. End:
  415. WebPSafeFree(huff_tree);
  416. WebPSafeFree(buf_rle);
  417. if (!ok) {
  418. WebPSafeFree(mem_buf);
  419. memset(huffman_codes, 0, 5 * histogram_image_size * sizeof(*huffman_codes));
  420. }
  421. return ok;
  422. }
  423. static void StoreHuffmanTreeOfHuffmanTreeToBitMask(
  424. VP8LBitWriter* const bw, const uint8_t* code_length_bitdepth) {
  425. // RFC 1951 will calm you down if you are worried about this funny sequence.
  426. // This sequence is tuned from that, but more weighted for lower symbol count,
  427. // and more spiking histograms.
  428. static const uint8_t kStorageOrder[CODE_LENGTH_CODES] = {
  429. 17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
  430. };
  431. int i;
  432. // Throw away trailing zeros:
  433. int codes_to_store = CODE_LENGTH_CODES;
  434. for (; codes_to_store > 4; --codes_to_store) {
  435. if (code_length_bitdepth[kStorageOrder[codes_to_store - 1]] != 0) {
  436. break;
  437. }
  438. }
  439. VP8LPutBits(bw, codes_to_store - 4, 4);
  440. for (i = 0; i < codes_to_store; ++i) {
  441. VP8LPutBits(bw, code_length_bitdepth[kStorageOrder[i]], 3);
  442. }
  443. }
  444. static void ClearHuffmanTreeIfOnlyOneSymbol(
  445. HuffmanTreeCode* const huffman_code) {
  446. int k;
  447. int count = 0;
  448. for (k = 0; k < huffman_code->num_symbols; ++k) {
  449. if (huffman_code->code_lengths[k] != 0) {
  450. ++count;
  451. if (count > 1) return;
  452. }
  453. }
  454. for (k = 0; k < huffman_code->num_symbols; ++k) {
  455. huffman_code->code_lengths[k] = 0;
  456. huffman_code->codes[k] = 0;
  457. }
  458. }
  459. static void StoreHuffmanTreeToBitMask(
  460. VP8LBitWriter* const bw,
  461. const HuffmanTreeToken* const tokens, const int num_tokens,
  462. const HuffmanTreeCode* const huffman_code) {
  463. int i;
  464. for (i = 0; i < num_tokens; ++i) {
  465. const int ix = tokens[i].code;
  466. const int extra_bits = tokens[i].extra_bits;
  467. VP8LPutBits(bw, huffman_code->codes[ix], huffman_code->code_lengths[ix]);
  468. switch (ix) {
  469. case 16:
  470. VP8LPutBits(bw, extra_bits, 2);
  471. break;
  472. case 17:
  473. VP8LPutBits(bw, extra_bits, 3);
  474. break;
  475. case 18:
  476. VP8LPutBits(bw, extra_bits, 7);
  477. break;
  478. }
  479. }
  480. }
  481. // 'huff_tree' and 'tokens' are pre-alloacted buffers.
  482. static void StoreFullHuffmanCode(VP8LBitWriter* const bw,
  483. HuffmanTree* const huff_tree,
  484. HuffmanTreeToken* const tokens,
  485. const HuffmanTreeCode* const tree) {
  486. uint8_t code_length_bitdepth[CODE_LENGTH_CODES] = { 0 };
  487. uint16_t code_length_bitdepth_symbols[CODE_LENGTH_CODES] = { 0 };
  488. const int max_tokens = tree->num_symbols;
  489. int num_tokens;
  490. HuffmanTreeCode huffman_code;
  491. huffman_code.num_symbols = CODE_LENGTH_CODES;
  492. huffman_code.code_lengths = code_length_bitdepth;
  493. huffman_code.codes = code_length_bitdepth_symbols;
  494. VP8LPutBits(bw, 0, 1);
  495. num_tokens = VP8LCreateCompressedHuffmanTree(tree, tokens, max_tokens);
  496. {
  497. uint32_t histogram[CODE_LENGTH_CODES] = { 0 };
  498. uint8_t buf_rle[CODE_LENGTH_CODES] = { 0 };
  499. int i;
  500. for (i = 0; i < num_tokens; ++i) {
  501. ++histogram[tokens[i].code];
  502. }
  503. VP8LCreateHuffmanTree(histogram, 7, buf_rle, huff_tree, &huffman_code);
  504. }
  505. StoreHuffmanTreeOfHuffmanTreeToBitMask(bw, code_length_bitdepth);
  506. ClearHuffmanTreeIfOnlyOneSymbol(&huffman_code);
  507. {
  508. int trailing_zero_bits = 0;
  509. int trimmed_length = num_tokens;
  510. int write_trimmed_length;
  511. int length;
  512. int i = num_tokens;
  513. while (i-- > 0) {
  514. const int ix = tokens[i].code;
  515. if (ix == 0 || ix == 17 || ix == 18) {
  516. --trimmed_length; // discount trailing zeros
  517. trailing_zero_bits += code_length_bitdepth[ix];
  518. if (ix == 17) {
  519. trailing_zero_bits += 3;
  520. } else if (ix == 18) {
  521. trailing_zero_bits += 7;
  522. }
  523. } else {
  524. break;
  525. }
  526. }
  527. write_trimmed_length = (trimmed_length > 1 && trailing_zero_bits > 12);
  528. length = write_trimmed_length ? trimmed_length : num_tokens;
  529. VP8LPutBits(bw, write_trimmed_length, 1);
  530. if (write_trimmed_length) {
  531. const int nbits = VP8LBitsLog2Ceiling(trimmed_length - 1);
  532. const int nbitpairs = (nbits == 0) ? 1 : (nbits + 1) / 2;
  533. VP8LPutBits(bw, nbitpairs - 1, 3);
  534. assert(trimmed_length >= 2);
  535. VP8LPutBits(bw, trimmed_length - 2, nbitpairs * 2);
  536. }
  537. StoreHuffmanTreeToBitMask(bw, tokens, length, &huffman_code);
  538. }
  539. }
  540. // 'huff_tree' and 'tokens' are pre-alloacted buffers.
  541. static void StoreHuffmanCode(VP8LBitWriter* const bw,
  542. HuffmanTree* const huff_tree,
  543. HuffmanTreeToken* const tokens,
  544. const HuffmanTreeCode* const huffman_code) {
  545. int i;
  546. int count = 0;
  547. int symbols[2] = { 0, 0 };
  548. const int kMaxBits = 8;
  549. const int kMaxSymbol = 1 << kMaxBits;
  550. // Check whether it's a small tree.
  551. for (i = 0; i < huffman_code->num_symbols && count < 3; ++i) {
  552. if (huffman_code->code_lengths[i] != 0) {
  553. if (count < 2) symbols[count] = i;
  554. ++count;
  555. }
  556. }
  557. if (count == 0) { // emit minimal tree for empty cases
  558. // bits: small tree marker: 1, count-1: 0, large 8-bit code: 0, code: 0
  559. VP8LPutBits(bw, 0x01, 4);
  560. } else if (count <= 2 && symbols[0] < kMaxSymbol && symbols[1] < kMaxSymbol) {
  561. VP8LPutBits(bw, 1, 1); // Small tree marker to encode 1 or 2 symbols.
  562. VP8LPutBits(bw, count - 1, 1);
  563. if (symbols[0] <= 1) {
  564. VP8LPutBits(bw, 0, 1); // Code bit for small (1 bit) symbol value.
  565. VP8LPutBits(bw, symbols[0], 1);
  566. } else {
  567. VP8LPutBits(bw, 1, 1);
  568. VP8LPutBits(bw, symbols[0], 8);
  569. }
  570. if (count == 2) {
  571. VP8LPutBits(bw, symbols[1], 8);
  572. }
  573. } else {
  574. StoreFullHuffmanCode(bw, huff_tree, tokens, huffman_code);
  575. }
  576. }
  577. static WEBP_INLINE void WriteHuffmanCode(VP8LBitWriter* const bw,
  578. const HuffmanTreeCode* const code,
  579. int code_index) {
  580. const int depth = code->code_lengths[code_index];
  581. const int symbol = code->codes[code_index];
  582. VP8LPutBits(bw, symbol, depth);
  583. }
  584. static WEBP_INLINE void WriteHuffmanCodeWithExtraBits(
  585. VP8LBitWriter* const bw,
  586. const HuffmanTreeCode* const code,
  587. int code_index,
  588. int bits,
  589. int n_bits) {
  590. const int depth = code->code_lengths[code_index];
  591. const int symbol = code->codes[code_index];
  592. VP8LPutBits(bw, (bits << depth) | symbol, depth + n_bits);
  593. }
  594. static WebPEncodingError StoreImageToBitMask(
  595. VP8LBitWriter* const bw, int width, int histo_bits,
  596. VP8LBackwardRefs* const refs,
  597. const uint16_t* histogram_symbols,
  598. const HuffmanTreeCode* const huffman_codes) {
  599. const int histo_xsize = histo_bits ? VP8LSubSampleSize(width, histo_bits) : 1;
  600. const int tile_mask = (histo_bits == 0) ? 0 : -(1 << histo_bits);
  601. // x and y trace the position in the image.
  602. int x = 0;
  603. int y = 0;
  604. int tile_x = x & tile_mask;
  605. int tile_y = y & tile_mask;
  606. int histogram_ix = histogram_symbols[0];
  607. const HuffmanTreeCode* codes = huffman_codes + 5 * histogram_ix;
  608. VP8LRefsCursor c = VP8LRefsCursorInit(refs);
  609. while (VP8LRefsCursorOk(&c)) {
  610. const PixOrCopy* const v = c.cur_pos;
  611. if ((tile_x != (x & tile_mask)) || (tile_y != (y & tile_mask))) {
  612. tile_x = x & tile_mask;
  613. tile_y = y & tile_mask;
  614. histogram_ix = histogram_symbols[(y >> histo_bits) * histo_xsize +
  615. (x >> histo_bits)];
  616. codes = huffman_codes + 5 * histogram_ix;
  617. }
  618. if (PixOrCopyIsLiteral(v)) {
  619. static const int order[] = { 1, 2, 0, 3 };
  620. int k;
  621. for (k = 0; k < 4; ++k) {
  622. const int code = PixOrCopyLiteral(v, order[k]);
  623. WriteHuffmanCode(bw, codes + k, code);
  624. }
  625. } else if (PixOrCopyIsCacheIdx(v)) {
  626. const int code = PixOrCopyCacheIdx(v);
  627. const int literal_ix = 256 + NUM_LENGTH_CODES + code;
  628. WriteHuffmanCode(bw, codes, literal_ix);
  629. } else {
  630. int bits, n_bits;
  631. int code;
  632. const int distance = PixOrCopyDistance(v);
  633. VP8LPrefixEncode(v->len, &code, &n_bits, &bits);
  634. WriteHuffmanCodeWithExtraBits(bw, codes, 256 + code, bits, n_bits);
  635. // Don't write the distance with the extra bits code since
  636. // the distance can be up to 18 bits of extra bits, and the prefix
  637. // 15 bits, totaling to 33, and our PutBits only supports up to 32 bits.
  638. // TODO(jyrki): optimize this further.
  639. VP8LPrefixEncode(distance, &code, &n_bits, &bits);
  640. WriteHuffmanCode(bw, codes + 4, code);
  641. VP8LPutBits(bw, bits, n_bits);
  642. }
  643. x += PixOrCopyLength(v);
  644. while (x >= width) {
  645. x -= width;
  646. ++y;
  647. }
  648. VP8LRefsCursorNext(&c);
  649. }
  650. return bw->error_ ? VP8_ENC_ERROR_OUT_OF_MEMORY : VP8_ENC_OK;
  651. }
  652. // Special case of EncodeImageInternal() for cache-bits=0, histo_bits=31
  653. static WebPEncodingError EncodeImageNoHuffman(VP8LBitWriter* const bw,
  654. const uint32_t* const argb,
  655. VP8LHashChain* const hash_chain,
  656. VP8LBackwardRefs refs_array[2],
  657. int width, int height,
  658. int quality, int low_effort) {
  659. int i;
  660. int max_tokens = 0;
  661. WebPEncodingError err = VP8_ENC_OK;
  662. VP8LBackwardRefs* refs;
  663. HuffmanTreeToken* tokens = NULL;
  664. HuffmanTreeCode huffman_codes[5] = { { 0, NULL, NULL } };
  665. const uint16_t histogram_symbols[1] = { 0 }; // only one tree, one symbol
  666. int cache_bits = 0;
  667. VP8LHistogramSet* histogram_image = NULL;
  668. HuffmanTree* const huff_tree = (HuffmanTree*)WebPSafeMalloc(
  669. 3ULL * CODE_LENGTH_CODES, sizeof(*huff_tree));
  670. if (huff_tree == NULL) {
  671. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  672. goto Error;
  673. }
  674. // Calculate backward references from ARGB image.
  675. if (!VP8LHashChainFill(hash_chain, quality, argb, width, height,
  676. low_effort)) {
  677. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  678. goto Error;
  679. }
  680. refs = VP8LGetBackwardReferences(width, height, argb, quality, 0, &cache_bits,
  681. hash_chain, refs_array);
  682. if (refs == NULL) {
  683. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  684. goto Error;
  685. }
  686. histogram_image = VP8LAllocateHistogramSet(1, cache_bits);
  687. if (histogram_image == NULL) {
  688. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  689. goto Error;
  690. }
  691. // Build histogram image and symbols from backward references.
  692. VP8LHistogramStoreRefs(refs, histogram_image->histograms[0]);
  693. // Create Huffman bit lengths and codes for each histogram image.
  694. assert(histogram_image->size == 1);
  695. if (!GetHuffBitLengthsAndCodes(histogram_image, huffman_codes)) {
  696. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  697. goto Error;
  698. }
  699. // No color cache, no Huffman image.
  700. VP8LPutBits(bw, 0, 1);
  701. // Find maximum number of symbols for the huffman tree-set.
  702. for (i = 0; i < 5; ++i) {
  703. HuffmanTreeCode* const codes = &huffman_codes[i];
  704. if (max_tokens < codes->num_symbols) {
  705. max_tokens = codes->num_symbols;
  706. }
  707. }
  708. tokens = (HuffmanTreeToken*)WebPSafeMalloc(max_tokens, sizeof(*tokens));
  709. if (tokens == NULL) {
  710. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  711. goto Error;
  712. }
  713. // Store Huffman codes.
  714. for (i = 0; i < 5; ++i) {
  715. HuffmanTreeCode* const codes = &huffman_codes[i];
  716. StoreHuffmanCode(bw, huff_tree, tokens, codes);
  717. ClearHuffmanTreeIfOnlyOneSymbol(codes);
  718. }
  719. // Store actual literals.
  720. err = StoreImageToBitMask(bw, width, 0, refs, histogram_symbols,
  721. huffman_codes);
  722. Error:
  723. WebPSafeFree(tokens);
  724. WebPSafeFree(huff_tree);
  725. VP8LFreeHistogramSet(histogram_image);
  726. WebPSafeFree(huffman_codes[0].codes);
  727. return err;
  728. }
  729. static WebPEncodingError EncodeImageInternal(VP8LBitWriter* const bw,
  730. const uint32_t* const argb,
  731. VP8LHashChain* const hash_chain,
  732. VP8LBackwardRefs refs_array[2],
  733. int width, int height, int quality,
  734. int low_effort,
  735. int use_cache, int* cache_bits,
  736. int histogram_bits,
  737. size_t init_byte_position,
  738. int* const hdr_size,
  739. int* const data_size) {
  740. WebPEncodingError err = VP8_ENC_OK;
  741. const uint32_t histogram_image_xysize =
  742. VP8LSubSampleSize(width, histogram_bits) *
  743. VP8LSubSampleSize(height, histogram_bits);
  744. VP8LHistogramSet* histogram_image = NULL;
  745. VP8LHistogramSet* tmp_histos = NULL;
  746. int histogram_image_size = 0;
  747. size_t bit_array_size = 0;
  748. HuffmanTree* huff_tree = NULL;
  749. HuffmanTreeToken* tokens = NULL;
  750. HuffmanTreeCode* huffman_codes = NULL;
  751. VP8LBackwardRefs refs;
  752. VP8LBackwardRefs* best_refs;
  753. uint16_t* const histogram_symbols =
  754. (uint16_t*)WebPSafeMalloc(histogram_image_xysize,
  755. sizeof(*histogram_symbols));
  756. assert(histogram_bits >= MIN_HUFFMAN_BITS);
  757. assert(histogram_bits <= MAX_HUFFMAN_BITS);
  758. assert(hdr_size != NULL);
  759. assert(data_size != NULL);
  760. VP8LBackwardRefsInit(&refs, refs_array[0].block_size_);
  761. if (histogram_symbols == NULL) {
  762. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  763. goto Error;
  764. }
  765. if (use_cache) {
  766. // If the value is different from zero, it has been set during the
  767. // palette analysis.
  768. if (*cache_bits == 0) *cache_bits = MAX_COLOR_CACHE_BITS;
  769. } else {
  770. *cache_bits = 0;
  771. }
  772. // 'best_refs' is the reference to the best backward refs and points to one
  773. // of refs_array[0] or refs_array[1].
  774. // Calculate backward references from ARGB image.
  775. if (!VP8LHashChainFill(hash_chain, quality, argb, width, height,
  776. low_effort)) {
  777. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  778. goto Error;
  779. }
  780. best_refs = VP8LGetBackwardReferences(width, height, argb, quality,
  781. low_effort, cache_bits, hash_chain,
  782. refs_array);
  783. if (best_refs == NULL || !VP8LBackwardRefsCopy(best_refs, &refs)) {
  784. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  785. goto Error;
  786. }
  787. histogram_image =
  788. VP8LAllocateHistogramSet(histogram_image_xysize, *cache_bits);
  789. tmp_histos = VP8LAllocateHistogramSet(2, *cache_bits);
  790. if (histogram_image == NULL || tmp_histos == NULL) {
  791. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  792. goto Error;
  793. }
  794. // Build histogram image and symbols from backward references.
  795. if (!VP8LGetHistoImageSymbols(width, height, &refs, quality, low_effort,
  796. histogram_bits, *cache_bits, histogram_image,
  797. tmp_histos, histogram_symbols)) {
  798. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  799. goto Error;
  800. }
  801. // Create Huffman bit lengths and codes for each histogram image.
  802. histogram_image_size = histogram_image->size;
  803. bit_array_size = 5 * histogram_image_size;
  804. huffman_codes = (HuffmanTreeCode*)WebPSafeCalloc(bit_array_size,
  805. sizeof(*huffman_codes));
  806. // Note: some histogram_image entries may point to tmp_histos[], so the latter
  807. // need to outlive the following call to GetHuffBitLengthsAndCodes().
  808. if (huffman_codes == NULL ||
  809. !GetHuffBitLengthsAndCodes(histogram_image, huffman_codes)) {
  810. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  811. goto Error;
  812. }
  813. // Free combined histograms.
  814. VP8LFreeHistogramSet(histogram_image);
  815. histogram_image = NULL;
  816. // Free scratch histograms.
  817. VP8LFreeHistogramSet(tmp_histos);
  818. tmp_histos = NULL;
  819. // Color Cache parameters.
  820. if (*cache_bits > 0) {
  821. VP8LPutBits(bw, 1, 1);
  822. VP8LPutBits(bw, *cache_bits, 4);
  823. } else {
  824. VP8LPutBits(bw, 0, 1);
  825. }
  826. // Huffman image + meta huffman.
  827. {
  828. const int write_histogram_image = (histogram_image_size > 1);
  829. VP8LPutBits(bw, write_histogram_image, 1);
  830. if (write_histogram_image) {
  831. uint32_t* const histogram_argb =
  832. (uint32_t*)WebPSafeMalloc(histogram_image_xysize,
  833. sizeof(*histogram_argb));
  834. int max_index = 0;
  835. uint32_t i;
  836. if (histogram_argb == NULL) {
  837. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  838. goto Error;
  839. }
  840. for (i = 0; i < histogram_image_xysize; ++i) {
  841. const int symbol_index = histogram_symbols[i] & 0xffff;
  842. histogram_argb[i] = (symbol_index << 8);
  843. if (symbol_index >= max_index) {
  844. max_index = symbol_index + 1;
  845. }
  846. }
  847. histogram_image_size = max_index;
  848. VP8LPutBits(bw, histogram_bits - 2, 3);
  849. err = EncodeImageNoHuffman(bw, histogram_argb, hash_chain, refs_array,
  850. VP8LSubSampleSize(width, histogram_bits),
  851. VP8LSubSampleSize(height, histogram_bits),
  852. quality, low_effort);
  853. WebPSafeFree(histogram_argb);
  854. if (err != VP8_ENC_OK) goto Error;
  855. }
  856. }
  857. // Store Huffman codes.
  858. {
  859. int i;
  860. int max_tokens = 0;
  861. huff_tree = (HuffmanTree*)WebPSafeMalloc(3ULL * CODE_LENGTH_CODES,
  862. sizeof(*huff_tree));
  863. if (huff_tree == NULL) {
  864. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  865. goto Error;
  866. }
  867. // Find maximum number of symbols for the huffman tree-set.
  868. for (i = 0; i < 5 * histogram_image_size; ++i) {
  869. HuffmanTreeCode* const codes = &huffman_codes[i];
  870. if (max_tokens < codes->num_symbols) {
  871. max_tokens = codes->num_symbols;
  872. }
  873. }
  874. tokens = (HuffmanTreeToken*)WebPSafeMalloc(max_tokens,
  875. sizeof(*tokens));
  876. if (tokens == NULL) {
  877. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  878. goto Error;
  879. }
  880. for (i = 0; i < 5 * histogram_image_size; ++i) {
  881. HuffmanTreeCode* const codes = &huffman_codes[i];
  882. StoreHuffmanCode(bw, huff_tree, tokens, codes);
  883. ClearHuffmanTreeIfOnlyOneSymbol(codes);
  884. }
  885. }
  886. *hdr_size = (int)(VP8LBitWriterNumBytes(bw) - init_byte_position);
  887. // Store actual literals.
  888. err = StoreImageToBitMask(bw, width, histogram_bits, &refs,
  889. histogram_symbols, huffman_codes);
  890. *data_size =
  891. (int)(VP8LBitWriterNumBytes(bw) - init_byte_position - *hdr_size);
  892. Error:
  893. WebPSafeFree(tokens);
  894. WebPSafeFree(huff_tree);
  895. VP8LFreeHistogramSet(histogram_image);
  896. VP8LFreeHistogramSet(tmp_histos);
  897. VP8LBackwardRefsClear(&refs);
  898. if (huffman_codes != NULL) {
  899. WebPSafeFree(huffman_codes->codes);
  900. WebPSafeFree(huffman_codes);
  901. }
  902. WebPSafeFree(histogram_symbols);
  903. return err;
  904. }
  905. // -----------------------------------------------------------------------------
  906. // Transforms
  907. static void ApplySubtractGreen(VP8LEncoder* const enc, int width, int height,
  908. VP8LBitWriter* const bw) {
  909. VP8LPutBits(bw, TRANSFORM_PRESENT, 1);
  910. VP8LPutBits(bw, SUBTRACT_GREEN, 2);
  911. VP8LSubtractGreenFromBlueAndRed(enc->argb_, width * height);
  912. }
  913. static WebPEncodingError ApplyPredictFilter(const VP8LEncoder* const enc,
  914. int width, int height,
  915. int quality, int low_effort,
  916. int used_subtract_green,
  917. VP8LBitWriter* const bw) {
  918. const int pred_bits = enc->transform_bits_;
  919. const int transform_width = VP8LSubSampleSize(width, pred_bits);
  920. const int transform_height = VP8LSubSampleSize(height, pred_bits);
  921. // we disable near-lossless quantization if palette is used.
  922. const int near_lossless_strength = enc->use_palette_ ? 100
  923. : enc->config_->near_lossless;
  924. VP8LResidualImage(width, height, pred_bits, low_effort, enc->argb_,
  925. enc->argb_scratch_, enc->transform_data_,
  926. near_lossless_strength, enc->config_->exact,
  927. used_subtract_green);
  928. VP8LPutBits(bw, TRANSFORM_PRESENT, 1);
  929. VP8LPutBits(bw, PREDICTOR_TRANSFORM, 2);
  930. assert(pred_bits >= 2);
  931. VP8LPutBits(bw, pred_bits - 2, 3);
  932. return EncodeImageNoHuffman(bw, enc->transform_data_,
  933. (VP8LHashChain*)&enc->hash_chain_,
  934. (VP8LBackwardRefs*)enc->refs_, // cast const away
  935. transform_width, transform_height,
  936. quality, low_effort);
  937. }
  938. static WebPEncodingError ApplyCrossColorFilter(const VP8LEncoder* const enc,
  939. int width, int height,
  940. int quality, int low_effort,
  941. VP8LBitWriter* const bw) {
  942. const int ccolor_transform_bits = enc->transform_bits_;
  943. const int transform_width = VP8LSubSampleSize(width, ccolor_transform_bits);
  944. const int transform_height = VP8LSubSampleSize(height, ccolor_transform_bits);
  945. VP8LColorSpaceTransform(width, height, ccolor_transform_bits, quality,
  946. enc->argb_, enc->transform_data_);
  947. VP8LPutBits(bw, TRANSFORM_PRESENT, 1);
  948. VP8LPutBits(bw, CROSS_COLOR_TRANSFORM, 2);
  949. assert(ccolor_transform_bits >= 2);
  950. VP8LPutBits(bw, ccolor_transform_bits - 2, 3);
  951. return EncodeImageNoHuffman(bw, enc->transform_data_,
  952. (VP8LHashChain*)&enc->hash_chain_,
  953. (VP8LBackwardRefs*)enc->refs_, // cast const away
  954. transform_width, transform_height,
  955. quality, low_effort);
  956. }
  957. // -----------------------------------------------------------------------------
  958. static WebPEncodingError WriteRiffHeader(const WebPPicture* const pic,
  959. size_t riff_size, size_t vp8l_size) {
  960. uint8_t riff[RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE + VP8L_SIGNATURE_SIZE] = {
  961. 'R', 'I', 'F', 'F', 0, 0, 0, 0, 'W', 'E', 'B', 'P',
  962. 'V', 'P', '8', 'L', 0, 0, 0, 0, VP8L_MAGIC_BYTE,
  963. };
  964. PutLE32(riff + TAG_SIZE, (uint32_t)riff_size);
  965. PutLE32(riff + RIFF_HEADER_SIZE + TAG_SIZE, (uint32_t)vp8l_size);
  966. if (!pic->writer(riff, sizeof(riff), pic)) {
  967. return VP8_ENC_ERROR_BAD_WRITE;
  968. }
  969. return VP8_ENC_OK;
  970. }
  971. static int WriteImageSize(const WebPPicture* const pic,
  972. VP8LBitWriter* const bw) {
  973. const int width = pic->width - 1;
  974. const int height = pic->height - 1;
  975. assert(width < WEBP_MAX_DIMENSION && height < WEBP_MAX_DIMENSION);
  976. VP8LPutBits(bw, width, VP8L_IMAGE_SIZE_BITS);
  977. VP8LPutBits(bw, height, VP8L_IMAGE_SIZE_BITS);
  978. return !bw->error_;
  979. }
  980. static int WriteRealAlphaAndVersion(VP8LBitWriter* const bw, int has_alpha) {
  981. VP8LPutBits(bw, has_alpha, 1);
  982. VP8LPutBits(bw, VP8L_VERSION, VP8L_VERSION_BITS);
  983. return !bw->error_;
  984. }
  985. static WebPEncodingError WriteImage(const WebPPicture* const pic,
  986. VP8LBitWriter* const bw,
  987. size_t* const coded_size) {
  988. WebPEncodingError err = VP8_ENC_OK;
  989. const uint8_t* const webpll_data = VP8LBitWriterFinish(bw);
  990. const size_t webpll_size = VP8LBitWriterNumBytes(bw);
  991. const size_t vp8l_size = VP8L_SIGNATURE_SIZE + webpll_size;
  992. const size_t pad = vp8l_size & 1;
  993. const size_t riff_size = TAG_SIZE + CHUNK_HEADER_SIZE + vp8l_size + pad;
  994. err = WriteRiffHeader(pic, riff_size, vp8l_size);
  995. if (err != VP8_ENC_OK) goto Error;
  996. if (!pic->writer(webpll_data, webpll_size, pic)) {
  997. err = VP8_ENC_ERROR_BAD_WRITE;
  998. goto Error;
  999. }
  1000. if (pad) {
  1001. const uint8_t pad_byte[1] = { 0 };
  1002. if (!pic->writer(pad_byte, 1, pic)) {
  1003. err = VP8_ENC_ERROR_BAD_WRITE;
  1004. goto Error;
  1005. }
  1006. }
  1007. *coded_size = CHUNK_HEADER_SIZE + riff_size;
  1008. return VP8_ENC_OK;
  1009. Error:
  1010. return err;
  1011. }
  1012. // -----------------------------------------------------------------------------
  1013. static void ClearTransformBuffer(VP8LEncoder* const enc) {
  1014. WebPSafeFree(enc->transform_mem_);
  1015. enc->transform_mem_ = NULL;
  1016. enc->transform_mem_size_ = 0;
  1017. }
  1018. // Allocates the memory for argb (W x H) buffer, 2 rows of context for
  1019. // prediction and transform data.
  1020. // Flags influencing the memory allocated:
  1021. // enc->transform_bits_
  1022. // enc->use_predict_, enc->use_cross_color_
  1023. static WebPEncodingError AllocateTransformBuffer(VP8LEncoder* const enc,
  1024. int width, int height) {
  1025. WebPEncodingError err = VP8_ENC_OK;
  1026. const uint64_t image_size = width * height;
  1027. // VP8LResidualImage needs room for 2 scanlines of uint32 pixels with an extra
  1028. // pixel in each, plus 2 regular scanlines of bytes.
  1029. // TODO(skal): Clean up by using arithmetic in bytes instead of words.
  1030. const uint64_t argb_scratch_size =
  1031. enc->use_predict_
  1032. ? (width + 1) * 2 +
  1033. (width * 2 + sizeof(uint32_t) - 1) / sizeof(uint32_t)
  1034. : 0;
  1035. const uint64_t transform_data_size =
  1036. (enc->use_predict_ || enc->use_cross_color_)
  1037. ? VP8LSubSampleSize(width, enc->transform_bits_) *
  1038. VP8LSubSampleSize(height, enc->transform_bits_)
  1039. : 0;
  1040. const uint64_t max_alignment_in_words =
  1041. (WEBP_ALIGN_CST + sizeof(uint32_t) - 1) / sizeof(uint32_t);
  1042. const uint64_t mem_size =
  1043. image_size + max_alignment_in_words +
  1044. argb_scratch_size + max_alignment_in_words +
  1045. transform_data_size;
  1046. uint32_t* mem = enc->transform_mem_;
  1047. if (mem == NULL || mem_size > enc->transform_mem_size_) {
  1048. ClearTransformBuffer(enc);
  1049. mem = (uint32_t*)WebPSafeMalloc(mem_size, sizeof(*mem));
  1050. if (mem == NULL) {
  1051. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1052. goto Error;
  1053. }
  1054. enc->transform_mem_ = mem;
  1055. enc->transform_mem_size_ = (size_t)mem_size;
  1056. }
  1057. enc->argb_ = mem;
  1058. mem = (uint32_t*)WEBP_ALIGN(mem + image_size);
  1059. enc->argb_scratch_ = mem;
  1060. mem = (uint32_t*)WEBP_ALIGN(mem + argb_scratch_size);
  1061. enc->transform_data_ = mem;
  1062. enc->current_width_ = width;
  1063. Error:
  1064. return err;
  1065. }
  1066. static WebPEncodingError MakeInputImageCopy(VP8LEncoder* const enc) {
  1067. WebPEncodingError err = VP8_ENC_OK;
  1068. const WebPPicture* const picture = enc->pic_;
  1069. const int width = picture->width;
  1070. const int height = picture->height;
  1071. int y;
  1072. err = AllocateTransformBuffer(enc, width, height);
  1073. if (err != VP8_ENC_OK) return err;
  1074. for (y = 0; y < height; ++y) {
  1075. memcpy(enc->argb_ + y * width,
  1076. picture->argb + y * picture->argb_stride,
  1077. width * sizeof(*enc->argb_));
  1078. }
  1079. assert(enc->current_width_ == width);
  1080. return VP8_ENC_OK;
  1081. }
  1082. // -----------------------------------------------------------------------------
  1083. static WEBP_INLINE int SearchColorNoIdx(const uint32_t sorted[], uint32_t color,
  1084. int hi) {
  1085. int low = 0;
  1086. if (sorted[low] == color) return low; // loop invariant: sorted[low] != color
  1087. while (1) {
  1088. const int mid = (low + hi) >> 1;
  1089. if (sorted[mid] == color) {
  1090. return mid;
  1091. } else if (sorted[mid] < color) {
  1092. low = mid;
  1093. } else {
  1094. hi = mid;
  1095. }
  1096. }
  1097. }
  1098. #define APPLY_PALETTE_GREEDY_MAX 4
  1099. static WEBP_INLINE uint32_t SearchColorGreedy(const uint32_t palette[],
  1100. int palette_size,
  1101. uint32_t color) {
  1102. (void)palette_size;
  1103. assert(palette_size < APPLY_PALETTE_GREEDY_MAX);
  1104. assert(3 == APPLY_PALETTE_GREEDY_MAX - 1);
  1105. if (color == palette[0]) return 0;
  1106. if (color == palette[1]) return 1;
  1107. if (color == palette[2]) return 2;
  1108. return 3;
  1109. }
  1110. static WEBP_INLINE uint32_t ApplyPaletteHash0(uint32_t color) {
  1111. // Focus on the green color.
  1112. return (color >> 8) & 0xff;
  1113. }
  1114. #define PALETTE_INV_SIZE_BITS 11
  1115. #define PALETTE_INV_SIZE (1 << PALETTE_INV_SIZE_BITS)
  1116. static WEBP_INLINE uint32_t ApplyPaletteHash1(uint32_t color) {
  1117. // Forget about alpha.
  1118. return ((color & 0x00ffffffu) * 4222244071u) >> (32 - PALETTE_INV_SIZE_BITS);
  1119. }
  1120. static WEBP_INLINE uint32_t ApplyPaletteHash2(uint32_t color) {
  1121. // Forget about alpha.
  1122. return (color & 0x00ffffffu) * ((1u << 31) - 1) >>
  1123. (32 - PALETTE_INV_SIZE_BITS);
  1124. }
  1125. // Sort palette in increasing order and prepare an inverse mapping array.
  1126. static void PrepareMapToPalette(const uint32_t palette[], int num_colors,
  1127. uint32_t sorted[], uint32_t idx_map[]) {
  1128. int i;
  1129. memcpy(sorted, palette, num_colors * sizeof(*sorted));
  1130. qsort(sorted, num_colors, sizeof(*sorted), PaletteCompareColorsForQsort);
  1131. for (i = 0; i < num_colors; ++i) {
  1132. idx_map[SearchColorNoIdx(sorted, palette[i], num_colors)] = i;
  1133. }
  1134. }
  1135. // Use 1 pixel cache for ARGB pixels.
  1136. #define APPLY_PALETTE_FOR(COLOR_INDEX) do { \
  1137. uint32_t prev_pix = palette[0]; \
  1138. uint32_t prev_idx = 0; \
  1139. for (y = 0; y < height; ++y) { \
  1140. for (x = 0; x < width; ++x) { \
  1141. const uint32_t pix = src[x]; \
  1142. if (pix != prev_pix) { \
  1143. prev_idx = COLOR_INDEX; \
  1144. prev_pix = pix; \
  1145. } \
  1146. tmp_row[x] = prev_idx; \
  1147. } \
  1148. VP8LBundleColorMap(tmp_row, width, xbits, dst); \
  1149. src += src_stride; \
  1150. dst += dst_stride; \
  1151. } \
  1152. } while (0)
  1153. // Remap argb values in src[] to packed palettes entries in dst[]
  1154. // using 'row' as a temporary buffer of size 'width'.
  1155. // We assume that all src[] values have a corresponding entry in the palette.
  1156. // Note: src[] can be the same as dst[]
  1157. static WebPEncodingError ApplyPalette(const uint32_t* src, uint32_t src_stride,
  1158. uint32_t* dst, uint32_t dst_stride,
  1159. const uint32_t* palette, int palette_size,
  1160. int width, int height, int xbits) {
  1161. // TODO(skal): this tmp buffer is not needed if VP8LBundleColorMap() can be
  1162. // made to work in-place.
  1163. uint8_t* const tmp_row = (uint8_t*)WebPSafeMalloc(width, sizeof(*tmp_row));
  1164. int x, y;
  1165. if (tmp_row == NULL) return VP8_ENC_ERROR_OUT_OF_MEMORY;
  1166. if (palette_size < APPLY_PALETTE_GREEDY_MAX) {
  1167. APPLY_PALETTE_FOR(SearchColorGreedy(palette, palette_size, pix));
  1168. } else {
  1169. int i, j;
  1170. uint16_t buffer[PALETTE_INV_SIZE];
  1171. uint32_t (*const hash_functions[])(uint32_t) = {
  1172. ApplyPaletteHash0, ApplyPaletteHash1, ApplyPaletteHash2
  1173. };
  1174. // Try to find a perfect hash function able to go from a color to an index
  1175. // within 1 << PALETTE_INV_SIZE_BITS in order to build a hash map to go
  1176. // from color to index in palette.
  1177. for (i = 0; i < 3; ++i) {
  1178. int use_LUT = 1;
  1179. // Set each element in buffer to max uint16_t.
  1180. memset(buffer, 0xff, sizeof(buffer));
  1181. for (j = 0; j < palette_size; ++j) {
  1182. const uint32_t ind = hash_functions[i](palette[j]);
  1183. if (buffer[ind] != 0xffffu) {
  1184. use_LUT = 0;
  1185. break;
  1186. } else {
  1187. buffer[ind] = j;
  1188. }
  1189. }
  1190. if (use_LUT) break;
  1191. }
  1192. if (i == 0) {
  1193. APPLY_PALETTE_FOR(buffer[ApplyPaletteHash0(pix)]);
  1194. } else if (i == 1) {
  1195. APPLY_PALETTE_FOR(buffer[ApplyPaletteHash1(pix)]);
  1196. } else if (i == 2) {
  1197. APPLY_PALETTE_FOR(buffer[ApplyPaletteHash2(pix)]);
  1198. } else {
  1199. uint32_t idx_map[MAX_PALETTE_SIZE];
  1200. uint32_t palette_sorted[MAX_PALETTE_SIZE];
  1201. PrepareMapToPalette(palette, palette_size, palette_sorted, idx_map);
  1202. APPLY_PALETTE_FOR(
  1203. idx_map[SearchColorNoIdx(palette_sorted, pix, palette_size)]);
  1204. }
  1205. }
  1206. WebPSafeFree(tmp_row);
  1207. return VP8_ENC_OK;
  1208. }
  1209. #undef APPLY_PALETTE_FOR
  1210. #undef PALETTE_INV_SIZE_BITS
  1211. #undef PALETTE_INV_SIZE
  1212. #undef APPLY_PALETTE_GREEDY_MAX
  1213. // Note: Expects "enc->palette_" to be set properly.
  1214. static WebPEncodingError MapImageFromPalette(VP8LEncoder* const enc,
  1215. int in_place) {
  1216. WebPEncodingError err = VP8_ENC_OK;
  1217. const WebPPicture* const pic = enc->pic_;
  1218. const int width = pic->width;
  1219. const int height = pic->height;
  1220. const uint32_t* const palette = enc->palette_;
  1221. const uint32_t* src = in_place ? enc->argb_ : pic->argb;
  1222. const int src_stride = in_place ? enc->current_width_ : pic->argb_stride;
  1223. const int palette_size = enc->palette_size_;
  1224. int xbits;
  1225. // Replace each input pixel by corresponding palette index.
  1226. // This is done line by line.
  1227. if (palette_size <= 4) {
  1228. xbits = (palette_size <= 2) ? 3 : 2;
  1229. } else {
  1230. xbits = (palette_size <= 16) ? 1 : 0;
  1231. }
  1232. err = AllocateTransformBuffer(enc, VP8LSubSampleSize(width, xbits), height);
  1233. if (err != VP8_ENC_OK) return err;
  1234. err = ApplyPalette(src, src_stride,
  1235. enc->argb_, enc->current_width_,
  1236. palette, palette_size, width, height, xbits);
  1237. return err;
  1238. }
  1239. // Save palette_[] to bitstream.
  1240. static WebPEncodingError EncodePalette(VP8LBitWriter* const bw, int low_effort,
  1241. VP8LEncoder* const enc) {
  1242. int i;
  1243. uint32_t tmp_palette[MAX_PALETTE_SIZE];
  1244. const int palette_size = enc->palette_size_;
  1245. const uint32_t* const palette = enc->palette_;
  1246. VP8LPutBits(bw, TRANSFORM_PRESENT, 1);
  1247. VP8LPutBits(bw, COLOR_INDEXING_TRANSFORM, 2);
  1248. assert(palette_size >= 1 && palette_size <= MAX_PALETTE_SIZE);
  1249. VP8LPutBits(bw, palette_size - 1, 8);
  1250. for (i = palette_size - 1; i >= 1; --i) {
  1251. tmp_palette[i] = VP8LSubPixels(palette[i], palette[i - 1]);
  1252. }
  1253. tmp_palette[0] = palette[0];
  1254. return EncodeImageNoHuffman(bw, tmp_palette, &enc->hash_chain_, enc->refs_,
  1255. palette_size, 1, 20 /* quality */, low_effort);
  1256. }
  1257. #ifdef WEBP_EXPERIMENTAL_FEATURES
  1258. static WebPEncodingError EncodeDeltaPalettePredictorImage(
  1259. VP8LBitWriter* const bw, VP8LEncoder* const enc, int quality,
  1260. int low_effort) {
  1261. const WebPPicture* const pic = enc->pic_;
  1262. const int width = pic->width;
  1263. const int height = pic->height;
  1264. const int pred_bits = 5;
  1265. const int transform_width = VP8LSubSampleSize(width, pred_bits);
  1266. const int transform_height = VP8LSubSampleSize(height, pred_bits);
  1267. const int pred = 7; // default is Predictor7 (Top/Left Average)
  1268. const int tiles_per_row = VP8LSubSampleSize(width, pred_bits);
  1269. const int tiles_per_col = VP8LSubSampleSize(height, pred_bits);
  1270. uint32_t* predictors;
  1271. int tile_x, tile_y;
  1272. WebPEncodingError err = VP8_ENC_OK;
  1273. predictors = (uint32_t*)WebPSafeMalloc(tiles_per_col * tiles_per_row,
  1274. sizeof(*predictors));
  1275. if (predictors == NULL) return VP8_ENC_ERROR_OUT_OF_MEMORY;
  1276. for (tile_y = 0; tile_y < tiles_per_col; ++tile_y) {
  1277. for (tile_x = 0; tile_x < tiles_per_row; ++tile_x) {
  1278. predictors[tile_y * tiles_per_row + tile_x] = 0xff000000u | (pred << 8);
  1279. }
  1280. }
  1281. VP8LPutBits(bw, TRANSFORM_PRESENT, 1);
  1282. VP8LPutBits(bw, PREDICTOR_TRANSFORM, 2);
  1283. VP8LPutBits(bw, pred_bits - 2, 3);
  1284. err = EncodeImageNoHuffman(bw, predictors, &enc->hash_chain_,
  1285. (VP8LBackwardRefs*)enc->refs_, // cast const away
  1286. transform_width, transform_height,
  1287. quality, low_effort);
  1288. WebPSafeFree(predictors);
  1289. return err;
  1290. }
  1291. #endif // WEBP_EXPERIMENTAL_FEATURES
  1292. // -----------------------------------------------------------------------------
  1293. // VP8LEncoder
  1294. static VP8LEncoder* VP8LEncoderNew(const WebPConfig* const config,
  1295. const WebPPicture* const picture) {
  1296. VP8LEncoder* const enc = (VP8LEncoder*)WebPSafeCalloc(1ULL, sizeof(*enc));
  1297. if (enc == NULL) {
  1298. WebPEncodingSetError(picture, VP8_ENC_ERROR_OUT_OF_MEMORY);
  1299. return NULL;
  1300. }
  1301. enc->config_ = config;
  1302. enc->pic_ = picture;
  1303. VP8LEncDspInit();
  1304. return enc;
  1305. }
  1306. static void VP8LEncoderDelete(VP8LEncoder* enc) {
  1307. if (enc != NULL) {
  1308. VP8LHashChainClear(&enc->hash_chain_);
  1309. VP8LBackwardRefsClear(&enc->refs_[0]);
  1310. VP8LBackwardRefsClear(&enc->refs_[1]);
  1311. ClearTransformBuffer(enc);
  1312. WebPSafeFree(enc);
  1313. }
  1314. }
  1315. // -----------------------------------------------------------------------------
  1316. // Main call
  1317. WebPEncodingError VP8LEncodeStream(const WebPConfig* const config,
  1318. const WebPPicture* const picture,
  1319. VP8LBitWriter* const bw, int use_cache) {
  1320. WebPEncodingError err = VP8_ENC_OK;
  1321. const int quality = (int)config->quality;
  1322. const int low_effort = (config->method == 0);
  1323. const int width = picture->width;
  1324. const int height = picture->height;
  1325. VP8LEncoder* const enc = VP8LEncoderNew(config, picture);
  1326. const size_t byte_position = VP8LBitWriterNumBytes(bw);
  1327. int use_near_lossless = 0;
  1328. int hdr_size = 0;
  1329. int data_size = 0;
  1330. int use_delta_palette = 0;
  1331. if (enc == NULL) {
  1332. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1333. goto Error;
  1334. }
  1335. // ---------------------------------------------------------------------------
  1336. // Analyze image (entropy, num_palettes etc)
  1337. if (!AnalyzeAndInit(enc)) {
  1338. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1339. goto Error;
  1340. }
  1341. // Apply near-lossless preprocessing.
  1342. use_near_lossless =
  1343. (config->near_lossless < 100) && !enc->use_palette_ && !enc->use_predict_;
  1344. if (use_near_lossless) {
  1345. if (!VP8ApplyNearLossless(width, height, picture->argb,
  1346. config->near_lossless)) {
  1347. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1348. goto Error;
  1349. }
  1350. }
  1351. #ifdef WEBP_EXPERIMENTAL_FEATURES
  1352. if (config->use_delta_palette) {
  1353. enc->use_predict_ = 1;
  1354. enc->use_cross_color_ = 0;
  1355. enc->use_subtract_green_ = 0;
  1356. enc->use_palette_ = 1;
  1357. err = MakeInputImageCopy(enc);
  1358. if (err != VP8_ENC_OK) goto Error;
  1359. err = WebPSearchOptimalDeltaPalette(enc);
  1360. if (err != VP8_ENC_OK) goto Error;
  1361. if (enc->use_palette_) {
  1362. err = AllocateTransformBuffer(enc, width, height);
  1363. if (err != VP8_ENC_OK) goto Error;
  1364. err = EncodeDeltaPalettePredictorImage(bw, enc, quality, low_effort);
  1365. if (err != VP8_ENC_OK) goto Error;
  1366. use_delta_palette = 1;
  1367. }
  1368. }
  1369. #endif // WEBP_EXPERIMENTAL_FEATURES
  1370. // Encode palette
  1371. if (enc->use_palette_) {
  1372. err = EncodePalette(bw, low_effort, enc);
  1373. if (err != VP8_ENC_OK) goto Error;
  1374. err = MapImageFromPalette(enc, use_delta_palette);
  1375. if (err != VP8_ENC_OK) goto Error;
  1376. // If using a color cache, do not have it bigger than the number of colors.
  1377. if (use_cache && enc->palette_size_ < (1 << MAX_COLOR_CACHE_BITS)) {
  1378. enc->cache_bits_ = BitsLog2Floor(enc->palette_size_) + 1;
  1379. }
  1380. }
  1381. if (!use_delta_palette) {
  1382. // In case image is not packed.
  1383. if (enc->argb_ == NULL) {
  1384. err = MakeInputImageCopy(enc);
  1385. if (err != VP8_ENC_OK) goto Error;
  1386. }
  1387. // -------------------------------------------------------------------------
  1388. // Apply transforms and write transform data.
  1389. if (enc->use_subtract_green_) {
  1390. ApplySubtractGreen(enc, enc->current_width_, height, bw);
  1391. }
  1392. if (enc->use_predict_) {
  1393. err = ApplyPredictFilter(enc, enc->current_width_, height, quality,
  1394. low_effort, enc->use_subtract_green_, bw);
  1395. if (err != VP8_ENC_OK) goto Error;
  1396. }
  1397. if (enc->use_cross_color_) {
  1398. err = ApplyCrossColorFilter(enc, enc->current_width_,
  1399. height, quality, low_effort, bw);
  1400. if (err != VP8_ENC_OK) goto Error;
  1401. }
  1402. }
  1403. VP8LPutBits(bw, !TRANSFORM_PRESENT, 1); // No more transforms.
  1404. // ---------------------------------------------------------------------------
  1405. // Encode and write the transformed image.
  1406. err = EncodeImageInternal(bw, enc->argb_, &enc->hash_chain_, enc->refs_,
  1407. enc->current_width_, height, quality, low_effort,
  1408. use_cache, &enc->cache_bits_, enc->histo_bits_,
  1409. byte_position, &hdr_size, &data_size);
  1410. if (err != VP8_ENC_OK) goto Error;
  1411. if (picture->stats != NULL) {
  1412. WebPAuxStats* const stats = picture->stats;
  1413. stats->lossless_features = 0;
  1414. if (enc->use_predict_) stats->lossless_features |= 1;
  1415. if (enc->use_cross_color_) stats->lossless_features |= 2;
  1416. if (enc->use_subtract_green_) stats->lossless_features |= 4;
  1417. if (enc->use_palette_) stats->lossless_features |= 8;
  1418. stats->histogram_bits = enc->histo_bits_;
  1419. stats->transform_bits = enc->transform_bits_;
  1420. stats->cache_bits = enc->cache_bits_;
  1421. stats->palette_size = enc->palette_size_;
  1422. stats->lossless_size = (int)(VP8LBitWriterNumBytes(bw) - byte_position);
  1423. stats->lossless_hdr_size = hdr_size;
  1424. stats->lossless_data_size = data_size;
  1425. }
  1426. Error:
  1427. VP8LEncoderDelete(enc);
  1428. return err;
  1429. }
  1430. int VP8LEncodeImage(const WebPConfig* const config,
  1431. const WebPPicture* const picture) {
  1432. int width, height;
  1433. int has_alpha;
  1434. size_t coded_size;
  1435. int percent = 0;
  1436. int initial_size;
  1437. WebPEncodingError err = VP8_ENC_OK;
  1438. VP8LBitWriter bw;
  1439. if (picture == NULL) return 0;
  1440. if (config == NULL || picture->argb == NULL) {
  1441. err = VP8_ENC_ERROR_NULL_PARAMETER;
  1442. WebPEncodingSetError(picture, err);
  1443. return 0;
  1444. }
  1445. width = picture->width;
  1446. height = picture->height;
  1447. // Initialize BitWriter with size corresponding to 16 bpp to photo images and
  1448. // 8 bpp for graphical images.
  1449. initial_size = (config->image_hint == WEBP_HINT_GRAPH) ?
  1450. width * height : width * height * 2;
  1451. if (!VP8LBitWriterInit(&bw, initial_size)) {
  1452. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1453. goto Error;
  1454. }
  1455. if (!WebPReportProgress(picture, 1, &percent)) {
  1456. UserAbort:
  1457. err = VP8_ENC_ERROR_USER_ABORT;
  1458. goto Error;
  1459. }
  1460. // Reset stats (for pure lossless coding)
  1461. if (picture->stats != NULL) {
  1462. WebPAuxStats* const stats = picture->stats;
  1463. memset(stats, 0, sizeof(*stats));
  1464. stats->PSNR[0] = 99.f;
  1465. stats->PSNR[1] = 99.f;
  1466. stats->PSNR[2] = 99.f;
  1467. stats->PSNR[3] = 99.f;
  1468. stats->PSNR[4] = 99.f;
  1469. }
  1470. // Write image size.
  1471. if (!WriteImageSize(picture, &bw)) {
  1472. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1473. goto Error;
  1474. }
  1475. has_alpha = WebPPictureHasTransparency(picture);
  1476. // Write the non-trivial Alpha flag and lossless version.
  1477. if (!WriteRealAlphaAndVersion(&bw, has_alpha)) {
  1478. err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1479. goto Error;
  1480. }
  1481. if (!WebPReportProgress(picture, 5, &percent)) goto UserAbort;
  1482. // Encode main image stream.
  1483. err = VP8LEncodeStream(config, picture, &bw, 1 /*use_cache*/);
  1484. if (err != VP8_ENC_OK) goto Error;
  1485. // TODO(skal): have a fine-grained progress report in VP8LEncodeStream().
  1486. if (!WebPReportProgress(picture, 90, &percent)) goto UserAbort;
  1487. // Finish the RIFF chunk.
  1488. err = WriteImage(picture, &bw, &coded_size);
  1489. if (err != VP8_ENC_OK) goto Error;
  1490. if (!WebPReportProgress(picture, 100, &percent)) goto UserAbort;
  1491. // Save size.
  1492. if (picture->stats != NULL) {
  1493. picture->stats->coded_size += (int)coded_size;
  1494. picture->stats->lossless_size = (int)coded_size;
  1495. }
  1496. if (picture->extra_info != NULL) {
  1497. const int mb_w = (width + 15) >> 4;
  1498. const int mb_h = (height + 15) >> 4;
  1499. memset(picture->extra_info, 0, mb_w * mb_h * sizeof(*picture->extra_info));
  1500. }
  1501. Error:
  1502. if (bw.error_) err = VP8_ENC_ERROR_OUT_OF_MEMORY;
  1503. VP8LBitWriterWipeOut(&bw);
  1504. if (err != VP8_ENC_OK) {
  1505. WebPEncodingSetError(picture, err);
  1506. return 0;
  1507. }
  1508. return 1;
  1509. }
  1510. //------------------------------------------------------------------------------